BlockRegistry.cpp 1.1 KB

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