CStackBasicDescriptor.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * CStackBasicDescriptor.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CStackBasicDescriptor.h"
  12. #include "../../CCreatureHandler.h"
  13. #include "../../GameLibrary.h"
  14. #include "../../serializer/JsonSerializeFormat.h"
  15. VCMI_LIB_NAMESPACE_BEGIN
  16. //This constructor should be placed here to avoid side effects
  17. CStackBasicDescriptor::CStackBasicDescriptor() = default;
  18. CStackBasicDescriptor::CStackBasicDescriptor(const CreatureID & id, TQuantity Count)
  19. : typeID(id)
  20. , count(Count)
  21. {
  22. }
  23. CStackBasicDescriptor::CStackBasicDescriptor(const CCreature * c, TQuantity Count)
  24. : typeID(c ? c->getId() : CreatureID())
  25. , count(Count)
  26. {
  27. }
  28. const CCreature * CStackBasicDescriptor::getCreature() const
  29. {
  30. return typeID.hasValue() ? typeID.toCreature() : nullptr;
  31. }
  32. const Creature * CStackBasicDescriptor::getType() const
  33. {
  34. return typeID.hasValue() ? typeID.toEntity(LIBRARY) : nullptr;
  35. }
  36. CreatureID CStackBasicDescriptor::getId() const
  37. {
  38. return typeID;
  39. }
  40. TQuantity CStackBasicDescriptor::getCount() const
  41. {
  42. return count;
  43. }
  44. void CStackBasicDescriptor::setType(const CCreature * c)
  45. {
  46. typeID = c ? c->getId() : CreatureID();
  47. }
  48. void CStackBasicDescriptor::setCount(TQuantity newCount)
  49. {
  50. assert(newCount >= 0);
  51. count = newCount;
  52. }
  53. bool operator==(const CStackBasicDescriptor & l, const CStackBasicDescriptor & r)
  54. {
  55. return l.typeID == r.typeID && l.count == r.count;
  56. }
  57. void CStackBasicDescriptor::serializeJson(JsonSerializeFormat & handler)
  58. {
  59. handler.serializeInt("amount", count);
  60. if(handler.saving)
  61. {
  62. if(typeID.hasValue())
  63. {
  64. std::string typeName = typeID.toEntity(LIBRARY)->getJsonKey();
  65. handler.serializeString("type", typeName);
  66. }
  67. }
  68. else
  69. {
  70. std::string typeName;
  71. handler.serializeString("type", typeName);
  72. if(!typeName.empty())
  73. setType(CreatureID(CreatureID::decode(typeName)).toCreature());
  74. }
  75. }
  76. VCMI_LIB_NAMESPACE_END