use std::ffi::c_void; use std::fmt::{Debug, Formatter}; use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU8, Ordering}; use std::sync::{Arc, Weak}; use atomig::Atomic; use parking_lot::lock_api::RwLockReadGuard; use parking_lot::{RawRwLock, RwLock}; use crate::defines::{LevelInt, MAX_MOVES}; use crate::dynamic_data::event_hooks::EventData; use crate::dynamic_data::models::battle::Battle; use crate::dynamic_data::models::learned_move::{LearnedMove, MoveLearnMethod}; use crate::dynamic_data::script_handling::{ScriptSource, ScriptSourceData, ScriptWrapper}; use crate::dynamic_data::{ DynamicLibrary, EventBatchId, Script, ScriptCategory, ScriptContainer, ScriptSet, VolatileScriptsOwner, WeakBattleReference, }; use crate::static_data::AbilityIndex; use crate::static_data::Form; use crate::static_data::Gender; use crate::static_data::Item; use crate::static_data::Nature; use crate::static_data::Species; use crate::static_data::TypeIdentifier; use crate::static_data::{Ability, Statistic}; use crate::static_data::{ClampedStatisticSet, StatisticSet}; use crate::utils::Random; use crate::{script_hook, PkmnError, StringKey, VecExt}; use anyhow::{anyhow, bail, Result}; /// The data of a Pokemon. struct PokemonData { /// The library data of the Pokemon. library: Arc, /// The species of the Pokemon. species: RwLock>, /// The form of the Pokemon. form: RwLock>, /// An optional display species of the Pokemon. If this is set, the client should display this /// species. An example of usage for this is the Illusion ability. display_species: Option>, /// An optional display form of the Pokemon. If this is set, the client should display this // species. An example of usage for this is the Illusion ability. display_form: Option>, /// The current level of the Pokemon. level: Atomic, /// The amount of experience of the Pokemon. experience: AtomicU32, /// The personality value of the Pokemon. personality_value: u32, /// The gender of the Pokemon. gender: RwLock, /// The coloring of the Pokemon. Value 0 is the default, value 1 means shiny. Other values are /// currently not used, and can be used for other implementations. coloring: u8, /// The held item of the Pokemon. held_item: RwLock>>, /// The remaining health points of the Pokemon. current_health: AtomicU32, /// The weight of the Pokemon in kilograms. weight: Atomic, /// The height of the Pokemon in meters. height: Atomic, /// The happiness of the Pokemon. Also known as friendship. happiness: AtomicU8, /// The stats of the Pokemon when disregarding any stat boosts. flat_stats: Arc>, /// The statistics boosts of the Pokemon. Will prevent the value from going above 6, and below /// -6. stat_boost: Arc>, /// The stats of the Pokemon including the stat boosts boosted_stats: Arc>, /// The [individual values](https://bulbapedia.bulbagarden.net/wiki/Individual_values) of the Pokemon. individual_values: Arc>, /// The [effort values](https://bulbapedia.bulbagarden.net/wiki/Effort_values) of the Pokemon. effort_values: Arc>, /// The [nature](https://bulbapedia.bulbagarden.net/wiki/Nature) of the Pokemon. nature: Arc, /// An optional nickname of the Pokemon. nickname: Option, /// An index of the ability to find the actual ability on the form. ability_index: AbilityIndex, /// An ability can be overriden to an arbitrary ability. This is for example used for the Mummy /// ability. override_ability: Option>, /// If in battle, we have additional data. battle_data: RwLock>, /// The moves the Pokemon has learned. This is of a set length of [`MAX_MOVES`]. Empty move slots /// are defined by None. moves: RwLock<[Option>; MAX_MOVES]>, /// Whether or not the Pokemon is allowed to gain experience. allowed_experience: bool, /// The current types of the Pokemon. types: RwLock>, /// Whether or not this Pokemon is an egg. is_egg: bool, /// Whether or not this Pokemon was caught this battle. is_caught: bool, /// The script for the held item. held_item_trigger_script: ScriptContainer, /// The script for the ability. ability_script: ScriptContainer, /// The script for the status. status_script: ScriptContainer, /// The volatile status scripts of the Pokemon. volatile: Arc, /// Data required for the Pokemon to be a script source. script_source_data: RwLock, } /// An individual Pokemon. #[derive(Clone)] pub struct Pokemon { /// The data of the Pokemon. data: Arc, } /// A non-owning reference to a Pokemon. #[derive(Debug, Clone)] pub struct WeakPokemonReference { /// The weak reference to the data. data: Weak, } unsafe impl Send for PokemonData {} unsafe impl Sync for PokemonData {} impl Pokemon { /// Instantiates a new Pokemon. pub fn new( library: Arc, species: Arc, form: &Arc, ability: AbilityIndex, level: LevelInt, unique_identifier: u32, gender: Gender, coloring: u8, nature: &StringKey, ) -> Result { // Calculate experience from the level for the specified growth rate. let experience = library .static_data() .growth_rates() .calculate_experience(species.growth_rate(), level)?; let weight = form.weight(); let height = form.height(); let base_happiness = species.base_happiness(); let nature = library .static_data() .natures() .get_nature(nature) .ok_or(PkmnError::InvalidNatureName { nature: nature.clone() })?; let pokemon_data = PokemonData { library, species: RwLock::new(species), form: RwLock::new(form.clone()), display_species: None, display_form: None, level: Atomic::new(level), experience: AtomicU32::new(experience), personality_value: unique_identifier, gender: RwLock::new(gender), coloring, held_item: RwLock::new(None), current_health: AtomicU32::new(1), weight: Atomic::new(weight), height: Atomic::new(height), stat_boost: Default::default(), flat_stats: Default::default(), boosted_stats: Default::default(), individual_values: Default::default(), effort_values: Default::default(), nature, nickname: None, ability_index: ability, override_ability: None, battle_data: RwLock::new(None), moves: RwLock::new(Default::default()), allowed_experience: false, types: RwLock::new(form.types().to_vec()), is_egg: false, is_caught: false, held_item_trigger_script: ScriptContainer::default(), ability_script: ScriptContainer::default(), status_script: ScriptContainer::default(), volatile: Default::default(), script_source_data: Default::default(), happiness: AtomicU8::new(base_happiness), }; let pokemon = Self { data: Arc::new(pokemon_data), }; pokemon.recalculate_flat_stats()?; let health = pokemon.flat_stats().hp(); pokemon.data.current_health.store(health, Ordering::Relaxed); Ok(pokemon) } /// The library data of the Pokemon. pub fn library(&self) -> &Arc { &self.data.library } /// The species of the Pokemon. pub fn species(&self) -> Arc { self.data.species.read().clone() } /// The form of the Pokemon. pub fn form(&self) -> Arc { self.data.form.read().clone() } /// Whether or not the Pokemon is showing as a different species than it actually is. pub fn has_different_display_species(&self) -> bool { self.data.display_species.is_some() } /// The species that should be displayed to the user. This handles stuff like the Illusion ability. pub fn display_species(&self) -> Arc { if let Some(v) = &self.data.display_species { v.clone() } else { self.species() } } /// Whether or not the Pokemon is showing as a different form than it actually is. pub fn has_different_display_form(&self) -> bool { self.data.display_form.is_some() } /// The form that should be displayed to the user. This handles stuff like the Illusion ability. pub fn display_form(&self) -> Arc { if let Some(v) = &self.data.display_form { v.clone() } else { self.form() } } /// The current level of the Pokemon. /// [See also](https://bulbapedia.bulbagarden.net/wiki/Level) pub fn level(&self) -> LevelInt { self.data.level.load(Ordering::Relaxed) } /// The amount of experience of the Pokemon. /// [See also](https://bulbapedia.bulbagarden.net/wiki/Experience) pub fn experience(&self) -> u32 { self.data.experience.load(Ordering::Relaxed) } /// The personality value of the Pokemon. /// [See also](https://bulbapedia.bulbagarden.net/wiki/Personality_value) pub fn personality_value(&self) -> u32 { self.data.personality_value } /// The gender of the Pokemon. pub fn gender(&self) -> Gender { *self.data.gender.read() } /// The coloring of the Pokemon. Value 0 is the default, value 1 means shiny. Other values are /// currently not used, and can be used for other implementations. pub fn coloring(&self) -> u8 { self.data.coloring } /// Gets the held item of a Pokemon pub fn held_item(&self) -> &RwLock>> { &self.data.held_item } /// Checks whether the Pokemon is holding a specific item. pub fn has_held_item(&self, name: &StringKey) -> bool { // Only true if we have an item, and the item name is the same as the requested item. if let Some(v) = self.data.held_item.read().deref() { return v.name() == name; } false } /// Changes the held item of the Pokemon. Returns the previously held item. pub fn set_held_item(&self, item: &Arc) -> Option> { self.data.held_item.write().replace(item.clone()) } /// Removes the held item from the Pokemon. Returns the previously held item. pub fn remove_held_item(&self) -> Option> { self.data.held_item.write().take() } /// Makes the Pokemon uses its held item. pub fn consume_held_item(&self) -> Result { if self.data.held_item.read().is_none() { return Ok(false); } let script = self.data.library.load_item_script( self.data .held_item .read() .as_ref() .ok_or(PkmnError::UnableToAcquireLock)?, )?; if script.is_none() { return Ok(false); } // TODO: the entire item use part. bail!("Not implemented yet.") } /// The remaining health points of the Pokemon. pub fn current_health(&self) -> u32 { self.data.current_health.load(Ordering::Relaxed) } /// The max health points of the Pokemon. pub fn max_health(&self) -> u32 { self.data.boosted_stats.hp() } /// The weight of the Pokemon in kilograms. pub fn weight(&self) -> f32 { self.data.weight.load(Ordering::Relaxed) } /// Sets the weight of the Pokemon in kilograms. pub fn set_weight(&self, weight: f32) { self.data.weight.store(weight, Ordering::Relaxed) } /// The height of the Pokemon in meters. pub fn height(&self) -> f32 { self.data.height.load(Ordering::Relaxed) } /// The current happiness of the Pokemon. Also known as friendship. pub fn happiness(&self) -> u8 { self.data.happiness.load(Ordering::Relaxed) } /// An optional nickname of the Pokemon. pub fn nickname(&self) -> &Option { &self.data.nickname } /// An index of the ability to find the actual ability on the form. pub fn real_ability(&self) -> &AbilityIndex { &self.data.ability_index } /// The current types of the Pokemon. pub fn types(&self) -> RwLockReadGuard<'_, RawRwLock, Vec> { self.data.types.read() } /// The moves the Pokemon has learned. This is of a set length of [`MAX_MOVES`]. Empty move slots /// are defined by None. pub fn learned_moves(&self) -> &RwLock<[Option>; MAX_MOVES]> { &self.data.moves } /// The stats of the Pokemon when disregarding any stat boosts. pub fn flat_stats(&self) -> &Arc> { &self.data.flat_stats } /// The amount of boosts on a specific stat. pub fn stat_boosts(&self) -> &Arc> { &self.data.stat_boost } /// Whether or not this Pokemon is still an egg, and therefore cannot battle. pub fn is_egg(&self) -> bool { self.data.is_egg } /// The stats of the Pokemon including the stat boosts pub fn boosted_stats(&self) -> &Arc> { &self.data.boosted_stats } /// Get the stat boosts for a specific stat. pub fn stat_boost(&self, stat: Statistic) -> i8 { self.data.stat_boost.get_stat(stat) } /// Change a boosted stat by a certain amount. pub fn change_stat_boost(&self, stat: Statistic, mut diff_amount: i8, self_inflicted: bool) -> Result { let mut prevent = false; script_hook!( prevent_stat_boost_change, self, self, stat, diff_amount, self_inflicted, &mut prevent ); if prevent { return Ok(false); } script_hook!( change_stat_boost_change, self, self, stat, self_inflicted, &mut diff_amount ); if diff_amount == 0 { return Ok(false); } let mut changed = false; let old_value = self.data.stat_boost.get_stat(stat); match diff_amount.cmp(&0_i8) { std::cmp::Ordering::Less => { changed = self.data.stat_boost.decrease_stat(stat, -diff_amount); } std::cmp::Ordering::Greater => { changed = self.data.stat_boost.increase_stat(stat, -diff_amount); } _ => {} } if changed { if let Some(battle) = self.get_battle() { let new_value = self.stat_boost(stat); battle.event_hook().trigger( EventData::StatBoostChange { user: self.clone(), stat, old_value, new_value, }, Default::default(), ) } self.recalculate_boosted_stats()?; } Ok(changed) } /// Gets an individual value of the Pokemon. /// [See also](https://bulbapedia.bulbagarden.net/wiki/Individual_values) pub fn individual_values(&self) -> &Arc> { &self.data.individual_values } /// Gets an effort value of the Pokemon. /// [See also](https://bulbapedia.bulbagarden.net/wiki/Effort_values) pub fn effort_values(&self) -> &Arc> { &self.data.effort_values } /// Gets the battle the battle is currently in. pub fn get_battle(&self) -> Option { let r = self.data.battle_data.read(); if let Some(data) = &r.deref() { data.battle.upgrade() } else { None } } /// Get the index of the side of the battle the Pokemon is in. Only returns a value if the Pokemon /// is on the battlefield. pub fn get_battle_side_index(&self) -> Option { self.data .battle_data .read() .as_ref() .map(|data| data.battle_side_index()) } /// Get the index of the slot on the side of the battle the Pokemon is in. Only returns a value /// if the Pokemon is on the battlefield. pub fn get_battle_index(&self) -> Option { self.data.battle_data.read().as_ref().map(|data| data.index()) } /// Returns whether something overrides the ability. pub fn is_ability_overriden(&self) -> bool { self.data.override_ability.is_some() } /// Returns the currently active ability. pub fn active_ability(&self) -> Result> { if let Some(v) = &self.data.override_ability { return Ok(v.clone()); } let form = self.form(); let ability = form.get_ability(self.data.ability_index)?; Ok(self .data .library .static_data() .abilities() .get(ability) .ok_or(PkmnError::InvalidAbilityName { ability: ability.clone(), })?) } /// The script for the status. pub fn status(&self) -> &ScriptContainer { &self.data.status_script } /// Returns the script for the currently active ability. pub fn ability_script(&self) -> &ScriptContainer { &self.data.ability_script } /// Whether or not the Pokemon is allowed to gain experience. pub fn allowed_experience_gain(&self) -> bool { self.data.allowed_experience } /// The nature of the Pokemon. /// [See also](https://bulbapedia.bulbagarden.net/wiki/Nature) pub fn nature(&self) -> &Arc { &self.data.nature } /// Calculates the flat stats on the Pokemon. This should be called when for example the base /// stats, level, nature, IV, or EV changes. This has a side effect of recalculating the boosted /// stats, as those depend on the flat stats. pub fn recalculate_flat_stats(&self) -> Result<()> { self.data .library .stat_calculator() .calculate_flat_stats(self, &self.data.flat_stats)?; self.recalculate_boosted_stats()?; Ok(()) } /// Calculates the boosted stats on the Pokemon, _without_ recalculating the flat stats. /// This should be called when a stat boost changes. pub fn recalculate_boosted_stats(&self) -> Result<()> { self.data .library .stat_calculator() .calculate_boosted_stats(self, &self.data.boosted_stats) } /// Change the species of the Pokemon. pub fn change_species(&self, species: Arc, form: Arc) -> Result<()> { *self.data.species.write() = species.clone(); *self.data.form.write() = form.clone(); // If the pokemon is genderless, but it's new species is not, we want to set its gender if self.gender() != Gender::Genderless && species.gender_rate() < 0.0 { // If we're in battle, use the battle random for predictability let r = self.data.battle_data.read(); if let Some(data) = r.deref() { let battle = data.battle().ok_or(anyhow!("Battle not set"))?; let mut random = match battle.random().get_rng().lock() { Ok(v) => v, Err(_) => return Err(PkmnError::UnableToAcquireLock.into()), }; *self.data.gender.write() = species.get_random_gender(random.deref_mut()); } else { // If we're not in battle, just use a new random. *self.data.gender.write() = species.get_random_gender(&mut Random::default()); } } // Else if the new species is genderless, but the pokemon has a gender, make the creature genderless. else if species.gender_rate() < 0.0 && self.gender() != Gender::Genderless { *self.data.gender.write() = Gender::Genderless; } let r = self.data.battle_data.read(); if let Some(battle_data) = &r.deref() { if let Some(battle) = battle_data.battle() { battle.event_hook().trigger( EventData::SpeciesChange { pokemon: self.clone(), species, form, }, Default::default(), ) } } Ok(()) } /// Change the form of the Pokemon. pub fn change_form(&self, form: &Arc) -> Result<()> { if self.form().eq(form.deref()) { return Ok(()); } *self.data.form.write() = form.clone(); { let mut type_lock = self.data.types.write(); type_lock.clear(); for t in form.types() { type_lock.push(*t); } } self.data.weight.store(form.weight(), Ordering::SeqCst); self.data.height.store(form.height(), Ordering::SeqCst); let ability = self.active_ability()?; let ability_script = self .data .library .load_script(self.into(), ScriptCategory::Ability, ability.name())?; if let Some(ability_script) = ability_script { let script_result = self .data .ability_script .set(ability_script) .as_ref() // Ensure the ability script gets initialized with the parameters for the ability. .on_initialize(&self.data.library, ability.parameters()); match script_result { Ok(_) => (), Err(e) => { crate::dynamic_data::script_handling::handle_script_error(&e); } } } else { self.data.ability_script.clear(); } let old_health = self.max_health(); self.recalculate_flat_stats()?; let diff_health = (self.max_health() - old_health) as i32; if self.current_health() == 0 && (self.current_health() as i32) < -diff_health { self.data.current_health.store(0, Ordering::SeqCst); } else if diff_health < 0 { self.data .current_health .fetch_sub(-diff_health as u32, Ordering::SeqCst); } else { self.data.current_health.fetch_add(diff_health as u32, Ordering::SeqCst); } // TODO: consider form specific attacks? let r = self.data.battle_data.read(); if let Some(battle_data) = r.deref() { if let Some(battle) = battle_data.battle() { battle.event_hook().trigger( EventData::FormChange { pokemon: self.clone(), form: form.clone(), }, Default::default(), ) } }; Ok(()) } /// Whether or not the Pokemon is useable in a battle. pub fn is_usable(&self) -> bool { !self.data.is_caught && !self.data.is_egg && !self.is_fainted() } /// Returns whether the Pokemon is fainted. pub fn is_fainted(&self) -> bool { self.current_health() == 0 } /// Sets the current battle the Pokemon is in. pub fn set_battle_data(&self, battle: WeakBattleReference, battle_side_index: u8) { let mut w = self.data.battle_data.write(); if let Some(battle_data) = w.deref_mut() { battle_data.battle = battle; battle_data.battle_side_index.store(battle_side_index, Ordering::SeqCst); } else { w.replace(PokemonBattleData { battle, battle_side_index: AtomicU8::new(battle_side_index), index: AtomicU8::new(0), on_battle_field: AtomicBool::new(false), seen_opponents: Default::default(), }); } } /// Sets whether or not the Pokemon is on the battlefield. pub fn set_on_battlefield(&self, value: bool) -> Result<()> { let r = self.data.battle_data.read(); if let Some(data) = &mut r.deref() { data.on_battle_field.store(value, Ordering::SeqCst); if !value { self.data.volatile.clear()?; self.data.weight.store(self.form().weight(), Ordering::SeqCst); self.data.height.store(self.form().height(), Ordering::SeqCst); } } Ok(()) } /// Sets the index of the slot of the side the Pokemon is on. pub fn set_battle_index(&self, index: u8) { let r = self.data.battle_data.read(); if let Some(data) = r.deref() { data.index.store(index, Ordering::SeqCst) } } /// Whether or not the Pokemon is on the battlefield. pub fn is_on_battlefield(&self) -> bool { self.data .battle_data .read() .as_ref() .is_some_and(|a| a.on_battle_field()) } /// Marks an opponent as seen, for use in experience gain. pub fn mark_opponent_as_seen(&self, pokemon: WeakPokemonReference) { let r = self.data.battle_data.read(); if let Some(battle_data) = r.deref() { let mut opponents = battle_data.seen_opponents().write(); for seen_opponent in opponents.deref() { if seen_opponent.eq(&pokemon) { return; } } opponents.push(pokemon); } } /// Damages the Pokemon by a certain amount of damage, from a damage source. pub fn damage(&self, mut damage: u32, source: DamageSource, evt_batch_id: EventBatchId) -> Result<()> { if damage > self.current_health() { damage = self.current_health(); } if damage == 0 { return Ok(()); } let new_health = self.current_health() - damage; if let Some(battle_data) = &self.data.battle_data.read().deref() { if let Some(battle) = battle_data.battle() { battle.event_hook().trigger( EventData::Damage { pokemon: self.clone(), source, original_health: self.current_health(), new_health, }, evt_batch_id, ); } } if self .data .battle_data .read() .as_ref() .is_some_and(|a| a.on_battle_field()) { script_hook!(on_damage, self, self, source, self.current_health(), new_health); } self.data.current_health.store(new_health, Ordering::SeqCst); if self.is_fainted() && damage > 0 { self.on_faint(source)?; } Ok(()) } /// Triggers when the Pokemon faints. fn on_faint(&self, source: DamageSource) -> Result<()> { let r = self.data.battle_data.read(); if let Some(battle_data) = r.deref() { if let Some(battle) = battle_data.battle() { battle .event_hook() .trigger(EventData::Faint { pokemon: self.clone() }, Default::default()); script_hook!(on_faint, self, self, source); script_hook!(on_remove, self,); if !battle.can_slot_be_filled(battle_data.battle_side_index(), battle_data.index()) { battle .sides() .get_res(battle_data.battle_side_index() as usize)? .mark_slot_as_unfillable(battle_data.index())?; } battle.validate_battle_state()?; } } Ok(()) } /// Heals the Pokemon by a specific amount. Unless allow_revive is set to true, this will not /// heal if the Pokemon has 0 health. If the amount healed is 0, this will return false. pub fn heal(&self, mut amount: u32, allow_revive: bool) -> bool { if self.current_health() == 0 && !allow_revive { return false; } let max_amount = self.max_health() - self.current_health(); if amount > max_amount { amount = max_amount; } if amount == 0 { return false; } let new_health = self.current_health() + max_amount; if let Some(battle_data) = &self.data.battle_data.read().deref() { if let Some(battle) = battle_data.battle() { battle.event_hook().trigger( EventData::Heal { pokemon: self.clone(), original_health: self.current_health(), new_health, }, Default::default(), ); } } self.data.current_health.store(new_health, Ordering::SeqCst); true } /// Learn a move. pub fn learn_move(&self, move_name: &StringKey, learn_method: MoveLearnMethod) -> Result<()> { let mut learned_moves = self.learned_moves().write(); let move_pos = learned_moves.iter().position(|a| a.is_none()); let move_pos = match move_pos { Some(a) => a, None => { bail!("No more moves with an empty space found."); } }; let move_data = self .data .library .static_data() .moves() .get(move_name) .ok_or(PkmnError::InvalidMoveName { move_name: move_name.clone(), })?; learned_moves .get_mut_res(move_pos)? .replace(Arc::new(LearnedMove::new(move_data, learn_method))); Ok(()) } /// Removes the current non-volatile status from the Pokemon. pub fn clear_status(&self) { self.data.status_script.clear() } /// Increases the level by a certain amount pub fn change_level_by(&self, amount: LevelInt) -> Result<()> { self.data .level .fetch_update(Ordering::SeqCst, Ordering::Relaxed, |x| { let max_level = self.library().static_data().settings().maximum_level(); if x + amount > max_level { Some(max_level) } else { Some(x + amount) } }) .ok(); self.recalculate_flat_stats() } /// Converts the Pokemon into a serializable form. #[cfg(feature = "serde")] pub fn serialize(&self) -> Result { self.into() } /// Deserializes a Pokemon from a serializable form. #[cfg(feature = "serde")] pub fn deserialize( library: &Arc, value: &super::serialization::SerializedPokemon, ) -> Result { let species = library .static_data() .species() .get(&value.species) .ok_or(PkmnError::InvalidSpeciesName { species: value.species.clone(), })?; let form = species.get_form(&value.form).ok_or(PkmnError::InvalidFormName { species: value.species.clone(), form: value.form.clone(), })?; let display_species = if let Some(v) = &value.display_species { Some( library .static_data() .species() .get(v) .ok_or(PkmnError::InvalidSpeciesName { species: v.clone() })?, ) } else { None }; let display_form = if let Some(v) = &value.display_form { if let Some(display_species) = &display_species { Some(display_species.get_form(v).ok_or(PkmnError::InvalidFormName { species: display_species.name().clone(), form: v.clone(), })?) } else { None } } else { None }; Ok(Self { data: Arc::new(PokemonData { library: library.clone(), species: RwLock::new(species), form: RwLock::new(form), display_species, display_form, level: Atomic::new(value.level), experience: AtomicU32::new(value.experience), personality_value: value.personality_value, gender: RwLock::new(value.gender), coloring: value.coloring, held_item: RwLock::new({ if let Some(v) = &value.held_item { Some( library .static_data() .items() .get(v) .ok_or(PkmnError::InvalidItemName { item: v.clone() })?, ) } else { None } }), current_health: AtomicU32::new(value.current_health), weight: Atomic::new(value.weight), height: Atomic::new(value.height), happiness: AtomicU8::new(value.happiness), flat_stats: Arc::new(Default::default()), stat_boost: Arc::new(value.stat_boosts.clone()), boosted_stats: Arc::new(Default::default()), individual_values: Arc::new(value.individual_values.clone()), effort_values: Arc::new(value.effort_values.clone()), nature: { library .static_data() .natures() .get_nature(&value.nature) .ok_or(PkmnError::InvalidNatureName { nature: value.nature.clone(), })? }, nickname: value.nickname.clone(), ability_index: value.ability_index, override_ability: { if let Some(v) = &value.override_ability { Some( library .static_data() .abilities() .get(v) .ok_or(PkmnError::InvalidAbilityName { ability: v.clone() })?, ) } else { None } }, battle_data: Default::default(), moves: { let mut moves: [Option>; MAX_MOVES] = Default::default(); for (i, v) in value.moves.iter().enumerate() { if i >= MAX_MOVES { break; } moves .get_mut(i) .replace(&mut Some(Arc::new(LearnedMove::deserialize(library, v)?))); } RwLock::new(moves) }, allowed_experience: value.allowed_experience, types: RwLock::new(value.types.clone()), is_egg: value.is_egg, is_caught: false, held_item_trigger_script: Default::default(), ability_script: Default::default(), status_script: Default::default(), volatile: Arc::new(Default::default()), script_source_data: Default::default(), }), }) } /// Take a weak reference to the Pokemon. pub fn weak(&self) -> WeakPokemonReference { WeakPokemonReference { data: Arc::downgrade(&self.data), } } /// Gets the inner pointer to the reference counted data. pub fn as_ptr(&self) -> *const c_void { Arc::as_ptr(&self.data) as *const c_void } } impl PartialEq for Pokemon { fn eq(&self, other: &Self) -> bool { Arc::ptr_eq(&self.data, &other.data) } } impl Eq for Pokemon {} impl PartialEq for WeakPokemonReference { fn eq(&self, other: &Self) -> bool { Weak::ptr_eq(&self.data, &other.data) } } impl Eq for WeakPokemonReference {} impl WeakPokemonReference { /// Attempts to upgrade the weak reference to a strong reference. pub fn upgrade(&self) -> Option { Some(Pokemon { data: self.data.upgrade()?, }) } /// Gets the pointer to the underlying data. #[cfg(feature = "wasm")] pub(crate) fn as_ptr(&self) -> *const c_void { self.data.as_ptr() as *const c_void } } /// The data of the Pokemon related to being in a battle. #[derive(Debug)] pub struct PokemonBattleData { /// The battle data of the Pokemon battle: WeakBattleReference, /// The index of the side of the Pokemon battle_side_index: AtomicU8, /// The index of the slot on the side of the Pokemon. index: AtomicU8, /// Whether or not the Pokemon is on the battlefield. on_battle_field: AtomicBool, /// A list of opponents the Pokemon has seen this battle. seen_opponents: RwLock>, } impl PokemonBattleData { /// The battle data of the Pokemon pub fn battle(&self) -> Option { self.battle.upgrade() } /// The index of the side of the Pokemon pub fn battle_side_index(&self) -> u8 { self.battle_side_index.load(Ordering::Relaxed) } /// The index of the slot on the side of the Pokemon. pub fn index(&self) -> u8 { self.index.load(Ordering::Relaxed) } /// Whether or not the Pokemon is on the battlefield. pub fn on_battle_field(&self) -> bool { self.on_battle_field.load(Ordering::Relaxed) } /// A list of opponents the Pokemon has seen this battle. pub fn seen_opponents(&self) -> &RwLock> { &self.seen_opponents } } impl ScriptSource for Pokemon { fn get_script_count(&self) -> Result { let mut c = 3; if let Some(battle_data) = &self.data.battle_data.read().deref() { if let Some(battle) = battle_data.battle() { c += battle .sides() .get_res(battle_data.battle_side_index() as usize)? .get_script_count()?; } } Ok(c) } fn get_script_source_data(&self) -> &RwLock { &self.data.script_source_data } fn get_own_scripts(&self, scripts: &mut Vec) { scripts.push((&self.data.held_item_trigger_script).into()); scripts.push((&self.data.ability_script).into()); scripts.push((&self.data.status_script).into()); scripts.push((&self.data.volatile).into()); } fn collect_scripts(&self, scripts: &mut Vec) -> Result<()> { self.get_own_scripts(scripts); if let Some(battle_data) = &self.data.battle_data.read().deref() { if let Some(battle) = battle_data.battle() { battle .sides() .get_res(battle_data.battle_side_index() as usize)? .collect_scripts(scripts)?; } } Ok(()) } } impl VolatileScriptsOwner for Pokemon { fn volatile_scripts(&self) -> &Arc { &self.data.volatile } fn load_volatile_script(&self, key: &StringKey) -> Result>> { self.data.library.load_script(self.into(), ScriptCategory::Pokemon, key) } } /// A source of damage. #[derive(Debug, Clone, Copy)] #[repr(u8)] pub enum DamageSource { /// The damage is done by a move. MoveDamage = 0, /// The damage is done by something else. Misc = 1, /// The damage is done because of struggling. Struggle = 2, } impl Debug for Pokemon { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str("Pokemon(")?; write!(f, "Species: {}, ", self.species().name())?; write!(f, "Form: {}, ", self.form().name())?; write!(f, "Level: {}, ", self.level())?; f.write_str(")")?; Ok(()) } } #[cfg(test)] #[allow(clippy::unwrap_used)] pub mod test { use crate::dynamic_data::libraries::test::MockDynamicLibrary; use crate::dynamic_data::models::pokemon::Pokemon; use crate::dynamic_data::tests::MockBattleStatCalculator; use crate::dynamic_data::DynamicLibrary; use crate::static_data::growth_rate_library::tests::MockGrowthRateLibrary; use crate::static_data::nature_library::tests::MockNatureLibrary; use crate::static_data::species_library::tests::MockSpeciesLibrary; use crate::static_data::test::MockStaticData; use crate::static_data::tests::{MockForm, MockNature, MockSpecies}; use crate::static_data::{AbilityIndex, Species}; use crate::static_data::{Form, Gender}; use crate::StringKey; use std::sync::Arc; pub fn mock_library() -> Arc { let mut species_lib = MockSpeciesLibrary::new(); species_lib.expect_get().return_once(|_| { let mut species = MockSpecies::new(); species.expect_get_form().return_once(|_| { let mut form = MockForm::new(); form.expect_name().return_const(StringKey::new("default")); form.expect_weight().return_const(100.0); form.expect_height().return_const(20.0); form.expect_types().return_const(vec![0u8.into()]); let a: Arc = Arc::new(form); Some(a) }); species.expect_growth_rate().return_const(StringKey::empty()); species.expect_name().return_const(StringKey::new("test_species")); species.expect_base_happiness().return_const(100); let s: Arc = Arc::new(species); Some(s) }); let mut static_lib = MockStaticData::new(); static_lib.expect_species().return_const(Arc::new(species_lib)); let mut growth_rate_lib = MockGrowthRateLibrary::new(); growth_rate_lib .expect_calculate_experience() .returning(|_, _| Ok(1000u32)); let mut nature_lib = MockNatureLibrary::new(); nature_lib.expect_get_nature().returning(|_| { let n = MockNature::new(); Some(Arc::new(n)) }); static_lib.expect_growth_rates().return_const(Arc::new(growth_rate_lib)); static_lib.expect_natures().return_const(Arc::new(nature_lib)); let mut stat_calculator = MockBattleStatCalculator::new(); stat_calculator.expect_calculate_flat_stats().returning(|_, _| Ok(())); stat_calculator .expect_calculate_boosted_stats() .returning(|_, _| Ok(())); let mut lib = MockDynamicLibrary::new(); lib.expect_static_data().return_const(Arc::new(static_lib)); lib.expect_stat_calculator().return_const(Arc::new(stat_calculator)); Arc::new(lib) } #[test] fn construct_pokemon() { let lib = mock_library(); let species = lib.static_data().species().get(&"foo".into()).unwrap(); let form = species.get_form(&"default".into()).unwrap(); let pokemon = Pokemon::new( lib, species, &form, AbilityIndex { hidden: false, index: 0, }, 10, 0, Gender::Male, 0, &"test_nature".into(), ) .unwrap(); assert_eq!(pokemon.species().name(), &"test_species".into()); assert_eq!(pokemon.form().name(), &"default".into()); } }