Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/PKForge.App/Views/HomePage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -479,8 +479,8 @@ private async Task ShowSaveMenuAsync(SaveCard card)

/// <summary>
/// First open of a save whose editions share one format (FireRed/LeafGreen, Ruby/Sapphire,
/// Diamond/Pearl): the bytes cannot say which cartridge it is, so the player picks once and
/// the choice sticks (it stays editable from the save's menu). False when they backed out.
/// Diamond/Pearl, Red/Blue/Green): the bytes cannot say which cartridge it is, so the player
/// picks once and the choice sticks (it stays editable from the save's menu). False when they backed out.
/// </summary>
private async Task<bool> ChooseEditionOnceAsync(DetectedSave save)
{
Expand All @@ -495,7 +495,7 @@ private async Task<bool> ChooseEditionOnceAsync(DetectedSave save)
var options = editions.Select(c => new PadOption(c.Label, IconPath: "game"))
.Append(new PadOption(later, IconPath: "close")).ToArray();
var choice = await PadMenu.ShowAsync(_hostGrid, "Which version is this?",
"Both versions write the same save file, so PKForge cannot tell them apart. " +
"These versions write the same save file, so PKForge cannot tell them apart. " +
"Pick yours once; you can change it later from the save's menu (long-press).", options);
if (choice is null) return false;
if (choice == later)
Expand Down
2 changes: 2 additions & 0 deletions src/PKForge.App/Views/SaveIdentitySheet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,8 @@ private static async Task PickGameAsync(Grid host, ISaveIdentityStore store, Sav
{
SaveLayoutFamily.Cfru or SaveLayoutFamily.UnboundCfru or SaveLayoutFamily.GsChroniclesCfru =>
"This save uses a CFRU layout. Only games that write it are listed, so PKForge never opens it with the wrong engine.",
SaveLayoutFamily.RedBlue =>
"Red, Blue, Green and Japanese Blue write the same save. Pick the cartridge: the shelf uses its art, and a transfer uses that origin game.",
SaveLayoutFamily.Other => "Pick the retail game, or mark it as a ROM hack built on it.",
_ => "Only games that share this save's layout are listed. A ROM hack built on it keeps the retail engine.",
};
Expand Down
32 changes: 26 additions & 6 deletions src/PKForge.Domain/SaveIdentity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ public enum SaveLayoutFamily
GsChroniclesCfru = 6,
/// <summary>Diamond and Pearl: one save format, the edition is not in the bytes.</summary>
DiamondPearl = 7,
/// <summary>Red, Blue, Green and Japanese Blue: one save format. Yellow is a different save.</summary>
RedBlue = 8,
}

/// <summary>
Expand Down Expand Up @@ -156,7 +158,11 @@ public static SaveIdentityGuess Guess(string? engineGame, int generation, string
"GS Chronicles" => SaveFormat.GsChronicles,
_ => SaveFormat.Standard,
};
return new SaveIdentityGuess(label, FamilyOf(engineGame), format, suggested, label);
var family = FamilyOf(engineGame);
// Red/Blue/Green share one layout and one lumped box-art file. Leave the sticker
// blank until the player picks a cartridge, so every unchosen save is not Green.
var art = family == SaveLayoutFamily.RedBlue ? null : label;
return new SaveIdentityGuess(label, family, format, suggested, art);
}

public static SaveLayoutFamily FamilyOf(string engineGame) => engineGame switch
Expand All @@ -165,6 +171,7 @@ public static SaveIdentityGuess Guess(string? engineGame, int generation, string
"Ruby" or "Sapphire" or "Ruby / Sapphire" => SaveLayoutFamily.RubySapphire,
"FireRed" or "LeafGreen" or "FireRed / LeafGreen" => SaveLayoutFamily.FireRedLeafGreen,
"Diamond" or "Pearl" or "Diamond / Pearl" => SaveLayoutFamily.DiamondPearl,
"Red / Blue" => SaveLayoutFamily.RedBlue,
"Unbound" => SaveLayoutFamily.UnboundCfru,
"Radical Red" => SaveLayoutFamily.Cfru,
"GS Chronicles" => SaveLayoutFamily.GsChroniclesCfru,
Expand Down Expand Up @@ -200,6 +207,17 @@ public static SaveIdentityGuess Guess(string? engineGame, int generation, string
new("pearl", "Pokémon Pearl", SaveFormat.Standard, "Pokémon Pearl", false),
new("hack-dp", "Diamond/Pearl-based ROM hack", SaveFormat.Standard, null, true),
],
// International Blue and Japanese Green are one version id (GN). The shelf can
// still tell the cartridges apart; a transfer records the shared origin either way.
// Art labels are the bundled asset names, not the menu text.
SaveLayoutFamily.RedBlue =>
[
new("red", "Pokémon Red", SaveFormat.Standard, "Pokémon Red", false),
new("blue-int", "Pokémon Blue (INT)", SaveFormat.Standard, "Pokémon Blue", false),
new("green-jp", "Pokémon Green (JP)", SaveFormat.Standard, "Pokémon Blue [INT]/Green [JP]", false),
new("blue-jp", "Pokémon Blue (JP)", SaveFormat.Standard, "Pokémon Blue [JP]", false),
new("hack-rb", "Red/Blue-based ROM hack", SaveFormat.Standard, null, true),
],
SaveLayoutFamily.UnboundCfru =>
[
new("unbound", "Pokémon Unbound", SaveFormat.Unbound, "Pokémon Unbound", true),
Expand All @@ -224,13 +242,14 @@ public static SaveIdentityGuess Guess(string? engineGame, int generation, string
};

/// <summary>
/// True for a save of a shared-format pair (Ruby/Sapphire, FireRed/LeafGreen, Diamond/Pearl)
/// that its own Pokémon could not place (the guess is still the pair) and the player has
/// not said which edition it is yet.
/// True for a save of a shared format (Ruby/Sapphire, FireRed/LeafGreen, Diamond/Pearl,
/// Red/Blue/Green) that the bytes could not place and the player has not said which
/// edition it is yet.
/// </summary>
public static bool NeedsEditionChoice(SaveIdentityGuess guess, string? gameChoiceId) =>
gameChoiceId is null && guess.Label.Contains(" / ", StringComparison.Ordinal)
&& guess.Family is SaveLayoutFamily.RubySapphire or SaveLayoutFamily.FireRedLeafGreen or SaveLayoutFamily.DiamondPearl;
&& guess.Family is SaveLayoutFamily.RubySapphire or SaveLayoutFamily.FireRedLeafGreen
or SaveLayoutFamily.DiamondPearl or SaveLayoutFamily.RedBlue;

/// <summary>Every choice across families, for resolving a persisted id.</summary>
public static SaveGameChoice? FindChoice(string? id, SaveLayoutFamily family, string detectedLabel) =>
Expand All @@ -243,7 +262,8 @@ public static bool NeedsEditionChoice(SaveIdentityGuess guess, string? gameChoic
"radicalred" or "hack-cfru" => SaveFormat.RadicalRed,
"gschronicles" => SaveFormat.GsChronicles,
"emerald" or "hack-emerald" or "ruby" or "sapphire" or "hack-rs" or "firered" or "leafgreen" or "hack-frlg"
or "diamond" or "pearl" or "hack-dp" => SaveFormat.Standard,
or "diamond" or "pearl" or "hack-dp"
or "red" or "blue-int" or "green-jp" or "blue-jp" or "hack-rb" => SaveFormat.Standard,
_ => SaveFormat.Auto,
};

Expand Down
6 changes: 6 additions & 0 deletions src/PKForge.Engine/SaveEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,12 @@ public ISaveEngineSession OpenBlankSession(int generation, string? displayName =
return new SaveDescription(editionName ?? pair, save.Generation, save.OT, save.PlayTimeString, LanguageTag(save));
}

// Red, international Blue, Japanese Green and Japanese Blue are one save.
// Yellow is a different file and is named from the version list below.
// The bytes cannot pick a cartridge; the player does, once, from this label.
if (save is SAV1 { Version: GameVersion.RB })
return new SaveDescription("Red / Blue", save.Generation, save.OT, save.PlayTimeString, LanguageTag(save));

var strings = GameInfo.GetStrings("en");
var versionIndex = (int)save.Version;
var gameName = versionIndex > 0 && versionIndex < strings.gamelist.Length && strings.gamelist[versionIndex].Length > 0
Expand Down
5 changes: 5 additions & 0 deletions src/PKForge.Engine/SaveEngineSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ public void MakeActive()
ThrowIfDisposed();
ParseSettings.InitFromSaveFileData(_save);
ParseSettings.ClearActiveTrainer();
// A Gen 1 Pokémon does not store its game. PKHeX writes the origin when the mon
// leaves the cartridge, from this process-wide value, and only the save the player
// opened may set it. RB (not chosen yet) falls back to Red inside the setter.
if (_save is SAV1)
EntityConverter.VirtualConsoleSourceGen1 = _save.Version;
}

/// <summary>
Expand Down
35 changes: 31 additions & 4 deletions src/PKForge.Engine/SaveParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,22 @@ internal static bool TryGetSaveFile(byte[] data, out SaveFile? save)
// Ruby and Sapphire have identical save layouts and no reliable version flag.
// Only resolve an ambiguous RS save, and require a standalone name token.
/// <summary>
/// FR/LG, R/S and D/P share one save layout, so the file itself never names the edition.
/// The game the player picked for this save wins; without a pick, the edition the
/// player's own Pokémon were caught in decides (see <see cref="EditionFromOwnPokemon"/>).
/// File names are never read.
/// FR/LG, R/S, D/P and Red/Blue/Green share one save layout, so the file itself never
/// names the edition. The game the player picked for this save wins; without a pick,
/// the edition the player's own Pokémon were caught in decides for the Gen 3/4 pairs
/// (see <see cref="EditionFromOwnPokemon"/>). Gen 1 has nothing to read, so it stays
/// the shared group until the player picks. File names are never read.
/// </summary>
internal static void ApplyVersionHint(SaveFile save, string? chosenGame)
{
// Gen 1 has no version byte and no per-Pokémon origin. The cartridge is applied
// in memory for this open; the file itself is not rewritten.
if (save is SAV1)
{
if (Gen1Edition(chosenGame) is { } gen1)
save.Version = gen1;
return;
}
if (save is not (SAV3FRLG or SAV3RS)) return;
var game = chosenGame?.Replace("Pokémon ", "", StringComparison.Ordinal).Trim();
GameVersion? chosen = game switch
Expand All @@ -76,6 +85,24 @@ internal static void ApplyVersionHint(SaveFile save, string? chosenGame)
save.Version = edition;
}

/// <summary>
/// The Gen 1 cartridge the player picked. International Blue and Japanese Green share
/// PKHeX's GN id, so a transfer records the same origin for both; the shelf still
/// shows the cartridge they chose. File names are not accepted.
/// </summary>
private static GameVersion? Gen1Edition(string? chosenGame)
{
var game = chosenGame?.Replace("Pokémon ", "", StringComparison.Ordinal).Trim();
return game switch
{
"Red" => GameVersion.RD,
"Blue (INT)" => GameVersion.GN,
"Green (JP)" => GameVersion.GN,
"Blue (JP)" => GameVersion.BU,
_ => null,
};
}

/// <summary>
/// The edition of a shared-layout save, read from the save's own Pokémon: every mon the
/// player caught or hatched records the game it came from, and a mon whose trainer ID,
Expand Down
22 changes: 22 additions & 0 deletions tests/PKForge.Domain.Tests/SaveIdentityTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,7 @@ public void FolderHintIsTheLastTwoFolders(string documentId, string? expected)
[InlineData("FireRed / LeafGreen", SaveLayoutFamily.FireRedLeafGreen)]
[InlineData("Ruby / Sapphire", SaveLayoutFamily.RubySapphire)]
[InlineData("Diamond / Pearl", SaveLayoutFamily.DiamondPearl)]
[InlineData("Red / Blue", SaveLayoutFamily.RedBlue)]
public void AnUnplacedPairAsksOnceUntilChosen(string engineGame, SaveLayoutFamily family)
{
var guess = SaveIdentityRules.Guess(engineGame, 3, "main.sav", null, "main.sav");
Expand All @@ -292,11 +293,32 @@ public void AnUnplacedPairAsksOnceUntilChosen(string engineGame, SaveLayoutFamil
Assert.Equal(SaveFormat.Standard, SaveIdentityRules.FormatOfChoice(edition.Id));
}

[Fact]
public void RedBlueOffersEachCartridgeAndKeepsTheArtBlankUntilChosen()
{
var guess = SaveIdentityRules.Guess("Red / Blue", 1, "Pokemon Red.sav", null, "Pokemon Red.sav");
Assert.Equal("Pokémon Red / Blue", guess.Label);
Assert.Null(guess.ArtLabel);
Assert.Equal("Red", guess.SuggestedName);

var choices = SaveIdentityRules.ChoicesFor(guess.Family, guess.Label).Where(c => !c.IsHack).ToList();
Assert.Equal(["Pokémon Red", "Pokémon Blue (INT)", "Pokémon Green (JP)", "Pokémon Blue (JP)"], choices.Select(c => c.Label));
Assert.Equal(["Pokémon Red", "Pokémon Blue", "Pokémon Blue [INT]/Green [JP]", "Pokémon Blue [JP]"], choices.Select(c => c.ArtLabel));

var blue = choices.Single(c => c.Id == "blue-int");
var resolved = SaveIdentityResolver.Resolve(guess, new SaveIdentity("doc", GameChoiceId: blue.Id));
Assert.Equal("Pokémon Blue (INT)", resolved.DisplayName);
Assert.Equal("Pokémon Blue (INT)", resolved.GameLabel);
Assert.Equal("Pokémon Blue", resolved.ArtLabel);
Assert.False(SaveIdentityRules.NeedsEditionChoice(guess, blue.Id));
}

[Theory]
[InlineData("LeafGreen")]
[InlineData("Sapphire")]
[InlineData("Pearl")]
[InlineData("Emerald")]
[InlineData("Yellow")]
public void AnIdentifiedEditionNeverAsks(string engineGame)
{
var guess = SaveIdentityRules.Guess(engineGame, 3, "main.sav", null, "main.sav");
Expand Down
90 changes: 90 additions & 0 deletions tests/PKForge.Engine.Tests/GameIdentificationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,82 @@ namespace PKForge.Engine.Tests;

public sealed class GameIdentificationTests
{
[Theory]
[InlineData("Pokémon Red", GameVersion.RD)]
[InlineData("Pokémon Blue (INT)", GameVersion.GN)]
[InlineData("Pokémon Green (JP)", GameVersion.GN)]
[InlineData("Pokémon Blue (JP)", GameVersion.BU)]
public void TheChosenGameResolvesTheRedBlueEdition(string chosenGame, GameVersion expected)
{
var save = new SAV1();

SaveParser.ApplyVersionHint(save, chosenGame);

Assert.Equal(expected, save.Version);
}

[Theory]
[InlineData("Pokemon - Red Version (USA, Europe).sav")]
[InlineData("Pokémon Red / Blue")]
[InlineData("Pokémon Blue")]
public void FileNamesAndTheGroupLabelNeverPickTheRedBlueEdition(string name)
{
var save = new SAV1();

SaveParser.ApplyVersionHint(save, name);

Assert.Equal(GameVersion.RB, save.Version);
}

[Fact]
public void ARedBlueSaveIsDescribedAsTheSharedGroup()
{
var description = new SaveEngine().TryDescribe(RecognizableRedBlue());

Assert.NotNull(description);
Assert.Equal("Red / Blue", description!.GameName);
Assert.Equal(1, description.Generation);
}

[Fact]
public void OpeningTheChosenCartridgeStampsThatOriginOnATransfer()
{
var previous = EntityConverter.VirtualConsoleSourceGen1;
try
{
using var session = new SaveEngineSession(RecognizableRedBlue(), "Pokémon Blue (JP)");
Assert.Equal(GameVersion.BU, Assert.IsType<SAV1>(session.SaveFile).Version);

session.MakeActive();

Assert.Equal(GameVersion.BU, EntityConverter.VirtualConsoleSourceGen1);
var transferred = new PK1(jp: true) { Species = (ushort)Species.Pikachu, CurrentLevel = 5 }.ConvertToPK7();
Assert.Equal(GameVersion.BU, transferred.Version);
}
finally
{
EntityConverter.VirtualConsoleSourceGen1 = previous;
}
}

[Fact]
public void OpeningYellowStampsYellowAsTheTransferOrigin()
{
var previous = EntityConverter.VirtualConsoleSourceGen1;
try
{
using var session = new SaveEngineSession(new SAV1(LanguageID.English, GameVersion.YW), "Pokémon Yellow");

session.MakeActive();

Assert.Equal(GameVersion.YW, EntityConverter.VirtualConsoleSourceGen1);
}
finally
{
EntityConverter.VirtualConsoleSourceGen1 = previous;
}
}

[Theory]
[InlineData("Pokémon LeafGreen", GameVersion.LG)]
[InlineData("Pokémon FireRed", GameVersion.FR)]
Expand Down Expand Up @@ -58,6 +134,20 @@ public void SingleVersionsAreNotPairs()
Assert.Null(SaveEngine.EditionPair(GameVersion.Pt, GameInfo.GetStrings("en")));
}

/// <summary>
/// A blank <see cref="SAV1"/> does not write the party and box list terminators the
/// recognizer requires. An empty international list at each offset is enough.
/// </summary>
private static byte[] RecognizableRedBlue()
{
var data = new byte[0x8000];
data[0x2F2C] = 0;
data[0x2F2D] = 0xFF;
data[0x30C0] = 0;
data[0x30C1] = 0xFF;
return data;
}

private static PK3 OwnMon(SaveFile save, GameVersion caughtIn, string ot)
{
var pk = new PK3 { Species = (ushort)Species.Bulbasaur, CurrentLevel = 5, Version = caughtIn, ID32 = save.ID32, OriginalTrainerName = ot, Language = (int)LanguageID.English };
Expand Down