You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

128 lines
2.5 KiB

  1. #![allow(dead_code)]
  2. use serde::{Deserialize, Serialize};
  3. use specs::{
  4. error::NoError,
  5. hibitset::BitSet,
  6. saveload::{ConvertSaveload, Marker},
  7. Component, Entity, HashMapStorage, VecStorage,
  8. };
  9. use crate::{
  10. builder::FleetBuilder,
  11. components::{Ship, ShipCount},
  12. misc::FlaggedStorage,
  13. };
  14. /// A fleet is a group of ships that share the same operation
  15. #[derive(Debug, Clone)]
  16. pub struct Fleet {
  17. owned: BitSet,
  18. count: ShipCount,
  19. }
  20. /// Entities with this component are owned by a certain fleet entity
  21. #[derive(Copy, Clone, Debug)]
  22. pub struct FleetOwned {
  23. owner: Entity,
  24. }
  25. #[derive(Serialize, Deserialize)]
  26. pub struct FleetOwnedData<M> {
  27. pub owner: M,
  28. }
  29. /* Fleet */
  30. impl Fleet {
  31. #[inline]
  32. pub fn builder() -> FleetBuilder {
  33. FleetBuilder::default()
  34. }
  35. #[inline]
  36. pub fn owned(&self) -> &BitSet {
  37. &self.owned
  38. }
  39. #[inline]
  40. pub fn count(&self) -> &ShipCount {
  41. &self.count
  42. }
  43. }
  44. impl Fleet {
  45. pub(crate) fn new() -> Self {
  46. Self {
  47. owned: BitSet::new(),
  48. count: ShipCount::none(),
  49. }
  50. }
  51. pub(crate) fn add_ship(&mut self, ship_id: Entity, ship: &Ship) {
  52. let type_ = ship.type_();
  53. self.count[type_] += 1;
  54. self.owned.add(ship_id.id());
  55. }
  56. pub(crate) fn remove_ship(&mut self, ship_id: Entity, ship: &Ship) {
  57. let type_ = ship.type_();
  58. self.count[type_] -= 1;
  59. self.owned.remove(ship_id.id());
  60. }
  61. }
  62. impl Component for Fleet {
  63. type Storage = HashMapStorage<Self>;
  64. }
  65. /* FleetOwned */
  66. impl FleetOwned {
  67. pub fn owner(&self) -> Entity {
  68. self.owner
  69. }
  70. }
  71. impl FleetOwned {
  72. pub(crate) fn new(owner: Entity) -> Self {
  73. Self { owner }
  74. }
  75. pub(crate) fn set_owner(&mut self, owner: Entity) {
  76. self.owner = owner;
  77. }
  78. }
  79. impl Component for FleetOwned {
  80. type Storage = FlaggedStorage<Self, VecStorage<Self>>;
  81. }
  82. impl<M> ConvertSaveload<M> for FleetOwned
  83. where
  84. for<'de> M: Marker + Serialize + Deserialize<'de>,
  85. {
  86. type Data = FleetOwnedData<M>;
  87. type Error = NoError;
  88. fn convert_into<F>(&self, mut ids: F) -> Result<Self::Data, Self::Error>
  89. where
  90. F: FnMut(Entity) -> Option<M>,
  91. {
  92. let owner = ids(self.owner).unwrap();
  93. Ok(FleetOwnedData { owner })
  94. }
  95. fn convert_from<F>(data: Self::Data, mut ids: F) -> Result<Self, Self::Error>
  96. where
  97. F: FnMut(M) -> Option<Entity>,
  98. {
  99. let owner = ids(data.owner).unwrap();
  100. Ok(FleetOwned { owner })
  101. }
  102. }