More work on using interior mutability instead of exterior mutability for dynamic types (Battle, Pokemon, etc).
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2022-06-18 15:52:39 +02:00
parent c45c7538bf
commit 5576bc8b80
21 changed files with 324 additions and 385 deletions

View File

@@ -19,17 +19,19 @@ use crate::static_data::statistic_set::{ClampedStatisticSet, StatisticSet};
use crate::static_data::DataLibrary;
use crate::utils::random::Random;
use crate::{script_hook, PkmnResult, ScriptCategory, StringKey};
use atomic::Atomic;
use parking_lot::RwLock;
use std::sync::atomic::{AtomicI8, AtomicU32, AtomicU8, Ordering};
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicBool, AtomicI8, AtomicU32, AtomicU8, Ordering};
use std::sync::{Arc, Weak};
#[derive(Debug)]
pub struct PokemonBattleData<'pokemon, 'library> {
battle: *mut Battle<'pokemon, 'library>,
battle_side_index: u8,
index: u8,
on_battle_field: bool,
seen_opponents: Vec<Weak<RwLock<Pokemon<'pokemon, 'library>>>>,
battle_side_index: AtomicU8,
index: AtomicU8,
on_battle_field: AtomicBool,
seen_opponents: RwLock<Vec<Weak<Pokemon<'pokemon, 'library>>>>,
}
impl<'pokemon, 'library> PokemonBattleData<'pokemon, 'library> {
@@ -41,13 +43,16 @@ impl<'pokemon, 'library> PokemonBattleData<'pokemon, 'library> {
}
pub fn battle_side_index(&self) -> u8 {
self.battle_side_index
self.battle_side_index.load(Ordering::Relaxed)
}
pub fn on_battle_field(&mut self) -> &mut bool {
&mut self.on_battle_field
pub fn index(&self) -> u8 {
self.index.load(Ordering::Relaxed)
}
pub fn seen_opponents(&mut self) -> &mut Vec<Weak<RwLock<Pokemon<'pokemon, 'library>>>> {
&mut self.seen_opponents
pub fn on_battle_field(&self) -> bool {
self.on_battle_field.load(Ordering::Relaxed)
}
pub fn seen_opponents(&self) -> &RwLock<Vec<Weak<Pokemon<'pokemon, 'library>>>> {
&self.seen_opponents
}
}
@@ -71,8 +76,8 @@ where
held_item: Option<&'own Item>,
current_health: AtomicU32,
weight: f32,
height: f32,
weight: Atomic<f32>,
height: Atomic<f32>,
stat_boost: ClampedStatisticSet<AtomicI8, -6, 6>,
flat_stats: StatisticSet<AtomicU32>,
@@ -87,9 +92,9 @@ where
is_ability_overridden: bool,
override_ability: Option<Ability>,
battle_data: Option<PokemonBattleData<'own, 'library>>,
battle_data: RwLock<Option<PokemonBattleData<'own, 'library>>>,
moves: [Option<Arc<LearnedMove<'library>>>; MAX_MOVES],
moves: RwLock<[Option<Arc<LearnedMove<'library>>>; MAX_MOVES]>,
allowed_experience: bool,
types: Vec<u8>,
@@ -141,8 +146,8 @@ impl<'own, 'library> Pokemon<'own, 'library> {
coloring,
held_item: None,
current_health: AtomicU32::new(1),
weight,
height,
weight: Atomic::new(weight),
height: Atomic::new(height),
stat_boost: Default::default(),
flat_stats: Default::default(),
boosted_stats: Default::default(),
@@ -153,8 +158,8 @@ impl<'own, 'library> Pokemon<'own, 'library> {
ability_index: ability,
is_ability_overridden: false,
override_ability: None,
battle_data: None,
moves: [None, None, None, None],
battle_data: RwLock::new(None),
moves: RwLock::new([None, None, None, None]),
allowed_experience: false,
types: form.types().to_vec(),
is_egg: false,
@@ -247,10 +252,10 @@ impl<'own, 'library> Pokemon<'own, 'library> {
self.boosted_stats.hp()
}
pub fn weight(&self) -> f32 {
self.weight
self.weight.load(Ordering::Relaxed)
}
pub fn height(&self) -> f32 {
self.height
self.height.load(Ordering::Relaxed)
}
pub fn nickname(&self) -> &Option<String> {
&self.nickname
@@ -261,7 +266,7 @@ impl<'own, 'library> Pokemon<'own, 'library> {
pub fn types(&self) -> &Vec<u8> {
&self.types
}
pub fn learned_moves(&self) -> &[Option<Arc<LearnedMove<'library>>>; MAX_MOVES] {
pub fn learned_moves(&self) -> &RwLock<[Option<Arc<LearnedMove<'library>>>; MAX_MOVES]> {
&self.moves
}
pub fn status(&self) -> &ScriptContainer {
@@ -284,17 +289,18 @@ impl<'own, 'library> Pokemon<'own, 'library> {
}
pub fn get_battle(&self) -> Option<&Battle<'own, 'library>> {
if let Some(data) = &self.battle_data {
Some(data.battle().unwrap())
let r = self.battle_data.read();
if let Some(data) = &r.deref() {
unsafe { data.battle.as_ref() }
} else {
None
}
}
pub fn get_battle_side_index(&self) -> Option<u8> {
self.battle_data.as_ref().map(|data| data.battle_side_index)
self.battle_data.read().as_ref().map(|data| data.battle_side_index())
}
pub fn get_battle_index(&self) -> Option<u8> {
self.battle_data.as_ref().map(|data| data.index)
self.battle_data.read().as_ref().map(|data| data.index())
}
pub fn is_ability_overriden(&self) -> bool {
self.is_ability_overridden
@@ -316,13 +322,9 @@ impl<'own, 'library> Pokemon<'own, 'library> {
&self.ability_script
}
pub fn seen_opponents(&self) -> Option<&Vec<Weak<RwLock<Pokemon<'own, 'library>>>>> {
if let Some(data) = &self.battle_data {
Some(&data.seen_opponents)
} else {
None
}
}
// pub fn seen_opponents(&self) -> &RwLock<Option<PokemonBattleData<'own, 'library>>> {
// &self.battle_data.read
// }
pub fn allowed_experience_gain(&self) -> bool {
self.allowed_experience
}
@@ -331,12 +333,16 @@ impl<'own, 'library> Pokemon<'own, 'library> {
self.nature
}
pub fn recalculate_flat_stats(&mut self) {
self.flat_stats = self.library.stat_calculator().calculate_flat_stats(self);
pub fn recalculate_flat_stats(&self) {
self.library
.stat_calculator()
.calculate_flat_stats(self, &self.flat_stats);
self.recalculate_boosted_stats();
}
pub fn recalculate_boosted_stats(&mut self) {
self.boosted_stats = self.library.stat_calculator().calculate_boosted_stats(self);
pub fn recalculate_boosted_stats(&self) {
self.library
.stat_calculator()
.calculate_boosted_stats(self, &self.boosted_stats);
}
pub fn change_species(&mut self, species: &'own Species, form: &'own Form) {
@@ -346,10 +352,10 @@ impl<'own, 'library> Pokemon<'own, 'library> {
// 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
if self.battle_data.is_some() {
let battle_data = self.battle_data.as_mut().unwrap();
self.gender =
species.get_random_gender(&mut battle_data.battle().unwrap().random().get_rng().lock().unwrap());
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());
@@ -359,7 +365,8 @@ impl<'own, 'library> Pokemon<'own, 'library> {
else if species.gender_rate() < 0.0 && self.gender != Gender::Genderless {
self.gender = Gender::Genderless;
}
if let Some(battle_data) = &self.battle_data {
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,
@@ -380,8 +387,8 @@ impl<'own, 'library> Pokemon<'own, 'library> {
for t in form.types() {
self.types.push(*t);
}
self.weight = form.weight();
self.height = form.height();
self.weight.store(form.weight(), Ordering::SeqCst);
self.height.store(form.height(), Ordering::SeqCst);
let ability_script = self
.library
@@ -409,7 +416,8 @@ impl<'own, 'library> Pokemon<'own, 'library> {
}
// TODO: consider form specific attacks?
if let Some(battle_data) = &self.battle_data {
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 })
}
@@ -424,58 +432,59 @@ impl<'own, 'library> Pokemon<'own, 'library> {
self.current_health() == 0
}
pub fn set_battle_data(&mut self, battle: *mut Battle<'own, 'library>, battle_side_index: u8) {
if let Some(battle_data) = &mut self.battle_data {
pub fn set_battle_data(&self, battle: *mut Battle<'own, 'library>, 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 = battle_side_index;
battle_data.battle_side_index.store(battle_side_index, Ordering::SeqCst);
} else {
self.battle_data = Some(PokemonBattleData {
w.replace(PokemonBattleData {
battle,
battle_side_index,
index: 0,
on_battle_field: false,
battle_side_index: AtomicU8::new(battle_side_index),
index: AtomicU8::new(0),
on_battle_field: AtomicBool::new(false),
seen_opponents: Default::default(),
})
});
}
}
pub fn set_on_battlefield(&mut self, value: bool) {
if let Some(data) = &mut self.battle_data {
data.on_battle_field = value;
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.write().clear();
self.weight = self.form.weight();
self.height = self.form.height();
self.weight.store(self.form.weight(), Ordering::SeqCst);
self.height.store(self.form.height(), Ordering::SeqCst);
}
}
}
pub fn set_battle_index(&mut self, index: u8) {
if let Some(data) = &mut self.battle_data {
data.index = index;
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)
}
}
pub fn is_on_battlefield(&self) -> bool {
if let Some(data) = &self.battle_data {
data.on_battle_field
} else {
false
}
self.battle_data.read().is_some_and(|a| a.on_battle_field())
}
pub fn mark_opponent_as_seen(&mut self, pokemon: Weak<RwLock<Pokemon<'own, 'library>>>) {
if let Some(battle_data) = &mut self.battle_data {
for seen_opponent in &battle_data.seen_opponents {
pub fn mark_opponent_as_seen(&self, pokemon: Weak<Pokemon<'own, 'library>>) {
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;
}
}
battle_data.seen_opponents.push(pokemon);
opponents.push(pokemon);
}
}
pub fn damage(&mut self, mut damage: u32, source: DamageSource) {
pub fn damage(&self, mut damage: u32, source: DamageSource) {
if damage > self.current_health() {
damage = self.current_health();
}
@@ -483,7 +492,7 @@ impl<'own, 'library> Pokemon<'own, 'library> {
return;
}
let new_health = self.current_health() - damage;
if let Some(battle_data) = &self.battle_data {
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,
@@ -492,65 +501,53 @@ impl<'own, 'library> Pokemon<'own, 'library> {
new_health,
});
// TODO: register history
script_hook!(on_damage, self, self, source, 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);
}
}
pub fn on_faint(&mut self, source: DamageSource) {
if self.battle_data.is_some() && self.battle_data.as_ref().unwrap().battle().is_some() {
self.battle_data
.as_ref()
.unwrap()
.battle()
.unwrap()
.event_hook()
.trigger(Event::Faint { pokemon: self });
script_hook!(on_faint, self, self, source);
script_hook!(on_remove, self,);
pub 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,);
let side_index = self.battle_data.as_ref().unwrap().battle_side_index;
let index = self.battle_data.as_ref().unwrap().index;
if !self
.battle_data
.as_ref()
.unwrap()
.battle()
.unwrap()
.can_slot_be_filled(side_index, index)
{
self.battle_data.as_mut().unwrap().battle_mut().unwrap().sides_mut()[side_index as usize]
.mark_slot_as_unfillable(index);
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();
}
self.battle_data
.as_mut()
.unwrap()
.battle_mut()
.unwrap()
.validate_battle_state();
}
}
pub fn learn_move(&mut self, move_name: &StringKey, learn_method: MoveLearnMethod) {
let move_pos = self.learned_moves().iter().position(|a| a.is_none());
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();
self.moves[move_pos.unwrap()] = Some(Arc::new(LearnedMove::new(move_data, learn_method)));
learned_moves[move_pos.unwrap()] = Some(Arc::new(LearnedMove::new(move_data, learn_method)));
}
}
impl<'own, 'library> ScriptSource<'own> for Pokemon<'own, 'library> {
fn get_script_count(&self) -> usize {
let mut c = 3;
if let Some(battle_data) = &self.battle_data {
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 += battle.sides()[battle_data.battle_side_index() as usize].get_script_count();
}
}
c
@@ -569,9 +566,9 @@ impl<'own, 'library> ScriptSource<'own> for Pokemon<'own, 'library> {
fn collect_scripts(&self, scripts: &mut Vec<ScriptWrapper>) {
self.get_own_scripts(scripts);
if let Some(battle_data) = &self.battle_data {
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);
battle.sides()[battle_data.battle_side_index() as usize].collect_scripts(scripts);
}
}
}