Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include <stdint.h>
  4. #include <stdlib.h>
  5.  
  6. typedef struct spatial_hash_s {
  7. uint32_t width;
  8. uint32_t height;
  9. uint16_t cellmax; // max # of entries per cell
  10. uint64_t entrysize; // size of a single entry
  11. } spatial_hash_t;
  12.  
  13. typedef struct spatial_index_s {
  14. uint16_t count; // # of entries held in this cell
  15. } spatial_index_t;
  16.  
  17. #define SHASH_CELL_AT(h,x,y) \
  18. ((spatial_index_t*)(((uint8_t*)((h)+1))+(((y)*(h)->width+(x))*(sizeof(spatial_index_t)+((h)->entrysize)*((h)->cellmax)))))
  19.  
  20. #define shash_new(type, w, h, cellmax) \
  21. (spatial_hash((w),(h),(cellmax),sizeof(type)))
  22.  
  23. spatial_hash_t* spatial_hash(uint32_t w, uint32_t h, uint16_t cellmax, uint16_t entrysize) {
  24. uint32_t cells = w * h;
  25. uint64_t rowsize = (sizeof(spatial_index_t) + (cellmax * entrysize));
  26. uint64_t total_size = sizeof(spatial_hash_t) + (cells * rowsize);
  27. spatial_hash_t *sh = malloc(total_size);
  28. memset(sh, 0, total_size); // zero out the memory
  29. sh->width = w;
  30. sh->height = h;
  31. sh->cellmax = cellmax;
  32. sh->entrysize = entrysize;
  33. return sh;
  34. }
  35.  
  36. // shash_get(sh, 0, 0, geometry_entry, &count, &results)
  37. #define shash_get(type, hash, x, y, countref) \
  38. ((type*)spatial_hash_get((hash),(x),(y),(countref)))
  39.  
  40. void* spatial_hash_get(spatial_hash_t *sh, uint16_t x, uint16_t y, uint16_t *count) {
  41. spatial_index_t *row = SHASH_CELL_AT(sh, x, y);
  42. *count = row->count;
  43. return (void*)(row+1);
  44. }
  45.  
  46. #define shash_append spatial_hash_append
  47.  
  48. void spatial_hash_append(spatial_hash_t *sh, uint16_t x, uint16_t y, void* val) {
  49. spatial_index_t *cell = SHASH_CELL_AT(sh, x, y);
  50. void *free_entry = (void*)(((char*)(cell+1))+(cell->count)*sh->entrysize);
  51. memcpy(free_entry, val, sh->entrysize);
  52. cell->count++;
  53. }
  54.  
  55. #define shash_delete spatial_hash_delete
  56.  
  57. void spatial_hash_delete(spatial_hash_t *sh, uint16_t x, uint16_t y, uint16_t i) {
  58. spatial_index_t *cell = SHASH_CELL_AT(sh, x, y);
  59. char *base = (char*)(cell+1);
  60. while (i < cell->count) {
  61. // overwrite with next entry
  62. memcpy(base + (i*sh->entrysize), base + ((i+1)*sh->entrysize), sh->entrysize);
  63. i++;
  64. }
  65. cell->count--;
  66. }
  67.  
  68. void spatial_hash_reset(spatial_hash_t *sh) {
  69. int cells = sh->width * sh->height;
  70. uint64_t cellsize = (sizeof(spatial_index_t) + (sh->cellmax * sh->entrysize));
  71. uint64_t total_size = sizeof(spatial_hash_t) + (cells * cellsize);
  72. memset((void*)(sh+1), 0, total_size);
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement