• Advertisement

C++ Unique identifier for functions? (c++)

Recommended Posts

Hi

I've built a system for handling gui-popups that the player can answer to. The popup when called sets an "popup id" so i can check for that popup being answered elsewhere in the code like so:

if (timeToEat())
  callPopup(13, "What to eat?", "Cake", "Cookies!");

//elsewhere in code
if (popupAnswered(13,0)) // clicked first button in popup
  eatCake();

if (popupAnswered(13,1)) // clicked second button in popup
  eatCookiesDamnit();

So i just increase the id (in the example it's 13) when adding more popups. This isn't ideal of course but I don't want to add defines or enums to identify the popups. Adding new popups should be easy.

Another idea is to set a string value when calling a popup and check for that string to be exactly the same (the string will be the ID instead). Would that make sense? What else could I do? 

See below for string identifier example:

if (timeToEat())
  callPopup("popup_eat_question", "What to eat?", "Cake", "Cookies!");

//elsewhere in code
if (popupAnswered("popup_eat_question",0))
  eatCake();

if (popupAnswered("popup_eat_question",1))
  eatCookiesDamnit();

 

Edited by suliman

Share this post


Link to post
Share on other sites
Advertisement

Use a run time hash function that takes in text and converts it to a 16 or 32bit integer (unsigned) or something.  A Murmur hash could work here I think.

Share this post


Link to post
Share on other sites

Use callbacks/anonymous methods/lambdas/whatever C++'s modern equivalent is.

C# example since it's easier to demonstrate:

Popup("What to eat?", new string[]{"Cake", "Cookies!"}, x =>
{
	switch (x)
	{
		case 0: eatCake(); break;
		case 1: eatCookiesDammit(); break;
	}
});

 

Edited by Nypyren

Share this post


Link to post
Share on other sites

The benefits is that you get unique ids for your popups without having any compile time code struggle. Think of the case that you have a hard night and set an id twice so what would happen then? The hashing method prevents this unless you set two popups have the same name.

I would also suggest like @Nypyren did to use some kind of event-(system) to have your popups listen to. This will make life easier when you intend to trigger/listen to popup answers at other parts of your code

Share this post


Link to post
Share on other sites

I'm not understanding what the problem is.

You have an arbitrary collection of questions and associated answers, and you want to know whether you should index that collection using a string or an integer?  Simple.  Use a string, it's human-readable and can be assigned meaning, and is more useful during debugging.  Have a struct storing the question and answers, and store it in a std::map keyed by the string index.

Move on to the next problem.

Share this post


Link to post
Share on other sites
3 hours ago, suliman said:

@Mike2343
But what would be the actual benefit over using my crude string comparison method?

Providing you aren't having a problem in practice with your IDs, there is no problem in using it. In some cases using callbacks / enums / strings etc can be overengineering.

But it totally depends on how many popups you are dealing with, and the use case. If it starts with 3 popups, then you find you are using it more than you first envisaged and you become more likely to make mistakes with ID collisions etc. If there are only a few canned 'actions' in response to the selections, it may make sense to store these on the GUI object and make it 'self aware' rather than deal with lots of similar case statements.

Edited by lawnjelly

Share this post


Link to post
Share on other sites

If the number of popups get ‘big’ in your code base, the chances of errors creeping with just hard coded number like 13 will increase massively.  I would use enums or the string method (using maps) instead of hard-coded numbers.  Just imagine doing a global search in your code base for the number ‘13’ compared to ‘popup_eat_question’, to find all uses of your popup.
 

Edited by desiado

Share this post


Link to post
Share on other sites

Instead of manually assigning an ID, make the function automatically assign one, and return it. You can then store it in a named (!) variable and use that variable to refer to the popup, instead of obfuscating meaning behind an arbitrary integer literal (which is just an implementation detail).

auto cakePopup = CreatePopup("Cake?", "Ya", "Na");

if (PopupAnswered(cakePopup,1)) DoStuff();

Popups are all named, and relying on variables over literals should enforce proper scoping and dependency passing (currently you can read/write/modify a popup from anywhere at any time knowing just the integer ID - the dependency is passed through the programmer, which is not ideal, more formal/documented approach scales better).

If you want more flexibility, just do what you would do with any other regular object - declare it in a higher scope (even a global if that is what is required to fully replace your current approach, the point is to use the most local scope possible to minimize clutter), or store handles in a map (as in string=>handle type) or other indirection mechanism instead of a named variable (if you want to load the popups from a data file at runtime / let the user create their own / procedurally generate them - all could use something like that).

The actual type of the handle is less critical (use auto, and a using-declaration so you can easily change it in one place), so it becomes easier to turn it into a struct/class if you want to add more functionality (thats why I used "auto" for the type). An integer is fine, but sometimes adding some additional context, debugging data, or member functions is useful (keeping the type ambiguous leaves the door open for such additions).

Enums could be used to index into a map (if you find you need that indirection layer) of these runtime-allocated handles. Dont use enums to directly name specific handle values at compile time - it requires allocating handles at compile time (which is unnecessary, complex, and limiting, if you already have the more flexible runtime allocation as a foundation).

So you have the basic runtime handle allocation (create any number of popups at any time), and then you can have more than one tool for managing and passing those around (variables in various scopes, containers/maps, function parameters...). You can even use your current integer-indexed approach, just create an array/vector/map of handles somewhere (as in PopupAnswered(popupHandles[13])).

Share this post


Link to post
Share on other sites

As others have stated it's trivial to code up (few lines of code to generate the hash) and it's cost is done at compile time.  Depending how often you'll be doing the compares between strings it can get CPU costly whereas integer comparisons are nearly free comparatively. Plus you're less likely to accidentally, once your instances of IDs increases, to type the wrong ID.  As noticing you used the wrong string verses hardcoded integer is easier for most humans.

Share this post


Link to post
Share on other sites

The reason why you should use a hash instead of a string comparison, is because in some situations in an IMGUI, you might want to use integer IDs also.

For example, with dear-ImGui, (which uses stacks of run-time hashes to support 'scopes' for the IDs), here's some actual code for a list widget:

    for(size_t i = 0; i < gameStruct.packetLogger.Size(); ++i)
    {
        const PacketLogMsg &packet = gameStruct.packetLogger.Get(i);

        ImGui::PushID(i); //<<<<<< Adds a new ID to the stack.

        //=====================================================

        std::string sender = String::Format("%1:%2", {packet.address.address.toString(), IntToString(packet.address.port)});
        if(ImGui::SmallButton(sender))
        {
          if(filterAddress == NetworkAddress()) filterAddress = packet.address;
          else filterAddress = NetworkAddress();
        }
  
        ImGui::NextColumn();
  
        //=====================================================
        
  		//...tons more stuff...
  
        //=======================================================

        ImGui::NextColumn();

        ImGui::PopID(); //<<<<< Pop the ID stack
    }

 

Basically, using PushID(i) to give each loop of the for() it's own unique ID scope, so there's no conflict with, say, a Button that appears in the loop multiple times accidentally having clashing IDs.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By isu diss
      I'm trying to duplicate vertices using std::map to be used in a vertex buffer. I don't get the correct index buffer(myInds) or vertex buffer(myVerts). I can get the index array from FBX but it differs from what I get in the following std::map code. Any help is much appreciated.
      struct FBXVTX { XMFLOAT3 Position; XMFLOAT2 TextureCoord; XMFLOAT3 Normal; }; std::map< FBXVTX, int > myVertsMap; std::vector<FBXVTX> myVerts; std::vector<int> myInds; HRESULT FBXLoader::Open(HWND hWnd, char* Filename, bool UsePositionOnly) { HRESULT hr = S_OK; if (FBXM) { FBXIOS = FbxIOSettings::Create(FBXM, IOSROOT); FBXM->SetIOSettings(FBXIOS); FBXI = FbxImporter::Create(FBXM, ""); if (!(FBXI->Initialize(Filename, -1, FBXIOS))) { hr = E_FAIL; MessageBox(hWnd, (wchar_t*)FBXI->GetStatus().GetErrorString(), TEXT("ALM"), MB_OK); } FBXS = FbxScene::Create(FBXM, "REALMS"); if (!FBXS) { hr = E_FAIL; MessageBox(hWnd, TEXT("Failed to create the scene"), TEXT("ALM"), MB_OK); } if (!(FBXI->Import(FBXS))) { hr = E_FAIL; MessageBox(hWnd, TEXT("Failed to import fbx file content into the scene"), TEXT("ALM"), MB_OK); } FbxAxisSystem OurAxisSystem = FbxAxisSystem::DirectX; FbxAxisSystem SceneAxisSystem = FBXS->GetGlobalSettings().GetAxisSystem(); if(SceneAxisSystem != OurAxisSystem) { FbxAxisSystem::DirectX.ConvertScene(FBXS); } FbxSystemUnit SceneSystemUnit = FBXS->GetGlobalSettings().GetSystemUnit(); if( SceneSystemUnit.GetScaleFactor() != 1.0 ) { FbxSystemUnit::cm.ConvertScene( FBXS ); } if (FBXI) FBXI->Destroy(); FbxNode* MainNode = FBXS->GetRootNode(); int NumKids = MainNode->GetChildCount(); FbxNode* ChildNode = NULL; for (int i=0; i<NumKids; i++) { ChildNode = MainNode->GetChild(i); FbxNodeAttribute* NodeAttribute = ChildNode->GetNodeAttribute(); if (NodeAttribute->GetAttributeType() == FbxNodeAttribute::eMesh) { FbxMesh* Mesh = ChildNode->GetMesh(); if (UsePositionOnly) { NumVertices = Mesh->GetControlPointsCount();//number of vertices MyV = new XMFLOAT3[NumVertices]; for (DWORD j = 0; j < NumVertices; j++) { FbxVector4 Vertex = Mesh->GetControlPointAt(j);//Gets the control point at the specified index. MyV[j] = XMFLOAT3((float)Vertex.mData[0], (float)Vertex.mData[1], (float)Vertex.mData[2]); } NumIndices = Mesh->GetPolygonVertexCount();//number of indices MyI = (DWORD*)Mesh->GetPolygonVertices();//index array } else { FbxLayerElementArrayTemplate<FbxVector2>* uvVertices = NULL; Mesh->GetTextureUV(&uvVertices); int idx = 0; for (int i = 0; i < Mesh->GetPolygonCount(); i++)//polygon(=mostly triangle) count { for (int j = 0; j < Mesh->GetPolygonSize(i); j++)//retrieves number of vertices in a polygon { FBXVTX myVert; int p_index = 3*i+j; int t_index = Mesh->GetTextureUVIndex(i, j); FbxVector4 Vertex = Mesh->GetControlPointAt(p_index);//Gets the control point at the specified index. myVert.Position = XMFLOAT3((float)Vertex.mData[0], (float)Vertex.mData[1], (float)Vertex.mData[2]); FbxVector4 Normal; Mesh->GetPolygonVertexNormal(i, j, Normal); myVert.Normal = XMFLOAT3((float)Normal.mData[0], (float)Normal.mData[1], (float)Normal.mData[2]); FbxVector2 uv = uvVertices->GetAt(t_index); myVert.TextureCoord = XMFLOAT2((float)uv.mData[0], (float)uv.mData[1]); if ( myVertsMap.find( myVert ) != myVertsMap.end() ) myInds.push_back( myVertsMap[ myVert ]); else { myVertsMap.insert( std::pair<FBXVTX, int> (myVert, idx ) ); myVerts.push_back(myVert); myInds.push_back(idx); idx++; } } } } } } } else { hr = E_FAIL; MessageBox(hWnd, TEXT("Failed to create the FBX Manager"), TEXT("ALM"), MB_OK); } return hr; } bool operator < ( const FBXVTX &lValue, const FBXVTX &rValue) { if (lValue.Position.x != rValue.Position.x) return(lValue.Position.x < rValue.Position.x); if (lValue.Position.y != rValue.Position.y) return(lValue.Position.y < rValue.Position.y); if (lValue.Position.z != rValue.Position.z) return(lValue.Position.z < rValue.Position.z); if (lValue.TextureCoord.x != rValue.TextureCoord.x) return(lValue.TextureCoord.x < rValue.TextureCoord.x); if (lValue.TextureCoord.y != rValue.TextureCoord.y) return(lValue.TextureCoord.y < rValue.TextureCoord.y); if (lValue.Normal.x != rValue.Normal.x) return(lValue.Normal.x < rValue.Normal.x); if (lValue.Normal.y != rValue.Normal.y) return(lValue.Normal.y < rValue.Normal.y); return(lValue.Normal.z < rValue.Normal.z); }  
    • By Karol Plewa
      Hi, 
       
      I am working on a project where I'm trying to use Forward Plus Rendering on point lights. I have a simple reflective scene with many point lights moving around it. I am using effects file (.fx) to keep my shaders in one place. I am having a problem with Compute Shader code. I cannot get it to work properly and calculate the tiles and lighting properly. 
       
      Is there anyone that is wishing to help me set up my compute shader?
      Thank you in advance for any replies and interest!
    • By fishyperil
      I'm looking for some references that could help me learn how to program some really basic 2D enemy behaviours.
      I wasn't sure whether to post this here or in the AI section but I think it might be more suitable to be posted here since it has more to do with basic maths than any AI related algorithms.
      Could anyone help recommend some resources (books, posts, videos) that could help me understand how to properly implement the basics of enemy movement in 2d games ? So far I've only managed to get them to chase the player character and to stop moving on collision, but the movement is pretty unrealistic and once the collision occurs the enemies all "pile up" on the player character. I'm doing this in C++ so no guides that explain how to script this using an engine api please.
    • By LifeArtist
      Good Evening,
      I want to make a 2D game which involves displaying some debug information. Especially for collision, enemy sights and so on ...
      First of I was thinking about all those shapes which I need will need for debugging purposes: circles, rectangles, lines, polygons.
      I am really stucked right now because of the fundamental question:
      Where do I store my vertices positions for each line (object)? Currently I am not using a model matrix because I am using orthographic projection and set the final position within the VBO. That means that if I add a new line I would have to expand the "points" array and re-upload (recall glBufferData) it every time. The other method would be to use a model matrix and a fixed vbo for a line but it would be also messy to exactly create a line from (0,0) to (100,20) calculating the rotation and scale to make it fit.
      If I proceed with option 1 "updating the array each frame" I was thinking of having 4 draw calls every frame for the lines vao, polygons vao and so on. 
      In addition to that I am planning to use some sort of ECS based architecture. So the other question would be:
      Should I treat those debug objects as entities/components?
      For me it would make sense to treat them as entities but that's creates a new issue with the previous array approach because it would have for example a transform and render component. A special render component for debug objects (no texture etc) ... For me the transform component is also just a matrix but how would I then define a line?
      Treating them as components would'nt be a good idea in my eyes because then I would always need an entity. Well entity is just an id !? So maybe its a component?
      Regards,
      LifeArtist
    • By nickyc95
      Hi.
      I'm kind of late to this party but I thought I would ask anyway as I haven't found a concrete answer.
       
      When creating a game engine, when should you choose one methodology over another (more specifically OOP and DOD)? Which areas benefit from DOD? Which areas benefit from OOP? Do people typically mix multiple methodologies throughout a project? I.e. certain sub-systems created in one, and others in the another?  
      DOD - Data Oriented Design
      OOP - Object Oriented Design
       
      Pretty simple
      Thanks
  • Advertisement