Advertisement
Guest User

Untitled

a guest
Dec 6th, 2018
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. struct SpriteNode{ //simple singly linked list, consider using a standard library one, I just did this to be explicit
  2.     SpriteNode* next;
  3.     int idx;
  4. }
  5.  
  6. int peakCapacity=0; //represents the last element of the array that has been populated
  7. Sprite sprites[MAX_SPRITES];
  8. SpriteNode* freeList; //this is the first element of the freelist, no seperate head. null initialized
  9.  
  10. //Don't add initially empty slots to the freelist, we keep a freelist to keep fragmentation low.
  11. //We always want the freelist to be the best choice for assigning to a new element
  12. void init(){
  13.     for(int i=0;i<loadCount;i++){
  14.         //just do whatever normal init you'd do for your sprites array
  15.         sprites[i]=loadNewSprite();
  16.         //then increment the peakCapacity so we keep track of where the iniitalized sprites end
  17.         peakCapacity++;
  18.     }
  19. }
  20. //This must be called whenever a sprite is considered an invalid entry in the sprites array.
  21. //for example your sprite dies. Wherever you would normally set is_used=0 basically
  22. void deadSprite(int idx){
  23.     SpriteNode* tmp=new SpriteNode;
  24.     tmp->idx=idx;
  25.     tmp->next=freeList;
  26.     freeList->next=null;
  27.     freeList=tmp;
  28.     return;
  29. }
  30. //called when we need to introduce a new sprite to the system
  31. //it returns the position where the calling code can introduce their new sprite
  32. int newSpriteIndex(){
  33.     if(freelist){
  34.         SpriteNode* tmpnode=freelist;
  35.         freelist=freelist->next;
  36.         int ret=tmpnode->idx;
  37.         delete tmpnode;
  38.         return ret;
  39.     }
  40.     if(peakCapacity<MAX_SPRITES){
  41.         return ++peakCapacity;
  42.     }
  43.     return null; //we didn't have any free slots on the freelist or the array,
  44.                  //we've reached capacity with no holes.
  45.                  //you should probably increase the array size if this happens. The freelist remains fine because we made it referential by index not pointer
  46. }
  47.  
  48. //This would be update/render code
  49. //notice how we don't loop through the entire array, we only go as far as we know there's sprites.
  50. for(int i=0;i<peakCapacity;i++){
  51.     //do normal sprite-y things
  52.    
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement