use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU8, Ordering}; use std::sync::{Arc, Weak}; use atomig::Atomic; use parking_lot::RwLock; use crate::defines::{LevelInt, MAX_MOVES}; use crate::dynamic_data::event_hooks::Event; 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, Script, ScriptCategory, ScriptContainer, ScriptSet, VolatileScriptsOwner}; 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::{AbilityIndex, DataLibrary}; use crate::static_data::{ClampedStatisticSet, StatisticSet}; use crate::utils::Random; use crate::{script_hook, PkmnResult, StringKey}; /// An individual Pokemon as we know and love them. #[derive(Debug)] #[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))] pub struct Pokemon { /// The library data of the Pokemon. library: Arc, /// The species of the Pokemon. species: Arc, /// The form of the Pokemon. form: Arc
, /// 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: LevelInt, /// The amount of experience of the Pokemon. experience: AtomicU32, /// A unique random number for this Pokemon. unique_identifier: u32, /// The gender of the Pokemon. gender: Gender, /// 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 stats of the Pokemon when disregarding any stat boosts. flat_stats: StatisticSet, /// The statistics boosts of the Pokemon. Will prevent the value from going above 6, and below /// -6. stat_boost: ClampedStatisticSet, /// The stats of the Pokemon including the stat boosts boosted_stats: StatisticSet, /// The [individual values](https://bulbapedia.bulbagarden.net/wiki/Individual_values) of the Pokemon. individual_values: ClampedStatisticSet, /// The [effort values](https://bulbapedia.bulbagarden.net/wiki/Effort_values) of the Pokemon. effort_values: ClampedStatisticSet, /// 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: Vec, /// 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, } 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, ) -> Self { // 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 nature = library .static_data() .natures() .get_nature(nature) .unwrap_or_else(|| panic!("Unknown nature name was given: {}.", &nature)) .clone(); let mut pokemon = Self { library, species, form: form.clone(), display_species: None, display_form: None, level, experience: AtomicU32::new(experience), unique_identifier, 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([None, None, None, None]), allowed_experience: false, types: 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(), }; pokemon.recalculate_flat_stats(); let health = pokemon.flat_stats().hp(); pokemon.current_health = AtomicU32::new(health); pokemon } /// The library data of the Pokemon. pub fn library(&self) -> &Arc { &self.library } /// The species of the Pokemon. pub fn species(&self) -> &Arc { &self.species } /// The form of the Pokemon. pub fn form(&self) -> &Arc { &self.form } /// 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.display_species { v } else { &self.species } } /// 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.display_form { v } else { &self.form } } /// The current level of the Pokemon. pub fn level(&self) -> LevelInt { self.level } /// The amount of experience of the Pokemon. pub fn experience(&self) -> u32 { self.experience.load(Ordering::Relaxed) } /// A unique random number for this Pokemon. pub fn unique_identifier(&self) -> u32 { self.unique_identifier } /// The gender of the Pokemon. pub fn gender(&self) -> Gender { self.gender } /// 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.coloring } /// Gets the held item of a Pokemon pub fn held_item(&self) -> &RwLock>> { &self.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.held_item.read().deref() { return v.name() == name; } false } /// Changes the held item of the Pokemon/ pub fn set_held_item(&self, item: &Arc) -> Option> { self.held_item.write().replace(item.clone()) } /// Removes the held item from the Pokemon. pub fn remove_held_item(&self) -> Option> { self.held_item.write().take() } /// Makes the Pokemon uses its held item. pub fn consume_held_item(&self) -> bool { if self.held_item.read().is_none() { return false; } let script = self .library .load_item_script(self.held_item.read().as_ref().unwrap()) .unwrap(); if script.is_none() { return false; } // TODO: the entire item use part. todo!(); } /// The remaining health points of the Pokemon. pub fn current_health(&self) -> u32 { self.current_health.load(Ordering::Relaxed) } /// The max health points of the Pokemon. pub fn max_health(&self) -> u32 { self.boosted_stats.hp() } /// The weight of the Pokemon in kilograms. pub fn weight(&self) -> f32 { self.weight.load(Ordering::Relaxed) } /// The height of the Pokemon in meters. pub fn height(&self) -> f32 { self.height.load(Ordering::Relaxed) } /// An optional nickname of the Pokemon. pub fn nickname(&self) -> &Option { &self.nickname } /// An index of the ability to find the actual ability on the form. pub fn real_ability(&self) -> &AbilityIndex { &self.ability_index } /// The current types of the Pokemon. pub fn types(&self) -> &Vec { &self.types } /// 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.moves } /// The stats of the Pokemon when disregarding any stat boosts. pub fn flat_stats(&self) -> &StatisticSet { &self.flat_stats } /// The stats of the Pokemon including the stat boosts pub fn stat_boosts(&self) -> &ClampedStatisticSet { &self.stat_boost } /// The stats of the Pokemon including the stat boosts pub fn boosted_stats(&self) -> &StatisticSet { &self.boosted_stats } /// Get the stat boosts for a specific stat. pub fn stat_boost(&self, stat: Statistic) -> i8 { self.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) -> bool { let mut prevent = false; script_hook!( prevent_stat_boost_change, self, self, stat, diff_amount, self_inflicted, &mut prevent ); if prevent { return false; } script_hook!( change_stat_boost_change, self, self, stat, self_inflicted, &mut diff_amount ); if diff_amount == 0 { return false; } let mut changed = false; let old_value = self.stat_boost.get_stat(stat); match diff_amount.cmp(&0_i8) { std::cmp::Ordering::Less => { changed = self.stat_boost.decrease_stat(stat, -diff_amount); } std::cmp::Ordering::Greater => { changed = self.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(Event::StatBoostChange { user: self, stat, old_value, new_value, }) } self.recalculate_boosted_stats(); } changed } /// The [individual values](https://bulbapedia.bulbagarden.net/wiki/Individual_values) of the Pokemon. pub fn individual_values(&self) -> &ClampedStatisticSet { &self.individual_values } /// The [effort values](https://bulbapedia.bulbagarden.net/wiki/Effort_values) of the Pokemon. pub fn effort_values(&self) -> &ClampedStatisticSet { &self.effort_values } /// Gets the battle the battle is currently in. pub fn get_battle(&self) -> Option<&Battle> { let r = self.battle_data.read(); if let Some(data) = &r.deref() { unsafe { data.battle.as_ref() } } 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.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.battle_data.read().as_ref().map(|data| data.index()) } /// Returns whether something overrides the ability. pub fn is_ability_overriden(&self) -> bool { self.override_ability.is_some() } /// Returns the currently active ability. pub fn active_ability(&self) -> &Ability { if let Some(v) = &self.override_ability { return v; } self.library .static_data() .abilities() .get(self.form.get_ability(self.ability_index)) .unwrap() } /// The script for the status. pub fn status(&self) -> &ScriptContainer { &self.status_script } /// Returns the script for the currently active ability. pub fn ability_script(&self) -> &ScriptContainer { &self.ability_script } /// Whether or not the Pokemon is allowed to gain experience. pub fn allowed_experience_gain(&self) -> bool { self.allowed_experience } /// The [nature](https://bulbapedia.bulbagarden.net/wiki/Nature) of the Pokemon. pub fn nature(&self) -> &Arc { &self.nature } /// Calculates the flat stats on the Pokemon. pub fn recalculate_flat_stats(&self) { self.library .stat_calculator() .calculate_flat_stats(self, &self.flat_stats); self.recalculate_boosted_stats(); } /// Calculates the boosted stats on the Pokemon. pub fn recalculate_boosted_stats(&self) { self.library .stat_calculator() .calculate_boosted_stats(self, &self.boosted_stats); } /// Change the species of the Pokemon. pub fn change_species(&mut self, species: Arc, form: Arc) { self.species = species.clone(); self.form = 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.battle_data.read(); if let Some(data) = r.deref() { let mut random = data.battle().unwrap().random().get_rng().lock().unwrap(); self.gender = species.get_random_gender(random.deref_mut()); } else { // If we're not in battle, just use a new random. self.gender = 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.gender = Gender::Genderless; } let r = self.battle_data.read(); if let Some(battle_data) = &r.deref() { if let Some(battle) = battle_data.battle() { battle.event_hook().trigger(Event::SpeciesChange { pokemon: self, species, form, }) } } } /// Change the form of the Pokemon. pub fn change_form(&mut self, form: &Arc) { if Arc::ptr_eq(&self.form, form) { return; } self.form = form.clone(); self.types.clear(); for t in form.types() { self.types.push(*t); } self.weight.store(form.weight(), Ordering::SeqCst); self.height.store(form.height(), Ordering::SeqCst); let ability_script = self .library .load_script((&*self).into(), ScriptCategory::Ability, self.active_ability().name()) .unwrap(); if let Some(ability_script) = ability_script { self.ability_script .set(ability_script) .as_ref() // Ensure the ability script gets initialized with the parameters for the ability. .on_initialize(self.library.as_ref(), self.active_ability().parameters()) } else { self.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.current_health.store(0, Ordering::SeqCst); } else if diff_health < 0 { self.current_health.fetch_sub(-diff_health as u32, Ordering::SeqCst); } else { self.current_health.fetch_add(diff_health as u32, Ordering::SeqCst); } // TODO: consider form specific attacks? let r = self.battle_data.read(); if let Some(battle_data) = r.deref() { if let Some(battle) = battle_data.battle() { battle.event_hook().trigger(Event::FormChange { pokemon: self, form }) } } } /// Whether or not the Pokemon is useable in a battle. pub fn is_usable(&self) -> bool { !self.is_caught && !self.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: *mut Battle, battle_side_index: u8) { let mut w = self.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) { let r = self.battle_data.read(); if let Some(data) = &mut r.deref() { data.on_battle_field.store(value, Ordering::SeqCst); if !value { self.volatile.clear(); self.weight.store(self.form.weight(), Ordering::SeqCst); self.height.store(self.form.height(), Ordering::SeqCst); } } } /// Sets the index of the slot of the side the Pokemon is on. pub fn set_battle_index(&self, index: u8) { let r = self.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.battle_data.read().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: Weak) { let r = self.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.ptr_eq(&pokemon) { return; } } opponents.push(pokemon); } } /// Damages the Pokemon by a certain amount of damage, from a specific damage source. pub fn damage(&self, mut damage: u32, source: DamageSource) { if damage > self.current_health() { damage = self.current_health(); } if damage == 0 { return; } let new_health = self.current_health() - damage; if let Some(battle_data) = &self.battle_data.read().deref() { if let Some(battle) = battle_data.battle() { battle.event_hook().trigger(Event::Damage { pokemon: self, source, original_health: self.current_health(), new_health, }); } } if self.battle_data.read().is_some_and(|a| a.on_battle_field()) { script_hook!(on_damage, self, self, source, self.current_health(), new_health); } self.current_health.store(new_health, Ordering::SeqCst); if self.is_fainted() && damage > 0 { self.on_faint(source); } } /// Triggers when the Pokemon faints. fn on_faint(&self, source: DamageSource) { let r = self.battle_data.read(); if let Some(battle_data) = r.deref() { if let Some(battle) = battle_data.battle() { battle.event_hook().trigger(Event::Faint { pokemon: self }); 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()[battle_data.battle_side_index() as usize] .mark_slot_as_unfillable(battle_data.index()); } battle.validate_battle_state(); } } } /// 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.battle_data.read().deref() { if let Some(battle) = battle_data.battle() { battle.event_hook().trigger(Event::Heal { pokemon: self, original_health: self.current_health(), new_health, }); } } self.current_health.store(new_health, Ordering::SeqCst); true } /// Learn a move. pub fn learn_move(&self, move_name: &StringKey, learn_method: MoveLearnMethod) { let mut learned_moves = self.learned_moves().write(); let move_pos = learned_moves.iter().position(|a| a.is_none()); if move_pos.is_none() { panic!("No more moves with an empty space found."); } let move_data = self.library.static_data().moves().get(move_name).unwrap(); learned_moves[move_pos.unwrap()] = Some(Arc::new(LearnedMove::new(move_data, learn_method))); } } /// The data of the Pokemon related to being in a battle. #[derive(Debug)] pub struct PokemonBattleData { /// The battle data of the Pokemon battle: *mut Battle, /// 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_mut(&mut self) -> Option<&mut Battle> { unsafe { self.battle.as_mut() } } /// The battle data of the Pokemon pub fn battle(&self) -> Option<&Battle> { unsafe { self.battle.as_ref() } } /// 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) -> usize { let mut c = 3; if let Some(battle_data) = &self.battle_data.read().deref() { if let Some(battle) = battle_data.battle() { c += battle.sides()[battle_data.battle_side_index() as usize].get_script_count(); } } c } fn get_script_source_data(&self) -> &RwLock { &self.script_source_data } fn get_own_scripts(&self, scripts: &mut Vec) { scripts.push((&self.held_item_trigger_script).into()); scripts.push((&self.ability_script).into()); scripts.push((&self.status_script).into()); scripts.push((&self.volatile).into()); } fn collect_scripts(&self, scripts: &mut Vec) { self.get_own_scripts(scripts); if let Some(battle_data) = &self.battle_data.read().deref() { if let Some(battle) = battle_data.battle() { battle.sides()[battle_data.battle_side_index() as usize].collect_scripts(scripts); } } } } impl VolatileScriptsOwner for Pokemon { fn volatile_scripts(&self) -> &Arc { &self.volatile } fn load_volatile_script(&self, key: &StringKey) -> PkmnResult>> { self.library.load_script(self.into(), ScriptCategory::Pokemon, key) } } /// A source of damage. This should be as unique as possible. #[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, } #[cfg(test)] pub mod test { use crate::dynamic_data::models::pokemon::Pokemon; use crate::static_data::Gender; use crate::static_data::{AbilityIndex, DataLibrary}; use std::sync::Arc; #[test] fn construct_pokemon() { let lib = Arc::new(crate::dynamic_data::libraries::dynamic_library::test::build()); let species = lib.static_data().species().get(&"foo".into()).unwrap().clone(); let form = species.get_form(&"default".into()).unwrap().clone(); let pokemon = Pokemon::new( lib, species, &form, AbilityIndex { hidden: false, index: 0, }, 10, 0, Gender::Male, 0, &"test_nature".into(), ); assert_eq!(pokemon.species.name(), &"foo".into()); assert_eq!(pokemon.form.name(), &"default".into()); } }