Wrong element is removed after leaving method which used std::erase succesfully - c++

I am working on a graphics engine. The engine has a std::vector of drawables. A Drawable is an object which contains a Model and a DrawableObject, which in turn holds a shader program and a bunch vertices from a 2D or 3D model. Adding new Drawables goes well, the problem occurs when I try to remove a Drawable. The last Drawable will always be removed and the second to last will have its values changed.
Code
Drawable.h
class Drawable
{
public:
Drawable& operator=(const Drawable& other)
{
Drawable tmp(other);
std::swap(model, other.model);
std::swap(drawableObject, other.drawableObject);
return *this;
}
Drawable(domain::Model& model, DrawableObject& drawableObject) :
model(model),
drawableObject(drawableObject)
{}
domain::Model& model;
DrawableObject& drawableObject;
};
game.cpp
void Game::init_game()
{
human = domain::Model(glm::vec3(0, 0, -3));
moveables.push_back(&human);
room = domain::Model(glm::vec3(0, 0, -10));
props.push_back(&room);
cube = domain::Model(glm::vec3(0, 0, 0));
props.push_back(&cube);
}
void Game::init_graphics_engine()
{
// ... load graphics models
// add drawables
graphicsEngine->add(cube, Drawable::CUBE);
graphicsEngine->add(human, Drawable::HUMAN);
graphicsEngine->add(room, Drawable::ROOM);
graphicsEngine->add(topDownScene->cursor, Drawable::MARKER);
}
graphics_engine/engine.cpp
void Engine::add(domain::Model& model, unsigned int object)
{
auto drawableObject = drawableObjects[object];
// make sure not to add a model that already is represented
auto it = std::find_if(drawables.begin(), drawables.end(), [&model](Drawable& drawable) {return &drawable.model == &model;});
if(drawableObject && it == drawables.end())
drawables.push_back(Drawable(model, *drawableObject));
}
void Engine::remove(domain::Model& model)
{
auto predicate = [&model](Drawable& drawable)
{
return &drawable.model == &model;
};
drawables.erase(std::remove_if(drawables.begin(), drawables.end(), predicate), drawables.end());
}
Scenes
This is what the scene looks like when I start the application:
This is what the scene looks like after attempting to erase the small 'human' cube in the middle:
The code removes the last Drawable, which is the white marker, instead of the 'human' cube, and changed the z position of the room. This almost always happens, it removes the last element and changed the z of the second to last. It only works if I add the 'human' cube last in the init method.
Breakpoints
Before removing the object:
After removing the object:
This is correct.
Leaving the remove method and taking a look in the render loop:
Somehow changed.

I changed the class members to pointers. Now it works. The comments were right, I didn't do anything with the tmp variable.
class Drawable
{
public:
Drawable& operator=(const Drawable& other)
{
this->model = other.model;
this->drawableObject = other.drawableObject;
return *this;
}
Drawable(domain::Model* model, std::shared_ptr<DrawableObject> drawableObject) :
model(model),
drawableObject(drawableObject)
{}
domain::Model* model;
std::shared_ptr<DrawableObject> drawableObject;
};

Related

Fixing an object oriented wrapper I am creating for bindbc.sfml

I am trying to create object oriented wrappers around bindbc.sfml, this is because I don't like the C-style syntax of CSFML.
The C-style syntax is not right -- in my opinion -- for an object oriented language. Dealing with pointers all the time is also unsafe.
This is not to say that CSFML isn't good -- it's great, and I've made some apps using bindbc-sfml. I just want to extend it to my liking with object oriented wrappers that can more closely match the C++ SFML syntax.
For the wrappers, I created a Shape class. This Shape class is seen in the original C++ SFML implementation:
class Shape : Transformable, Drawable {
void setTexture(sfTexture* texture, bool resetRect) {
ptr.sfShape_setTexture(texture, resetRect);
}
void setTextureRect(IntRect rect) {
ptr.sfShape_setTextureRect(rect.to_sfIntRect());
}
void setFillColor(Color color) {
ptr.sfShape_setFillColor(color.to_sfColor());
}
void setOutlineColor(Color color) {
ptr.sfShape_setOutlineColor(color.to_sfColor());
}
void setOutlineThickness(float thickness) {
ptr.sfShape_setOutlineThickness(thickness);
}
const(sfTexture)* getTexture() {
return ptr.sfShape_getTexture();
}
IntRect getTextureRect() {
return ptr.sfShape_getTextureRect().toIntRect();
}
Color getFillColor() {
return ptr.sfShape_getFillColor().toColor();
}
Color getOutlineColor() {
return ptr.sfShape_getOutlineColor().toColor();
}
float getOutlineThickness() {
return ptr.sfShape_getOutlineThickness();
}
size_t getPointCount() nothrow {
return ptr.sfShape_getPointCount();
}
Vector2f getPoint(size_t index) nothrow {
return ptr.sfShape_getPoint(index).toVector2f_noThrow();
}
FloatRect getLocalBounds() {
return ptr.sfShape_getLocalBounds().toFloatRect();
}
FloatRect getGlobalBounds() {
return ptr.sfShape_getGlobalBounds().toFloatRect();
}
private sfShape* ptr;
}
The sfShape pointer isn't currently initialized, I'll get to that issue soon.
As you can see, Shape extends the Transformable class and the Drawable interface. This again roughly matches what's seen in SFML. SFML.NET also did a similar wrapper for their CSFML C# bindings. What's great about SFML.NET is that you don't even know that you're using CSFML, this is because it feels just like C++ SFML.
Now, I will create a RectangleShape which will be a subclass of the Shape class:
(Btw I took a lot of inspiration from SFML.NET when it comes to these wrappers.)
class RectangleShape : Shape {
this(Vector2f size) {
_size = size;
setSize(_size);
}
Vector2f getSize() {
return _size;
}
void setSize(Vector2f size) {
_size = size;
}
override {
size_t getPointCount() {
return 4;
}
Vector2f getPoint(size_t index) {
final switch (index) {
case 0:
return Vector2f(0, 0);
case 1:
return Vector2f(_size.x, 0);
case 2:
return Vector2f(_size.x, _size.y);
case 3:
return Vector2f(0, _size.y);
}
}
}
private Vector2f _size;
}
As you can see, the Rectangle class only overrides the getPointCount and getPoint methods.
These are the methods that the superclass - Shape - will use to construct the shape object for it to actually be drawable.
Now, let us add the following code to the Shape class so that we can construct a Shape via these two methods, which we assume that the child provides us a good implementation for:
class Shape : Transformable, Drawable {
this() {
ptr = sfShape_create(&getPointCount, &getPoint, cast(void*)this);
}
extern(C) private static ulong getPointCount(void* data) nothrow {
return (cast(Shape)data).getPointCount();
}
extern(C) private static sfVector2f getPoint(size_t index, void* data) nothrow {
return (cast(Shape)data).getPoint(index).to_sfVector2f_noThrow();
}
I hear you asking, what's going on here?
We are providing two callbacks to the getPointCount and getPoint methods via function pointers, and we're passing in the current object to the data void* pointer. It's kind of hard to understand, but if you read through it carefully you should get a rough idea of what's going on.
Now, when we create a new instance of Rectangle, I will assume that the constructor will be called, the sf_shape ptr will be initialized correctly (as it will be utilizing the crucial getPoint and getPointCount methods) and everything will be OK.
This is the following test code I had:
void main() {
loadSFML();
RectangleShape rectangleShape = new RectangleShape(Vector2f(50, 50));
rectangleShape.setPosition(Vector2f(50, 50));
rectangleShape.setFillColor(Color.Blue);
RenderWindow renderWindow = new RenderWindow(sfVideoMode(500, 500), "Tests", sfWindowStyle.sfDefaultStyle, null);
sfEvent event;
while (renderWindow.isOpen()) {
while (renderWindow.pollEvent(&event)) {
if (event.type == sfEventType.sfEvtClosed) {
renderWindow.close();
}
}
renderWindow.clear(Color.Yellow);
renderWindow.ptr.sfRenderWindow_drawShape(rectangleShape.ptr, null);
renderWindow.display();
}
}
I would read through this line by line to get a good idea of what's going on.
Really, for demonstration purposes, we're using the renderWindow's ptr variable for drawing. When I can get this to work I will create wrapper functions so that it's nicer to use, but for now it's not important.
What I'd expect to pop up on screen is a 50x50 rectangle, filled with a blue color, at the position 50x50 on the screen.
Upon running the application, I don't see anything -- it's just a yellow screen.
I am very confused why this is the case, it seems like I've done everything fine, but I've obviously made a mistake somewhere in my implementation. I don't know specifically if it's an issue on my end, or a bug in bindbc-sfml, but this issue has infuriated me, because I am not getting what I expected to show up on screen.
Fixed it by calling sfShape_update here:
class RectangleShape : Shape {
this(Vector2f size) {
_size = size;
setSize(_size);
ptr.sfShape_update();
}

Drawing from a vector of sprites SFML

Every object in my game world has a vector of sprites that visually represent that object. My issue is that i cant seem to draw them properly on the screen:
This is the drawable object that every drawable inherits from:
class Drawable {
private:
static vector<Drawable*> sprites;
protected:
vector<sf::Texture> myTextures;
vector<sf::Sprite> mySprites;
public:
Drawable();
static vector<Drawable*> getSprites();
void draw(sf::RenderWindow&) const;
};
And its .cpp:
vector<Drawable*> Drawable::drawables;
Drawable::Drawable() {
drawables.push_back(this);
}
vector<Drawable*> Drawable::getDrawables() {
return drawables;
}
void Drawable::draw(sf::RenderWindow& window) const {
for (auto sprite : mySprites) {
window.draw(sprite);
}
}
Example of a object that inherits from drawable:
class Terrain : public Drawable {
private:
void loadSprite(string);
public:
Terrain(string);
};
and its .cpp:
Terrain::Terrain(string fileName) {
loadSprite(fileName);
}
void Terrain::loadSprite(string fileName) {
sf::Texture texture;
texture.loadFromFile(fileName);
myTextures.push_back(texture);
sf::Sprite sprite;
sprite.setTexture(texture);
mySprites.push_back(sprite);
}
In this case the terrain sprite is only a white-box during run-time. I think this is because the "texture" and "sprite" var in loadSprite gets destroyed after the method goes out of scope.
I know i could probably solve the issue by saving "texture" and "sprite" in the terrain-class (not creating them locally in a method like now). But this seems unnecessary to me, cant i store them in the vectors mySprites and myTextures instead?
I think this is because the "texture" and "sprite" var in loadSprite gets destroyed after the method goes out of scope.
You're right. sf::Sprite stores a reference to sf::Texture. loadSprite would work one-time only if you'd do sprite.setTexture(myTextures.back());. But std::vector's elements will be reallocated as you push_back. I recommend std::vector<std::shared_ptr<sf::Texture>> for simplicity.
Better yet, load all the textures at once, so that you don't have duplicate ones and use IDs to refer to them.

Recommended way to create an inversion of a bool value returned by a class with same interface in C++?

I have a use case that involves collections of sensor objects that return a bool (indicating the state of the sensor). In some cases the collection object is interested in the inverse of a the sensor value, but I want to use the same interface for both cases so that the collection doesn't need to track this. An example might be
Result = sensorA | not(sensorB)
where the the value of sensorA and not(sensorB) are accessed using the same interface. I've come up with a couple of solutions for this, none of which seem as simple as I originally expected the problem to be.
Firstly, I can realize the goal by creating another class that inherits from the same base interface and performs the translation. However this seems a little clunky as I have to instantiate a inverting object for each sensor:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class ObservedSensorBase
{
public:
virtual bool getState(void) = 0;
protected:
ObservedSensorBase() { inverted = new InvertSensor(this); }
};
class ConcreteSensor : public ObservedSensorBase
{
public:
ConcreteSensor(bool state) :mState(state) {}
bool getState(void) { return mState; }
private:
bool mState;
};
class InvertSensor : public ObservedSensorBase
{
public:
InvertSensor(ObservedSensorBase *sensor) :mSensor(sensor) {}
bool getState(void) { return !mSensor->getState(); }
private:
ObservedSensorBase *mSensor;
};
int main()
{
ConcreteSensor sensorA(true);
InvertSensor notSensorA(&sensorA);
vector <class ObservedSensorBas*> sensors;
sensors.push_back(&sensorA);
sensors.push_back(&notSensorA);
for (class ObservedSensorBase* it : sensors)
{
cout << it->getState() << endl;
}
return 0;
}
Prints:
1
0
Ideally I'm looking for the original concrete sensor class to be able to return the inverted functionality. I can do this if I add a public class to each concrete sensor:
class ConcreteSensor : public ObservedSensorBase
{
public:
ConcreteSensor(bool state) :mState(state),inv(this) {}
bool getState(void) { return mState; }
class InvertSensor inv;
private:
bool mState;
};
...
sensors.push_back(&sensorA.inv);
Prints
0
but this seems a little cumbersome, as its a new variable in each concrete class. I can't add it to the base class, as InvertSensor inherits from the base, so InvertSensor isn't fully defined and can't be instantiated (at least I haven't been able to do so).
The other approach I've investigated is using an object factory:
ObservedSensorBase *invertFactory(ObservedSensorBase *sensor)
{
static map<ObservedSensorBase *, ObservedSensorBase *> m;
// Create an instance of the inverter for this object if it doesn't already exist
if (m.find(sensor) == m.end())
{
m[sensor] = new InvertSensor(sensor);
}
// Provide the inverting object for the passed sensor
return m[sensor];
}
...
sensors.push_back(invertFactory(&sensorA));
Prints
0
Is there another solution that I'm missing? Ideally something inherent in the class that each concrete instance can inherit from, but at this point it's become a bit of an intellectual challenge as well :)
--- EDIT ---
Thanks for the comments so far.
To clarify the objective better, this is for a little project for an Arduino to control signals on a model railroad. For the purposes here, assume that the signals can only show green and red. They show red when any track occupancy circuit or switch orientation that the signal is 'protecting' against indicates its unsafe for a train to proceed (and green otherwise).
Both the track detection and switch orientation objects would be concrete instances of the base sensor, but it's the switch orientation that creates this use case. If we have two signals, each of which is 'protecting' the two approaches to the two-track end of a single switch, one signal will want to use the switch orientation sensor 'as-is', and the other will want to use the inverted sensor value (to represent which way the switch is thrown).
I'm wanting to be able to invert the sensors' state representation when loading the into the signal object that holds them to avoid having to store a separate 'invert this signal' indication in the signal object, or manually instantiate a separate object that performs the inversion.
So something like
Signal1 protects SensorA (trackA) and Switch B
Signal2 protects SensorC (trackC) and not(SwitchB)
Here is an example of the signal (a container of sensors that just ORs them all together) e.g.
class Signal
{
public:
void protect(class ObservedSensorBase *sensor) { mSensors.push_back(sensor); }
void periodicLoop(void)
{
bool anyProtectedSensorActive = false;
for ( auto it = mSensors.begin();
it != mSensors.end() && !anyProtectedSensorActive;
++it)
{ anyProtectedSensorActive |= (*it)->getState(); }
if(anyProtectedSensorActive)
{ /* set Signal Red */ }
else
{ /* set signal Green */ }
}
private:
vector <class ObservedSensorBase*> mSensors; // protected sensors
};
...
Signal signal1;
Signal signal2;
signal1.protect(&sensorA);
signal1.protect(&sensorB);
signal1.protect(&sensorC);
signal1.protect(&notSensorB);
However, after playing with #Jason C's recommendation to put something in the base class (which I couldn't get working prior to asking the question, or after his suggestion) it occured to me that I could create
// Invert Sensor and ObservedSensorBase are declared as above...
class InvertedSensorBase : public ObservedSensorBase
{
public:
InvertedSensorBase() : inverted(this) {}
class InvertSensor inverted;
};
// Change the inheritance of the concrete observer
//class ConcreteSensor : public ObservedSensorBase
class ConcreteSensor : public InvertedSensorBase
And now SensorA.inverted seems to fit the bill very well.
Of course, since this is mostly a side project to return to C++ and learn C++11 after a long absence, if anyone has alternate suggestions about any point, I'd be more than happy to see them.
If you want a really no-effort solution you could store pair<ObservedSensorBase*,bool>'s in your container, where the boolean is whether you want to invert or not, and just have your logic invert the value based on that bool:
typedef pair<ObservedSensorBase *,bool> SensorWithFlag; // ...or something
vector<SensorWithFlag> sensors;
sensors.push_back(SensorWithFlag(sensor1, true)); // invert
sensors.push_back(SensorWithFlag(sensor2, false)); // don't invert
// then later when you use it, say 'n' is an index:
bool state = (sensors[n].first->getState() != sensors[n].second);
But if not, I suppose you could do the inversion in the base:
class ObservedSensorBase {
...
public:
void setInvertState (bool invertState) {
invertState_ = invertState;
}
bool getState () {
return invertState_ != getState_(); // != is xor
}
protected:
virtual bool getState_ () = 0;
private:
bool invertState_;
};
Then all subclasses implement getState_ instead of getState, and all have the ability to have their results inverted by setting setInvertState(true).
But this seems weird. Perhaps you could add some more details about how your containers are using these values. I feel like there may be a better way in general to structure your program and algorithms.
Another option is to use your "inverting filter" option but manage it in the base:
class ObservedSensorBase {
...
public:
ObservedSensorBase (...) : inv_(this) { ... }
InvertSensor * inverted () { return &inv_; }
private:
InvertSensor inv_;
};
Then you can just add mySensor->inverted() to your container when needed. This has the following caveats:
Do not call any virtual methods of ObservedSensorBase from InvertSensor's constructor.
Do not call any methods of InvertSensor that may lead to virtual base methods being called, from ObservedSensorBase's constructor.
Pointer returned by inverted() is invalidated when sensor is deleted.
The first two points are important because this won't be fully constructed yet when constructing subclasses.
This way, every sensor automatically has an inverted version of itself that comes along with it, and you don't have to manage them manually.
Yet another solution is to create wrappers around sensor objects, but keep them simple and store them directly in containers instead of storing pointers to them, to keep memory management easier. For example:
class SensorValue {
public:
SensorValue (ObservedSensorBase *s, bool invert)
: s_(s), i_(invert) { }
bool getState () { return i_ != s_->getState(); }
ObservedSensorBase * sensor () { return s_; }
private:
ObservedSensorBase *s_;
bool i_;
};
// then later, let's say you have some sensors:
ObservedSensorBase *sensor1 = ...;
ObservedSensorBase *sensor2 = ...;
// you can have containers like this:
vector<SensorValue> collection1, collection2;
// and you can use normal/inverted states as needed:
collection1.push_back(SensorValue(sensor1, false)); // normal values
collection1.push_back(SensorValue(sensor2, false));
collection2.push_back(SensorValue(sensor1, true)); // and inverted
collection2.push_back(SensorValue(sensor2, true)); // at the same time
// if you ever need the sensor object itself you can use SensorValue#sensor:
for (vector<SensorValue>::iterator i = collection1.begin();
i != collection1.end(); ++ i)
{
bool state = i->getState(); // normal or inverted, transparent to us here
ObservedSensorBase *sensor = i->sensor(); // can be used for whatever.
// note that i->getState() != i->sensor()->getState() if we're
// using an inverted SensorValue.
}
// and they aren't pointers, you can just do this with no leaks:
collection1.clear();
collection2.clear();
// although of course you still do this for sensor cleanup:
delete sensor2;
delete sensor1;
This is sort of conceptually like your inverted sensor object approach except SensorValue isn't an ObservedSensorBase, it's lightweight and cheaply copyable, and you can just store them directly in containers instead of passing around pointers.
It's very similar to storing e.g. pair<ObservedSensorBase*,bool> (where you store sensor and invert flag) in your containers instead, except unlike pair it gives you a convenient getState() member, and has some semantic meaning.

How to pass arguments to draw() method - FLTK

I´m new to FLTK and currently facing the following problem:
I have a class PointModel, which stores points with x- and y-coordinates, a class View, which needs to call update(), everytime the coordinates in the PointModel change (Observer Pattern) and draw them and finally a class MyBox, where the coordinates should be drawn in.
View is derived from Fl_Window. MyBox is derived from Fl_Box and part of View.
Therefore I need to know, how to pass the point coordinates from a member function (void update()) of View to the draw method of MyBox.
I´m trying to typecast the user_data pointer I get to View* in case to be able to get the PointModel, holding the point coordinates. But the window closes after calling the draw() method.
Maybe I only get a NULL-Pointer here? Unfortunately I can´t check it through debugging, because somehow Eclipse doesn´t break at the breakpoints now..
Any solutions, hints what I´m doing wrong or possible alternatives?
Thanks in advance!
Here some pieces of my code:
View.cpp:
class MyBox : public Fl_Box {
void draw() {
Fl_Box::draw();
View *v1 = (View*)this->parent();
if(v1 != NULL) {
int lastX = v1->getPointModel()->getLastX();
int lastY = v1->getPointModel()->getLastY();
int currentX = v1->getPointModel()->getCurrentX();
int currentY = v1->getPointModel()->getCurrentY();
fl_color(FL_WHITE);
fl_line(lastX, lastY, currentX, currentY);
}
}
public:
MyBox(int X,int Y,int W,int H,const char*L=0) : Fl_Box(X,Y,W,H,L) {
box(FL_FLAT_BOX);
}
};
View::View(*arguments*) :Fl_Window(540,650,"View1") {
begin();
MyBox box(20,20,500,500," ");
box.box(FL_UP_BOX);
box.color(0x00000000);
//more widgets
end();
show();
Fl::add_timeout(3.0, Timer_CB, (void*)this);
Fl::run();
}
edit: I updated the code to running version
Well, MyBox.draw() will be called before you call add_timeout(). user_data() will give you NULL most likely... You could add a check for NULL in there. Something like:
void draw() {
Fl_Box::draw();
void* ptr = user_data();
if (ptr) {
// do stuff here...
}
Second possible problem is this->parent()->user_data(); . Parent of your MyBox object is the Fl_Window object (actually, your View object, which is a Fl_Window), and user_data() will always return NULL for it I think...
The easiest way to pass any object to your widget is to use user_data() method:
box.user_data(&myview); // after this box.user_data() will return a View*

Exposing multiple iterable interfaces

A Scene contains a list of Shape.
Each Shape contains:
Its std::vector of Vertex (with surface normal, texcoord, 3-space position)
Its std::vector of Triangle (tied up vertices, for mesh intersection)
I'd like to make the Scene object iterable both as a collection of Vertex, and a collection of Triangle, in a not-so-messy way.
Currently what is required is to walk the triangles: (C# syntax here):
foreach( Shape shape in Scene )
{
foreach( Mesh mesh in shape.meshGroup.meshes )
{
foreach( Triangle tri in mesh.tris )
{
// work with tri
}
}
}
The triple nested for isn't nice to see, and of course C++ syntax is hella worse, using either counters i, j and k or using ::iterators..
To access each Vertex:
foreach( Shape shape in Scene )
{
foreach( Mesh mesh in shape.meshGroup.meshes )
{
foreach( Vertex v in mesh.verts )
{
// work with v
}
}
}
Since walking all Triangles/Vertices is expensive to begin with, what's the best way to do this? (Assume its necessary to hit every Triangle / Vertex, so no need for spatial subdivision algorithms etc)
You can use any C++ 0x features (VS-2010 enabled), lambda included.
You could create functions which iterate over all the elements and call a function object:
template <typename F>
inline void for_each_vertex(Scene& scene,F f)
{
for (Shape& shape : scene) {
for (Mesh& mesh : shape.meshGroup.meshes) {
for (Vertex& vertex : mesh.verts) {
f(vertex);
}
}
}
}
template <typename F>
inline void for_each_triangle(Scene& scene,F f)
{
for (Shape& shape : scene) {
for (Mesh& mesh : shape.meshGroup.meshes) {
for (Triangle& triangle : mesh.tris) {
f(triangle);
}
}
}
}
Now you can do
for_each_vertex(scene,[](Vertex& vertex)(/* work with vertex */});
for_each_triangle(scene,[](Triangle& triangle)(/* work with triangle */});
This should have the same performance as your original code, but you won't have to write the same loop structure multiple times throughout your program.
What I usually do to expose separate 'logical containers' into a big (multi-)container class:
I define a method 'getMeshRange(),getShapeRange()` etc.
If you use the boost range library, you could return boost::iterator_range<const Shape*>, boost::sub_range<std::vector<Vertex> > etc.
In practice, IIRC, to satisfy the Range concept, you can just return std::pair<const_iterator, const_iterator>.
A range can be used as follows:
for (It it = std::begin(X.getMeshRange()); it!= std::end(X.getMeshRange()); ++it)
{
// use *it
}
or in C++0x
for (auto& mesh : X.getMeshRange())
{
// use mesh
}
With Boost Range Algorithm, you can do anything that you could with a 'regular' container:
const Shape& shape = *std::min_element(X.getShapeRange());
If all the processing is done in the inner loop, you could create a custom iterator which iterates over all three levels, and produces (Shape*,Mesh*,Vertex*) triples, handling the logic to move e.g. to the next Mesh once all the Vertexes have been iterated over for the current Mesh.
If you want to do some processing in the middle or outer loops, you could add some hooks, or for instance return a (Shape*,NULL,NULL) triple for the first time through a new Shape.