Skip to content

Commit

Permalink
I think I finally fixed the thread hanging stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
FM1337 committed Aug 2, 2020
1 parent 804d88b commit 408a37f
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 81 deletions.
5 changes: 2 additions & 3 deletions Controllers/LegalizeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,12 @@ public Legalize Legalize([FromForm] [Required] IFormFile pokemon, [FromForm] str
{
version = Utils.GetGameVersion(pkm).ToString();
}
if(!Utils.PokemonExistsInGeneration(generation, pkm.Species))
if (!Utils.PokemonExistsInGeneration(generation, pkm.Species))
{
Response.StatusCode = 400;
return null;
}
Legalize L = new Legalize(pkm, version);
return L;
return new Legalize(pkm, version);
}
// POST: api/LegalityCheck
[Route("api/LegalityCheck")]
Expand Down
105 changes: 41 additions & 64 deletions Helpers/AutoLegality.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,21 @@
using PKHeX.Core;
using PKHeX.Core.AutoMod;
using Microsoft.Extensions.FileSystemGlobbing.Internal.Patterns;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace CoreAPI.Helpers
{

public class AutoLegality
{
private PKM startingPK;
private CancellationTokenSource cts;
private GameVersion gv;
private static PKM legalpk;
private static LegalityAnalysis la;
private static bool Initialized;
private readonly Random _random = new Random();
private static bool Initialized = false;
public bool OkayToRun = false;
public bool Successful = false;
public bool Ran = true;
public string Report;
Expand All @@ -25,41 +30,57 @@ public static void EnsureInitialized()
{
return;
}
Initialized = true;
Initalize();
}

public static void Initalize()
private static void Initalize()
{
Legalizer.AllowBruteForce = true;
Legalizer.AllowBruteForce = false;
Legalizer.EnableEasterEggs = false;
Legalizer.AllowAPI = true;
APILegality.PrioritizeGame = true;
APILegality.UseTrainerData = false;
Initialized = true;
}

public AutoLegality(PKM pk, string ver)
public AutoLegality(PKM pk, string ver, CancellationTokenSource cancellationTokenSource)
{
EnsureInitialized();
bool valid = Enum.TryParse<GameVersion>(ver, true, out var game);
if (valid)
ProcessALM(pk, game);
{
OkayToRun = true;
startingPK = pk;
gv = game;
cts = cancellationTokenSource;
}
return;
}

private void ProcessALM(PKM pkm, GameVersion ver = GameVersion.GP)
public PKM LegalizePokemon()
{
return ProcessALM(startingPK, gv);
}

private PKM ProcessALM(PKM pkm, GameVersion ver = GameVersion.GP)
{
la = new LegalityAnalysis(pkm);
var tcs = new TaskCompletionSource<string>();
if (la.Valid)
{
legalpk = pkm;
Ran = false;
Report = la.Report();
return;
return legalpk;
}
/*if (la.Report().ToLower().Contains("invalid move")){
Ran = true; // because piepie62 and griffin wanted to make my program a liar. GG guys GG.
Successful = false;
Report = la.Report();
return;
}*/
legalpk = Legalize(pkm, ver);
Task.Run (() =>
{
Console.WriteLine(String.Format("Legalization on Thread ({0}) has started at: {1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("F")));
legalpk = Legalize(pkm, ver);
Console.WriteLine(String.Format("Legalization on Thread ({0}) has finished at: {1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("F")));
cts.Cancel();
}, cts.Token);
return legalpk;
}

private SimpleTrainerInfo getInfo(PKM pk, GameVersion ver)
Expand All @@ -75,72 +96,28 @@ private SimpleTrainerInfo getInfo(PKM pk, GameVersion ver)
info.Gender = pk.OT_Gender;
return info;
}

private int ChooseRandomMove(int[] moves)
{
var mvs = la.AllSuggestedMovesAndRelearn().Where(move => !moves.Contains(move));
if(mvs.Count() == 0)
{
return 0;
}
return mvs.ElementAt(Rand.RandomNum() % mvs.Count());
}
private PKM Legalize(PKM pk, GameVersion ver)
{
Report = la.Report();
var sav = SaveUtil.GetBlankSAV(ver, pk.OT_Name);
sav.TID = pk.TID;
sav.SID = pk.SID;
sav.Language = pk.Language;
Legalizer.AllowBruteForce = true;
Legalizer.EnableEasterEggs = false;
Legalizer.AllowAPI = true;
APILegality.PrioritizeGame = true;
APILegality.UseTrainerData = false;
var r = new Regex(@"invalid move ([1-4]):", RegexOptions.IgnoreCase);
var matches = r.Matches(la.Report());
foreach (Match match in matches)
{
int movePos;
if (int.TryParse(match.Groups[1].Value, out movePos))
{
var mvs = pk.Moves;
mvs[movePos - 1] = ChooseRandomMove(pk.Moves);
pk.Moves = mvs;
}
}

PKM upd = sav.Legalize(pk.Clone());
upd.SetTrainerData(getInfo(pk, ver));
la = new LegalityAnalysis(upd);
if(la.Valid)
if (la.Valid)
{
legalpk = upd;
Successful = true;
//Report = la.Report();
}
else
{
upd = sav.Legalize(pk.Clone());
la = new LegalityAnalysis(upd);
if (la.Valid)
{
legalpk = upd;
Successful = true;
} else
{
Console.WriteLine(la.Report());
}
}

if (Successful)
{
return legalpk;
//Report = la.Report();
}

return null;
}
public PKM GetLegalPKM()

public PKM getLegalPK()
{
return legalpk;
}
Expand Down
59 changes: 45 additions & 14 deletions Models/Legalize.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,29 +15,60 @@ public class Legalize
public string Species { get; }
public string[] Report { get; }
public bool Ran { get; }
public string QR { get; }
public string QR { get; }


public Legalize(PKM pk, string version)
{
CancellationTokenSource cts = new CancellationTokenSource();
var al = new AutoLegality(pk, version);
Success = al.Successful;
Report = al.Report.Split('\n');
Ran = al.Ran;
if (Success)
CancellationTokenSource cts = new CancellationTokenSource(10000);
var al = new AutoLegality(pk, version, cts);
if (al.OkayToRun)
{
Pokemon = Convert.ToBase64String(al.GetLegalPKM().DecryptedBoxData);
Species = new PokemonSummary(al.GetLegalPKM(), GameInfo.Strings).Species;
try
PKM pkmn;
al.LegalizePokemon();
while (true)
{
if (cts.IsCancellationRequested)
{
pkmn = al.getLegalPK();
break;
}
Thread.Sleep(100);
}
Success = al.Successful;
Report = al.Report.Split('\n');
Ran = al.Ran;
if (Success)
{
QR = Utils.GenerateQR(QRMessageUtil.GetMessage(al.GetLegalPKM()));
} catch
try
{
Pokemon = Convert.ToBase64String(pkmn.DecryptedBoxData);
Species = new PokemonSummary(pkmn, GameInfo.Strings).Species;
try
{
QR = Utils.GenerateQR(QRMessageUtil.GetMessage(pkmn));
}
catch
{
QR = "";
}
} catch
{
Pokemon = "";
Species = "";
Success = false;
Ran = true;
Report = new string[1] { "Stuck in legalization!" };
}
} else
{
QR = "";
Pokemon = "";
}
} else
{
Pokemon = "";
Ran = false;
Success = false;
Report = new string[1] { "Could not run legalization!" };
}
}
}
Expand Down
Binary file modified deps/PKHeX.Core.AutoMod.dll
Binary file not shown.

0 comments on commit 408a37f

Please sign in to comment.