AGXDynamics  2.31.1.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
CollisionGroupManager.h
Go to the documentation of this file.
1 /*
2 Copyright 2007-2021. Algoryx Simulation AB.
3 
4 All AGX source code, intellectual property, documentation, sample code,
5 tutorials, scene files and technical white papers, are copyrighted, proprietary
6 and confidential material of Algoryx Simulation AB. You may not download, read,
7 store, distribute, publish, copy or otherwise disseminate, use or expose this
8 material unless having a written signed agreement with Algoryx Simulation AB, or having been
9 advised so by Algoryx Simulation AB for a time limited evaluation, or having purchased a
10 valid commercial license from Algoryx Simulation AB.
11 
12 Algoryx Simulation AB disclaims all responsibilities for loss or damage caused
13 from using this software, unless otherwise stated in written agreements with
14 Algoryx Simulation AB.
15 */
16 
17 #ifndef AGXCOLLIDE_COLLISIONGROUPHANDLER_H
18 #define AGXCOLLIDE_COLLISIONGROUPHANDLER_H
19 
20 #include <agx/HashSet.h>
21 #include <agx/AtomicValue.h>
22 #include <agx/Component.h>
25 #include <agxStream/Serializable.h>
26 
27 namespace agxCollide
28 {
31  {
32  public:
33  static CollisionGroupManager *defaultManager();
34 
35  public:
36  // typedef agx::Vector< agx::UInt32 > GroupIdVector;
42 
44 
45  public:
47 
53  agx::Physics::CollisionGroupSetPtr set, agx::UInt32 groupId, bool unreferenceOldSet = true);
54 
59  agx::Physics::CollisionGroupSetPtr getExtendedSetFromAddedSet(
60  agx::Physics::CollisionGroupSetPtr set, agx::Physics::CollisionGroupSetPtr set2, bool unreferenceOldSet = true);
61 
67  agx::Physics::CollisionGroupSetPtr set, agx::UInt32 groupId, bool unreferenceOldSet = true);
68 
75 
76 
80  void unreferenceSet(agx::Physics::CollisionGroupSetPtr set);
81 
85  void setEnableCollisions(agx::UInt32 groupId1, agx::UInt32 groupId2, bool flag);
86 
91  bool canSetsCollide(agx::UInt32 set1, agx::UInt32 set2) const;
92 
93  // Wrapper
94  bool canSetsCollide(agx::Physics::CollisionGroupSetPtr set1, agx::Physics::CollisionGroupSetPtr set2) const;
95 
96 
101  bool canGroupsCollide(agx::UInt32 group1, agx::UInt32 group2) const;
102 
106  agx::UInt32 generateUniqueId();
107 
108  static bool hasGroup(agx::Physics::CollisionGroupSetPtr set, agx::UInt32 groupId);
109  static bool hasGroup(agx::Physics::CollisionGroupSetPtr set, const agx::Name& groupName);
110  static bool verify(agx::Physics::CollisionGroupSetPtr set);
111 
112  const CollisionHash& getDisabledGroupCollisions() const;
113  const CollisionHash& getDisabledSetCollisions() const;
114 
115 
116  // Not thread safe
117  bool hasGroup(const agx::Name& groupName) const;
118  bool hasGroup(agx::UInt32 groupId) const;
119 
120  // Not thread safe
121  agx::UInt32 getGroupId(const agx::Name& groupName);
122  agx::Physics::CollisionGroupPtr getGroup(const agx::Name& groupName);
124 
126 
128  SymmetricCollisionGroupVector getDisabledCollisionGroupPairs() const;
129 
131 
132  protected:
133  virtual ~CollisionGroupManager();
134 
135  private:
136  friend class Space;
137  agx::UInt32 generateNameId();
138  void setUniqueIdCounter(agx::UInt32 id);
139  void setNameIdCounter(agx::UInt32 id);
140 
141  private:
142  agx::Physics::CollisionGroupSetPtr getUnarySet(agx::UInt32 groupId);
143  void internal_unreferenceSet(agx::Physics::CollisionGroupSetPtr set);
144  bool internal_canCollide(const GroupIdHash& groups1, const GroupIdHash& groups2);
145  void removeInactiveSets();
146  void registerNewSet(agx::Physics::CollisionGroupSetPtr set);
147 
148  class GroupSetCache
149  {
150  public:
151  class Bucket
152  {
153  public:
154  enum State
155  {
158  VALID
159  };
160 
162 
163  AGX_FORCE_INLINE Bucket() : state(INACTIVE)
164  {
165  }
166 
168  {
169  groupSet = b.groupSet;
170  state = b.state;
171 
172  return *this;
173  }
174 
176  { return state >= ACTIVE; }
177 
179  {
180  // prefetch( &state, agx::NTA );
181  return state == VALID;
182  }
183 
184  private:
185  friend class GroupSetCache;
186  agx::UInt8 state;
187  };
188 
189 
190  public:
191  GroupSetCache() :
192  m_size(0), m_capacity(0), m_buckets(nullptr),
193  m_maxProbeLength(0)
194  {
195  this->rebuild(0);
196  }
197 
198  ~GroupSetCache()
199  {
200  m_allocator.deallocateBytes(m_buckets, m_capacity * sizeof(Bucket));
201  }
202 
203 
205  {
206  agx::UInt32 bucketIndex = findBucket(&group, 1);
207  return bucketIndex != agx::InvalidIndex ? m_buckets[bucketIndex].groupSet : agx::Physics::CollisionGroupSetPtr();
208  }
209 
211  {
212  agxAssert(set && set.groups().size() + 1 < 1024);
213  agx::Physics::CollisionGroupPtr localGroups[1024];
214  size_t numGroups = 0;
215 
216  // Build extended list, insert group in already sorted vector
217  const GroupVector& groups = set.groups();
218  size_t i = 0;
219  for (; i < groups.size() && groups[i].id() < group.id(); ++i)
220  localGroups[numGroups++] = groups[i];
221 
222  localGroups[numGroups++] = group;
223 
224  for (; i < groups.size(); ++i)
225  localGroups[numGroups++] = groups[i];
226 
227 
228  agx::UInt32 bucketIndex = findBucket(localGroups, numGroups);
229  return bucketIndex != agx::InvalidIndex ? m_buckets[bucketIndex].groupSet : agx::Physics::CollisionGroupSetPtr();
230  }
231 
233  {
234  agxAssert(set && set.groups().size() - 1 < 1024);
235  agx::Physics::CollisionGroupPtr localGroups[1024];
236  size_t numGroups = 0;
237 
238  // Build reduced list
239  const GroupVector& groups = set.groups();
240  for (size_t i = 0; i < groups.size(); ++i)
241  {
242  if (groups[i].id() == group.id())
243  continue;
244 
245  localGroups[numGroups++] = groups[i];
246  }
247 
248  agx::UInt32 bucketIndex = findBucket(localGroups, numGroups);
249  return bucketIndex != agx::InvalidIndex ? m_buckets[bucketIndex].groupSet : agx::Physics::CollisionGroupSetPtr();
250  }
251 
253  {
254  if (!set)
256 
257  const GroupVector& groups = set.groups();
258 
259  agx::UInt32 bucketIndex = findBucket(groups.begin(), groups.size());
260  return bucketIndex != agx::InvalidIndex ? m_buckets[bucketIndex].groupSet : agx::Physics::CollisionGroupSetPtr();
261  }
262 
263  void insert(agx::Physics::CollisionGroupSetPtr set)
264  {
265  agxAssert(set);
266  const GroupVector& groups = set.groups();
267 
268  agx::UInt32 hashValue = calculateHash(groups.begin(), groups.size());
269 
270  Bucket *bucket;
271  Bucket *targetBucket = 0;
272  size_t offset = 0;
273  // std::cout << "Insert " << cellIndex << " with id " << cellId << std::endl;
274 
275  /* Check if we should grow and rebuild hash table */
276  if (m_size >= (size_t)((float)m_capacity * AGX_HASH_SET_GROW_THRESHOLD))
277  this->rebuild((size_t)((float)(m_capacity+1) * AGX_HASH_SET_GROW_FACTOR));
278 
279  /* Iterate until target bucket is found */
280  bool goon = true;
281  do
282  {
283  bucket = &m_buckets[(hashValue + offset * offset) % m_capacity];
284 
285  /* Check if overwriting previous insertion with same key */
286  if (bucket->isValid() && compareGroups(groups.begin(), groups.size(), bucket->groupSet))
287  {
288  targetBucket = bucket;
289  break;
290  }
291 
292  /* Tag first free slot */
293  if (!bucket->isValid() && !targetBucket)
294  targetBucket = bucket;
295 
296  /* If we have found a free bucket we can stop iterating when we are sure that the key was not previously inserted */
297  if (targetBucket && offset >= m_maxProbeLength)
298  break;
299 
300  /* Go to next bucket */
301  offset++;
302 
303  /* Resize and rebuild table if it takes too long to find a free slot */
304  if (offset > AGX_HASH_SET_MAX_PROBE_LENGTH)
305  {
306  this->rebuild((size_t)((float)m_capacity * AGX_HASH_SET_GROW_FACTOR));
307  return this->insert(set);
308  }
309  } while (goon);
310 
311  agxAssert(targetBucket);
312 
313  if (offset > m_maxProbeLength)
314  m_maxProbeLength = (agx::UInt16)offset;
315 
316  targetBucket->groupSet = set;
317 
318  /* Check if inserting a new value rather than overwriting an old entry */
319  if (!targetBucket->isValid())
320  {
321  m_size++;
322  targetBucket->state = Bucket::VALID;
323  }
324  }
325 
326  bool contains(agx::Physics::CollisionGroupSetPtr set) const
327  {
328  return find(set).isValid();
329  }
330 
331 
332  void erase(agx::Physics::CollisionGroupSetPtr set)
333  {
334  agxAssert(set);
335  const GroupVector& groups = set.groups();
336 
337  agx::UInt32 bucketIndex = findBucket(groups.begin(), groups.size());
338  agxAssert(bucketIndex != agx::InvalidIndex);
339 
340  Bucket *bucket = &m_buckets[bucketIndex];
341  agxAssert(bucket->isValid() && compareGroups(groups.begin(), groups.size(), bucket->groupSet));
342 
343  m_size--;
344 
345  // Bucket does not become inactive since it might be in the middle of a probing chain
346  bucket->state = Bucket::ACTIVE;
347  }
348 
349  private:
350 
351  AGX_FORCE_INLINE agx::UInt32 findBucket(const agx::Physics::CollisionGroupPtr *localGroups, size_t numGroups) const
352  {
353  agxAssert(m_buckets);
354  if (m_buckets) {
355 
356  agx::UInt32 hashValue = calculateHash(localGroups, numGroups);
357 
358  size_t index = hashValue % m_capacity;
359  const Bucket *bucket = &m_buckets[index];
360 
361  /* First test is outside for-loop, hopefully getting better branch prediction */
362  if (bucket->isValid() && compareGroups(localGroups, numGroups, bucket->groupSet))
363  return (agx::UInt32)index;
364 
365 
366  for (size_t offset = 1; bucket->isActive() && offset <= m_maxProbeLength; offset++)
367  {
368  index = (hashValue + offset * offset) % m_capacity;
369  bucket = &m_buckets[index];
370 
371  if (bucket->isValid() && compareGroups(localGroups, numGroups, bucket->groupSet))
372  return (agx::UInt32)index;
373  }
374  }
375 
376  /* Not found */
377  return agx::InvalidIndex;
378  }
379 
380  AGX_FORCE_INLINE agx::UInt32 calculateHash(const agx::Physics::CollisionGroupPtr *localGroups, size_t numGroups) const
381  {
382  // Calculate hash
383  agx::UInt32 hashValue = 0;
384  for (size_t i = 0; i < numGroups; ++i)
385  hashValue = agx::hash(hashValue, agx::hash(localGroups[i].id()));
386 
387  return hashValue;
388  }
389 
390 
391  AGX_FORCE_INLINE bool compareGroups(const agx::Physics::CollisionGroupPtr *localGroups, size_t numGroups, agx::Physics::CollisionGroupSetPtr set) const
392  {
393  agxAssert(set);
394  const GroupVector& groups = set.groups();
395 
396  if (groups.size() != numGroups)
397  return false;
398 
399  for (size_t i = 0; i < groups.size(); ++i)
400  {
401  if (groups[i].id() != localGroups[i].id())
402  return false;
403  }
404 
405  return true;
406  }
407 
408  void rebuild(size_t size)
409  {
410  size = std::max( size, size_t(AGX_HASH_SET_MIN_SIZE) );
411  //LOGGER_DEBUG() << "HashTable: Rebuilding and resizing from " << numBuckets() << " to " << agx::nextPrime((int)(numBuckets() * resizeFactor)) << " buckets.\n" << LOGGER_END();
412  agxAssert(size >= m_size);
413  size_t oldNumBuckets = m_capacity;
414  Bucket *oldBuckets = m_buckets;
415 
416  m_capacity = agx::nextPrime((int)size);
417  m_buckets = (Bucket *)m_allocator.allocateBytes(m_capacity * sizeof(Bucket));
418  for (size_t i = 0; i < m_capacity; ++i)
419  ::new (&m_buckets[i]) Bucket();
420 
421  m_size = 0;
422  m_maxProbeLength = 0;
423 
424  for (size_t i = 0; i < oldNumBuckets; i++)
425  {
426  Bucket& bucket = oldBuckets[i];
427 
428  if (bucket.isValid())
429  this->insert(bucket.groupSet);
430  }
431 
432  m_allocator.deallocateBytes((void *)oldBuckets, oldNumBuckets * sizeof(Bucket));
433  }
434 
435  private:
436  size_t m_size;
437  size_t m_capacity;
438  Bucket *m_buckets;
439 
440  agx::UInt16 m_maxProbeLength;
441  agx::ByteAllocator m_allocator;
442  };
443 
444 
445  private:
446  agx::AtomicValue m_nameIdCounter;
447  agx::AtomicValue m_uniqueIdCounter;
448  agx::Mutex m_mutex;
449  GroupSetCache m_groupSetCache;
450  agxData::EntityStorageRef m_collisionGroupSetStorage;
451 
452  CollisionHash m_disabledSetCollisions;
453  CollisionHash m_disabledGroupCollisions;
454 
456 
457  agxData::EntityStorageRef m_collisionGroupStorage;
458 
460  CollisionGroupTable m_collisionGroupTable;
461 
462  typedef agx::HashVector<agx::Name, agx::UInt32> CollisionGroupNameTable;
463  CollisionGroupNameTable m_collisionGroupNameTable;
464  };
465 
466 
467  std::ostream& operator << ( std::ostream& output, const agx::Physics::CollisionGroupSetPtr& set );
468  std::ostream& operator << ( std::ostream& output, const agx::Physics::CollisionGroupPtr& group );
469 
470 
471 
472 
473  /* Implementation */
474 
476  {
477  // std::cout << "canSetsCollide " << set1 << " : " << set2 << " => " << !m_disabledSetCollisions.contains(agx::buildHashKey(set1, set2)) << std::endl;
478  return !m_disabledSetCollisions.contains(agx::buildHashKey(set1, set2));
479  }
480 
482  {
483  agxAssert(set1);
484  agxAssert(set2);
485  agxAssert(set1.getStorage() == m_collisionGroupSetStorage);
486  agxAssert(set2.getStorage() == m_collisionGroupSetStorage);
487  return this->canSetsCollide((agx::UInt32)set1.getId(), (agx::UInt32)set2.getId());
488  }
489 
491  {
492  return !m_disabledGroupCollisions.contains(agx::buildHashKey(group1, group2));
493  }
494 
497 
498 }
499 
500 
501 #endif /* AGXCOLLIDE_COLLISIONGROUPHANDLER_H */
agx::HashSet< agx::UInt32 > GroupIdHash
AGXCORE_EXPORT UInt32 hash(const T &key)
Definition: HashFunction.h:65
bool contains(const KeyT &key) const
Boolean query to test existence of an element.
Definition: HashSet.h:310
Vec3T< T > max(const Vec3T< T > &lhs, const Vec3T< T > &rhs)
Definition: Vec3Template.h:874
A component is an object containing other objects, enabling hierarchical structuring.
Definition: Component.h:38
Pointer to a entity instance of type Physics.CollisionGroup.
#define m_size
Definition: Vector.h:429
uint8_t UInt8
Definition: Integer.h:38
std::pair< agx::Name, agx::Real > Bucket
#define AGXPHYSICS_EXPORT
AGXCORE_EXPORT const InvalidIndexStruct InvalidIndex
Representation of a name string.
Definition: Name.h:32
#define AGX_FORCE_INLINE
Definition: Object.h:62
agx::Index getId() const
Definition: EntityPtr.h:273
Pointer to a entity instance of type Physics.CollisionGroupSet.
std::ostream & operator<<(std::ostream &output, const BoundingAABB &bound)
Definition: BoundingAABB.h:224
agxData::EntityStorage * getStorage() const
Definition: EntityPtr.h:272
#define AGX_HASH_SET_GROW_THRESHOLD
Definition: HashSet.h:65
AGXPHYSICS_EXPORT agx::Vector< agx::Physics::CollisionGroupPtr > & groups()
Templated vector class.
Definition: Vector.h:52
#define AGX_HASH_SET_GROW_FACTOR
Definition: HashSet.h:67
AGXCORE_EXPORT agx::UInt64 buildHashKey(agx::UInt32 id1, agx::UInt32 id2)
Definition: HashFunction.h:41
const CollisionHash & getDisabledSetCollisions() const
This class contains all Geometries and performs Broad Phase and Narrow Phase collision detection to c...
Definition: Space.h:81
agx::HashSet< agx::UInt64 > CollisionHash
agx::HashSet< agx::Physics::CollisionGroupPtr > GroupHash
agx::Vector< agx::Physics::CollisionGroupSetPtr > GroupSetVector
agx::Vector< agx::Physics::CollisionGroupPtr > GroupVector
#define AGX_HASH_SET_MAX_PROBE_LENGTH
Definition: HashSet.h:70
Byte allocator.
Definition: Allocator.h:54
const CollisionHash & getDisabledGroupCollisions() const
agx::Vector< agx::SymmetricPair< agx::Physics::CollisionGroupPtr > > SymmetricCollisionGroupVector
#define agxAssert(expr)
Definition: debug.h:143
bool canSetsCollide(agx::UInt32 set1, agx::UInt32 set2) const
AGXCORE_EXPORT int nextPrime(int n)
bool canGroupsCollide(agx::UInt32 group1, agx::UInt32 group2) const
AGXPHYSICS_EXPORT bool setEnableCollisions(agx::RigidBody *rb1, agx::RigidBody *rb2, bool enable)
Enable or disable the collision between all geometries in RigidBody rb1 and RigidBody rb2...
#define AGX_HASH_SET_MIN_SIZE
Definition: HashSet.h:63
#define AGXSTREAM_DECLARE_SERIALIZABLE(T)
Use this in a Serializable class to add the required methods Important: Use full namespace in the dec...
Definition: Serializable.h:206
This class is an abstract base class for all classes that can be stored and retrieved from an Archive...
Definition: Serializable.h:44
std::mutex Mutex
Definition: Referenced.h:93
#define m_capacity
Definition: Vector.h:430
uint16_t UInt16
Definition: Integer.h:39
agx::HashSet< agx::Physics::CollisionGroupSetPtr > GroupSetHash
Inheritance with partial specialization due to bug with ref_ptr containers.
AGXPHYSICS_EXPORT agx::UInt32 & id()
uint32_t UInt32
Definition: Integer.h:40
AGX_DECLARE_POINTER_TYPES(SpaceListener)