Cache pokemon in PokemonParty so they're not garbage collected.

This commit is contained in:
Deukhoofd 2020-08-25 17:56:57 +02:00
parent b1f134c2a1
commit 2ded1d3ceb
Signed by: Deukhoofd
GPG Key ID: F63E044490819F6F
1 changed files with 15 additions and 3 deletions

View File

@ -8,6 +8,7 @@ namespace PkmnLibSharp.Battling
{ {
public class PokemonParty : PointerWrapper, IEnumerable<Pokemon> public class PokemonParty : PointerWrapper, IEnumerable<Pokemon>
{ {
private Pokemon?[]? _cache;
private ReadOnlyNativePtrArray<Pokemon>? _party; private ReadOnlyNativePtrArray<Pokemon>? _party;
internal PokemonParty(IntPtr ptr) : base(ptr){} internal PokemonParty(IntPtr ptr) : base(ptr){}
@ -18,10 +19,15 @@ namespace PkmnLibSharp.Battling
public PokemonParty(Pokemon?[] pokemon) : base( public PokemonParty(Pokemon?[] pokemon) : base(
Creaturelib.Generated.CreatureParty.ConstructFromArray(pokemon.ArrayPtr(), (ulong) pokemon.Length)) Creaturelib.Generated.CreatureParty.ConstructFromArray(pokemon.ArrayPtr(), (ulong) pokemon.Length))
{ {
for (var index = 0; index < pokemon.Length; index++) _cache = pokemon;
pokemon[index] = null;
} }
protected internal override void Initialize(IntPtr ptr)
{
base.Initialize(ptr);
_cache = Party.ToArray();
}
public virtual Pokemon this[int i] => GetAtIndex((ulong) i); public virtual Pokemon this[int i] => GetAtIndex((ulong) i);
public Pokemon GetAtIndex(ulong index) public Pokemon GetAtIndex(ulong index)
@ -34,12 +40,16 @@ namespace PkmnLibSharp.Battling
public void Switch(ulong indexA, ulong indexB) public void Switch(ulong indexA, ulong indexB)
{ {
Creaturelib.Generated.CreatureParty.Switch(Ptr, indexA, indexB); Creaturelib.Generated.CreatureParty.Switch(Ptr, indexA, indexB);
var temp = _cache![indexA];
_cache[indexA] = _cache[indexB];
_cache[indexB] = temp;
} }
public Pokemon SwapInto(ulong indexA, Pokemon pokemon) public Pokemon SwapInto(ulong indexA, Pokemon pokemon)
{ {
var ptr = IntPtr.Zero; var ptr = IntPtr.Zero;
Creaturelib.Generated.CreatureParty.SwapInto(ref ptr, Ptr, indexA, pokemon.Ptr).Assert(); Creaturelib.Generated.CreatureParty.SwapInto(ref ptr, Ptr, indexA, pokemon.Ptr).Assert();
_cache![indexA] = pokemon;
if (TryResolvePointer(ptr, out Pokemon? newPokemon)) if (TryResolvePointer(ptr, out Pokemon? newPokemon))
return newPokemon!; return newPokemon!;
return Constructor.Active.ConstructPokemon(ptr)!; return Constructor.Active.ConstructPokemon(ptr)!;
@ -66,6 +76,7 @@ namespace PkmnLibSharp.Battling
public void PackParty() public void PackParty()
{ {
Creaturelib.Generated.CreatureParty.PackParty(Ptr); Creaturelib.Generated.CreatureParty.PackParty(Ptr);
_cache = Party.ToArray();
} }
public IEnumerator<Pokemon?> GetEnumerator() public IEnumerator<Pokemon?> GetEnumerator()
@ -90,6 +101,7 @@ namespace PkmnLibSharp.Battling
{ {
pokemon?.MarkAsDeleted(); pokemon?.MarkAsDeleted();
} }
_cache = null;
} }