onilink_

Structure Object Test

Mar 5th, 2015
377
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.11 KB | None | 0 0
  1.  
  2. template<class T>
  3. class SpacePartitioning
  4. {
  5. public:
  6.     virtual void insert(T * entity) = 0;
  7.     virtual bool remove(T * entity) = 0;
  8.     virtual T * instanceCollision(T * entity, float dx, float dy) = 0;
  9.     virtual std::vector<T*> instancesCollision(T * entity, float x, float y) = 0;
  10.     virtual bool collision(T * entity, float dx, float dy) = 0;
  11.     virtual std::vector<T*> retrieve(float x1, float y1, float x2, float y2, int mode) const = 0;
  12. };
  13.  
  14.  
  15. template<class T>
  16. class InstanceContext
  17. {
  18.     vector< vector<T*> > instances;
  19.     vector< SpacePartitioning<T> > partitionning;
  20.    
  21.     void add(T*);
  22.     void remove(T*);
  23.    
  24.     static void setGlobal();
  25.     static InstanceContext & getDefault();
  26.     static InstanceContext & global();
  27. };
  28.  
  29.  
  30. template<class T>
  31. class ObjectBase
  32. {
  33.     InstanceContext<T> * my_context;
  34.     int index;
  35.    
  36.     ObjectBase(int index) :
  37.         my_context(InstanceContext<T>::global()),
  38.         index(index)
  39.     {
  40.         my_context->add(index, this);
  41.     }
  42.     virtual ~ObjectBase()
  43.     {
  44.         my_context->remove(index, this);
  45.     }
  46.    
  47.     virtual void step(float dt) {}
  48.     virtual void draw() const {}
  49.    
  50.     InstanceContext<T> & context();
  51. };
  52.  
  53. class Object2d : public ObjectBase<Object2d>
  54. {
  55.     Vec2 pos;
  56.    
  57.     Object2d(float x, float y, int index): ObjectBase(index), pos(x, y) {}
  58. };
  59.  
  60. // Auto index
  61. template<class T>
  62. class Object : public Object2d
  63. {
  64.     static int current_index;
  65.    
  66.     Object(float x, float y): Object2d(x, y, current_index) {}
  67.    
  68.     int instanceNumber() const
  69.     {
  70.         return context().number(objectIndex());
  71.     }
  72.     T * find(int n)
  73.     {
  74.         return reinterpret_cast<T*>(context().get(n));
  75.     }
  76. };
  77. int Object<T>::current_index = hidden::global_index++;
  78.  
  79.  
  80. //--------------------------------------------
  81. //      Usage
  82. //--------------------------------------------
  83. class Player : public Object<Player>
  84. {
  85. };
  86.  
  87. void test()
  88. {
  89.     InstanceContext<Object2d> ic;
  90.     ic.setGlobal();
  91.    
  92.     new Player(32, 48);
  93.     new Player(16, 16);
  94.    
  95.     Player * first = Player::find(0);
  96. }
Advertisement
Add Comment
Please, Sign In to add comment