# Unity [C++] custom iterators

This topic is 3759 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have a 3D array representing Z, Y and X like
vector< vector< vector<T> > > myArray
where T is some type. Now if I form an iterator
vector<T>::iterator xIter
xIter = myArray[z][y].begin();
I can loop over the x dimension of the array. Now if I have a function that iterates over x performing some action (say, gaussian blur in 1D) I'd define it something like
doBlur(vector<T>::iterator xIterBegin, vector<T>::iterator xIterEnd);
which would in place blur along a line along the x-axis. Based on responses to this thread, I can define a templated function to take *any* iterator. So, with all this in mind, I can see how to write my 1D blur function using templates, allowing me to perform a blur with multiple calls with different iterators, as long as I can pass in iterators that iterate over the x, y, z coordinates as appropriate. What I can't see is what these iterators should be. Thinking about an iterator for the y axis, perhaps something like
vector< vector<T> >::iterator yIter
yIter = myArray[z].begin();
but this doesn't quite work as dereferencing the iterator gives me vector<T> not T, as I'd like. How do I write a custom iterator to give me this functionality? Do I have to write a custom iterator or is there a simpler, clever, way to do it? Many TIA

##### Share on other sites
Something you seem to have overlooked when considering y-axis iteration is that there are many 'columns' down which you could iterate.
What you're trying to do is actually disregarde the 'column-identifier', which turns out to be the x-component, and this just isn't practical.

Side note:
You might wonder why you can disregard the y (or even z) components for iterating along the x-axis, the answer is that this largely down to the way that you've set up your nested vectors such that the x-axis vector is the vector that actually contains the data.

Well it turns out you have a few ways to solve this.

One way, which isn't entirely unreasonable I suppose, is to write custom iterators. This might make (more) sense if you wrapped those nested vectors into a new container class, call it CubeArray for example, then you can have a custom 3D iterator that you can access like normal: CubeArray<T>::iterator.

Writing iterators isn't hard, you just need to provide some technique to... well... iterate. Depending on the function that you provide your iterator can be a forwards iterator, backwards iterator, random access iterator etc.

If you're interested in writing STL compliant iterators then you need to adhere to their interface requirements. For example here you can find the details of a bi-directional iterator, if you provide a class with those functions then it's a fully compliant iterator.

However,
Other solutions certainly do exist; one way might be to condense your container down into a single vector:

vector<T> myArray

Note: You might actually gain some efficiency from a single vector, but that's not why I'm suggesting it.

You can still pretend this is a 3-dimensional array if you know the width, height and depth, although actually you don't need the depth for accessing elements:

myArray[(z * height + y) * width + x]

This now means that all mutable iterators will be of type vector<T>::iterator.

In order to allow the doBlur function to do its job it needs to be augmented with an offset argument; it must now also require that its iterators be random-access iterators (vector iterators are random access, so it's fine).

This offset argument (occasionally called the 'pitch', I think) is the offset from one element to the next.
So (if),
the x-axis components are contiguous, it's an offset of: 0,
the y-axis components are width distance apart, it's an offset of: width,
the z-axis components are width * height distance apart, it's an offset of: width * height.

To see this in action:

template <class RandomAccessIter>
void doBlur(RandomAccessIter xIterBegin, RandomAccessIter xIterEnd, int offset);

vector<T>::iterator yIterBegin = myArray.begin() + ((z1 * height + y1) * width + x1);
vector<T>::iterator yIterEnd = myArray.begin() + ((z2 * height + y2) * width + x2);
int offset = width;
doBlur(yIterBegin, yIterEnd, offset);

It would probably do to write a utility function to return the iterator at a given x, y, z position.

##### Share on other sites
Yes, there is a simpler way: use a more powerful (and more efficient) representation of the 3D array - boost::multi_array.

It holds things in a single allocated space (as far as I can tell from the documentation), and makes sure the array is "rectangular". Basically, it computes an index based on the dimensions and bounds of the array and indexes into a single vector. That avoids wasting lots of space (unused vector reserve capacity; redundant "per-row" vector object bookkeeping data).

It also provides a way to create "views" of parts of the array, in each dimension.

typedef boost::multi_array<Thing, 3> grid;typedef typename grid::array_view<1>::type column;grid myArray(boost::extents[5][5][5]); // or whatever size you wantedtypedef grid::index_range range;grid::index_gen indices;// Take 1D "core samples" in each direction, going through the middle of the cube.column x22 = myArray[indices[range(0, 5)][2][2]];column y22 = myArray[indices[2][range(0, 5)][2]];column z22 = myArray[indices[2][2][range(0, 5)]];// assuming we have template <typename Iterator> void blur(Iterator begin, Iterator end), blur each sample:blur(x22.begin(), x22.end());blur(y22.begin(), y22.end());blur(z22.begin(), z22.end());

Reference.

##### Share on other sites
Of course boost::multi_array essentially does the same thing that I suggested, except it wraps everything up for you in a nice clean interface. [smile]

I'm not a huge user of the boost libraries so I tend to forget to recommend it's components. I'd suggest you go for the boost solution, unless, like me, you're prone to reinventing the wheel.

##### Share on other sites
I've done the "flatten 3D to 1D" thing many times, usually with bog standard arrays rather than vectors but the same thing. I'm not sure about the boost::multi_array being able to do exactly what I want but that's my fault for not being clear enough in my original post. Although the blur example describes my problem it also implied a "rectangular" array; this isn't the case. The number of elements in each vector can (and is) different depending on the dimensional coordinate: the first 2 'outer' vectors are rectangular but the last, innermost, vector can change in length.

Can boost::multi_array be formed to hold vector<T> objects with the
typedef typename grid::array_view<1>::type column
acting as my outer iterator? I think it should but am not sure - I've never used boost before. Also, what is the speed likely to be like compared to a custom iterator?

I'll also have a look at writing my own iterator as an intellectual exercise :)

Thanks for you help.

##### Share on other sites
Quote:
 Original post by coordzI've done the "flatten 3D to 1D" thing many times, usually with bog standard arrays rather than vectors but the same thing. I'm not sure about the boost::multi_array being able to do exactly what I want but that's my fault for not being clear enough in my original post. Although the blur example describes my problem it also implied a "rectangular" array; this isn't the case. The number of elements in each vector can (and is) different depending on the dimensional coordinate: the first 2 'outer' vectors are rectangular but the last, innermost, vector can change in length.

So, make a boost::multi_array<2, std::vector<T> >. No problem.

Except... what does it mean to iterate over Y and Z dimensions, then? Say I want to iterate over X = 3, Z = 1... what if I hit a vector (indexed by X) that doesn't have enough elements?

• ### Similar Content

• Hello Guys!
Please share your experience, where is it better to find sales manager  specialists for indie team of 6 + people(remotely)?
Maybe someone has a good experience of cooperation with finding projects through sale managers(USA and Canada)?
Thank you
Best Regards
Alex Vovk
Co-Founder of Sixteen Squares
Alexander_Vovk@outlook.com

• Been a bit quiet recently, but we've been busy bug fixing and tweaking things... Now we have lots more 'Particle effects' in the game, specifically here the Flamethrower and Enemy attacks!

• Hi and thanks for reading, I have an issue with this reactive crosshair script, everything works fine until I start changing the offset. Give the script a go and you will see what I mean, when I do SetOffset(0f); it doesnt always set back to the origional state, if anyone can spot a fix I'd be super appreciative!
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ReactiveCrosshair : MonoBehaviour { [SerializeField] GameObject c_limb_prefab; private float center_offset = 0f; private float current_offset = 0f; private float max_offset = .5f; private int number_of_limbs = 4; private float limb_length = .05f; private float limb_width = .005f; private List<GameObject> c_limbs = new List<GameObject>(); public void SetupCrosshair(){ for (int i = 0; i < number_of_limbs; i++) { GameObject line_go = (GameObject)Instantiate (c_limb_prefab); line_go.transform.SetParent (this.transform); Vector3 limb_pos = new Vector3 (0f,0f,0f); //line_go.transform.position = limb_pos; line_go.transform.localPosition = limb_pos; LineRenderer line = line_go.GetComponent<LineRenderer>(); line.startWidth = limb_width; line.positionCount = 2; line.SetPosition (0, line_go.transform.localPosition + new Vector3(center_offset, 0f, 0f)); line.SetPosition (1, line_go.transform.localPosition + new Vector3(center_offset + limb_length, 0f, 0f)); line.useWorldSpace = false; c_limbs.Add(line_go.gameObject); } if (c_limbs != null) { OrientLimbs (); SetOffset (0f); } } public void OrientLimbs(){ for (int i = 0; i < c_limbs.Count; i++) { float rotation_step = 360f / (float)c_limbs.Count; c_limbs [i].transform.RotateAround (c_limbs[i].transform.position, c_limbs[i].transform.forward, 90f + (rotation_step * (float)i)); } } public void SetOffset(float _current_spread){ float offset = Mathf.Lerp (0f, max_offset, _current_spread); for (int i = 0; i < number_of_limbs; i++) { if (offset > current_offset) { Vector3 pos = c_limbs [i].transform.position + (c_limbs [i].transform.TransformDirection (Vector3.right) * offset); c_limbs [i].transform.position = pos; } if (offset < current_offset) { Vector3 pos = c_limbs [i].transform.position - (c_limbs [i].transform.TransformDirection (Vector3.right) * offset); c_limbs [i].transform.position = pos; } } Debug.Log ("SetOffset() offset: " + offset.ToString () + " _current_spread: " + _current_spread.ToString() + " localPos: " + c_limbs[1].transform.localPosition); current_offset = offset; } }

• So, as the title says i am trying to figure out a good way sync all that information with other players in Unity. My problem is that i can't come up with a good solution since i am used to creating classes for everything e.g. attachments are its own class and then the weapon would save a reference to that attachment. But since you can't send custom classes over [Command] & [ClientRPC] i am a little stuck. A solution for this would be giving each attachment for a slot a unique ID and then passing the ID to other player but i feel like that is very error prone if other ppl add a new attachment or the IDs get mixed up.
Is there a "standard" way that this is usually done that i am missing?
I am fairly new to programming so any help is appreciated!

• I'm looking for any team / people that need a programmer for their project. I'm looking to expand my portfolio which you can see Here. I'm more experienced with Unity but I can spend the time to learn new Engines if that's your preference. I have worked on Unreal Engine 4 before but I might take some time to re-learn it, if the project requires it. Feel free to DM here or use the contact info on my website.

• I'm working on a system for my game that will allow the player to stack pick ups in a queue. As one pick up expires, the next automatically activates. I'm having an issue though where if I pick up the first one, it activates fine, but if i pick up a second directly after it, it overrides the first one, activates the second one, and then once it has run it's course, everything goes back to normal gameplay, no first pick up. I'm not sure why this is happening. Hopefully someone can spot what I'm doing wrong in my code.
Here is the code for the pick up manager:
// Update is called once per frame void Update () { if (pickUpQueue.Count != 0 && !pickUpActive) { pickUpActive = true; pickUpQueue[0].ActivatePickUp(); } DeactivatePickUp(); } void DeactivatePickUp () { if (pickUpQueue.Count != 0 && pickUpActive) { Destroy (pickUpQueue [0]); pickUpQueue.RemoveAt (0); pickUpActive = false; } } And here is the PickUp:
public override void ActivatePickUp () { ball.GetComponent<Ball>().Speed = 2.0f; //increase ball speed... ball.GetComponent<Ball>().StartCoroutine(timer); //...set time that power up is active }
There is also a Base Pick Up:
public void OnCollisionEnter2D (Collision2D collision) { Vector2 tweak = new Vector2 (Random.Range(0f, 0.2f),Random.Range(0f, 0.2f)); this.gameObject.GetComponent<Rigidbody2D>().velocity += tweak; //if the pickup makes contact with the paddle or ball.... if (collision.gameObject.tag == "Paddle" || collision.gameObject.tag == "Ball") { GameObject.FindObjectOfType<GameManager>().GetComponent<PickUpManager>().pickUpQueue.Add(this); Destroy(gameObject); //...and finally destroy power up object } } As a side note, I am trying to find a solution to this that will work for all of my pickups. Some pickups are ammo based, some are timed.
• By D34DPOOL
Edit Your Profile D34DPOOL 0 Threads 0 Updates 0 Messages Network Mod DB GameFront Sign Out Add jobEdit jobDeleteC# Programmer for a Unity FPS at Anywhere   Programmers located Anywhere.
Posted by D34DPOOL on May 20th, 2018
Hello, my name is Mason, and I've been working on a Quake style arena shooter about destroying boxes on and off for about a year now. I have a proof of concept with all of the basic features, but as an artist with little programming skill I've reached the end of my abilities as a programmer haha. I need someone to help fix bugs, optomize code, and to implent new features into the game. As a programmer you will have creative freedom to suggest new features and modes to add into the game if you choose to, I'm usually very open to suggestions :).
What is required:
Skill using C#
Experience with Unity
Experience using UNET (since it is a multiplayer game), or the effort and ability to learn it
Compensation:
Since the game currently has no funding, we can split whatever revenue the game makes in the future. However if you would perfer I can create 2D and/or 3D assets for whatever you need in return for your time and work.
It's a very open and chill enviornment, where you'll have relative creative freedom. I hope you are interested in joining the team, and have a good day!

To apply email me at mangemason@yahoo.com

• Is there a way to automatically change the start position of an animation? I have a bunch of animations set up on 3D models in unity. The issue is that I need to move the 3D models, however when I do so the animation start positions are not updated and I have to do it manually.

Changing the transform of key frames is time consuming with the amount of animations I have, so I was wondering if there was a way to do it automatically?
• By MoreLion
hey all! We are looking for members for our Unity horror game!
Here’s the story:
After a deadly virus plunges the world into chaos killing 85% of the human population there are now what they call “zones” these zones are watched very closely by the surviving government, people are checked every day for the virus, even if you touch the spit or any human waste or fluids of the victim who is infected, you will die. But one day, people in the west zone start to go missing, 1 woman goes outside the walls to uncover the mystery, is there more to the virus than meets the eye?, That is where your story starts.
This game is not a long development game, I have loads other game ideas,
I will also allow you to have a bit of creative freedom if you wish to add or share a idea!
And no, it’s not a zombie game lol I feel like zombie games are too generic, in this game you will encounter terrifying beasts!
There is some concept art one of our concept artists have made
If interested email liondude12@gmail.com

• GOVERNOR is a modernized version of the highly popular series of “Caesar” games. Our small team has already developed maps, written specifications, acquired music and performed the historical research needed to create a good base for the programming part of the project.

Our ultimate goal is to create a world class multi-level strategic city building game, but to start with we would like to create some of the simpler modules to demonstrate proof of concept and graphical elegance.

We would like programmers and graphical artists to come onboard to (initially) create:

A module where Province wide infrastructure can be built on an interactive 3D map of one of the ancient Roman Provinces.
A module where city infrastructure can be built on a real 3D interactive landscape.
For both parts, geographically and historically accurate base maps will be prepared by our team cartographer. Graphics development will be using Blender. The game engine will be Unity.

More information, and examples of the work carried out so far can be found at http://playgovernor.com/ (most of the interesting content is under the Encyclopedia tab).

This project represents a good opportunity for upcoming programmers and 3D modeling artists to develop something for their portfolios in a relatively short time span, working closely with one of Canada’s leading cartographers. There is also the possibility of being involved in this project to the point of a finished game and commercial success! Above all, this is a fun project to work on.

Best regards,

• 11
• 20
• 12
• 11
• 38
• ### Forum Statistics

• Total Topics
631401
• Total Posts
2999866
×