Advertisement
copyrat90

Butano `bn::pool` example

Mar 6th, 2023
821
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.05 KB | None | 0 0
  1. #include <bn_core.h>
  2. #include <bn_forward_list.h>
  3. #include <bn_log.h>
  4. #include <bn_pool.h>
  5.  
  6. struct Bullet {
  7.     int x, y;
  8.     bool is_dead;
  9. };
  10.  
  11. int main() {
  12.     bn::core::init();
  13.     constexpr int POOL_SIZE = 2;
  14.  
  15.     bn::pool<Bullet, POOL_SIZE> bullet_pool;
  16.     bn::forward_list<Bullet*, POOL_SIZE> bullet_list;
  17.  
  18.     // Create bullets in `bullet_pool`, store their pointers to `bullet_list`.
  19.     Bullet& bullet1 = bullet_pool.create(11, 11, true);
  20.     Bullet& bullet2 = bullet_pool.create(22, 22, true);
  21.     bullet_list.push_front(&bullet1);
  22.     bullet_list.push_front(&bullet2);
  23.  
  24.     BN_LOG("bullet1 created on {x=", bullet1.x, ", y=", bullet1.y, "}");
  25.     BN_LOG("bullet2 created on {x=", bullet2.x, ", y=", bullet2.y, "}");
  26.  
  27.     // Destroy the dead bullets
  28.     bullet_list.remove_if([&bullet_pool](Bullet* bullet) -> bool {
  29.         if (bullet->is_dead) {
  30.             BN_LOG("Destroy bullet on {x=", bullet->x, ", y=", bullet->y, "}");
  31.             bullet_pool.destroy(*bullet);
  32.             return true;
  33.         }
  34.         return false;
  35.     });
  36.  
  37.     // Now that the `bullet_pool` is empty, you can push 2 bullets again.
  38.     bullet_list.push_front(&bullet_pool.create(42, 42, true));
  39.     bullet_list.push_front(&bullet_pool.create(99, 99, true));
  40.  
  41.     for (const Bullet* bullet : bullet_list)
  42.         BN_LOG("bullet created on {x=", bullet->x, ", y=", bullet->y, "}");
  43.  
  44.     // Another way to conditionally destroy.
  45.     for (auto before_iter = bullet_list.before_begin(),
  46.               iter = bullet_list.begin();
  47.          iter != bullet_list.end();) {
  48.         Bullet* bullet = *iter;
  49.         if (bullet->is_dead) {
  50.             BN_LOG("Destroy bullet on {x=", bullet->x, ", y=", bullet->y, "}");
  51.             bullet_pool.destroy(*bullet);
  52.             iter = bullet_list.erase_after(before_iter);
  53.         } else {
  54.             before_iter = iter;
  55.             ++iter;
  56.         }
  57.     }
  58.  
  59.     BN_LOG("bullet_list.size(): ", bullet_list.size());
  60.     BN_LOG("bullet_pool.size(): ", bullet_pool.size());
  61.  
  62.     while (true)
  63.         bn::core::update();
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement