BlockRegistry.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include <unordered_map>
  2. #include <vector>
  3. #include <fstream>
  4. #include <iostream>
  5. #include "BlockRegistry.h"
  6. namespace BlockRegistry
  7. {
  8. static Block NULL_BLOCK(0, "null_block");
  9. static std::unordered_map<std::string, u16> registry;
  10. static std::vector<Block> idMap = {NULL_BLOCK};
  11. void loadFromFile(const std::string& path)
  12. {
  13. std::ifstream in;
  14. in.open(path);
  15. if(in.fail())
  16. {
  17. std::cout << "cannot read blocks from file '" << path << "'" << std::endl;
  18. return;
  19. }
  20. std::string line;
  21. while(true)
  22. {
  23. std::getline(in, line, '\n');
  24. if(in.fail())
  25. {
  26. break;
  27. }
  28. u16 id = idMap.size();
  29. std::cout << id << std::endl;
  30. idMap.emplace_back(id, line);
  31. registry[line] = id;
  32. }
  33. }
  34. const Block& getBlock(const std::string& name)
  35. {
  36. const std::unordered_map<std::string, u16>::const_iterator& iter = registry.find(name);
  37. if(iter == registry.end())
  38. {
  39. return NULL_BLOCK;
  40. }
  41. return idMap[iter->second];
  42. }
  43. const Block& getBlock(u16 id)
  44. {
  45. if(id >= idMap.size())
  46. {
  47. return NULL_BLOCK;
  48. }
  49. return idMap[id];
  50. }
  51. }