Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved unlockablesAPI #180

Merged
merged 3 commits into from
Aug 14, 2020
Merged
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
25 changes: 13 additions & 12 deletions R2API/APIExtras/UnlockableAPIExtras.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ namespace R2API {
/// Interface used to provide the metadata needed to register an achievement
/// </summary>
public interface IModdedUnlockableDataProvider {

/// <summary>
/// The identifier of the achievement being added
/// Should be unique
Expand Down Expand Up @@ -70,7 +71,7 @@ internal static string GetHowToUnlock<TDataProvider>(this TDataProvider self)
return Language.GetStringFormatted("UNLOCK_VIA_ACHIEVEMENT_FORMAT", name, desc);
}

internal static String GetUnlocked<TDataProvider>(this TDataProvider self)
internal static string GetUnlocked<TDataProvider>(this TDataProvider self)
where TDataProvider : class, IModdedUnlockableDataProvider {
var name = Language.GetString(self.AchievementNameToken);
var desc = Language.GetString(self.AchievementDescToken);
Expand Down Expand Up @@ -114,14 +115,14 @@ public VanillaSpriteProvider(String path) {
/// Creates a CustomSpriteProvider from the path used for a ResourcesProvider from ResourcesAPI
/// </summary>
/// <param name="modPrefixedPath">The path used to retreive the sprite from the provider</param>
public CustomSpriteProvider( String modPrefixedPath) {
public CustomSpriteProvider( string modPrefixedPath) {
this.PathString = modPrefixedPath;
}

/// <summary>
/// The path that will be passed to Resources.Load to get the sprite
/// </summary>
public String PathString { get; }
public string PathString { get; }
/// <summary>
/// Loads the sprite
/// </summary>
Expand All @@ -135,13 +136,13 @@ public CustomSpriteProvider( String modPrefixedPath) {
/// A base class that can be used to conveinently supply all the required info for a modded achievement
/// </summary>
/// <typeparam name="TSpriteProvider">The type of sprite provider being used for this achievement</typeparam>
public abstract class ModdedUnlockable<TSpriteProvider> : BaseAchievement, IModdedUnlockableDataProvider
public abstract class ModdedUnlockableAndAchievement<TSpriteProvider> : BaseAchievement, IModdedUnlockableDataProvider
where TSpriteProvider : IAchievementSpriteProvider {
#region Implementation
/// <summary>
/// The path that will be passed to Resources.Load to get the sprite
/// </summary>
public String SpritePath { get => this.SpriteProvider.PathString; }
public string SpritePath { get => this.SpriteProvider.PathString; }

/// <summary>
/// Removes this achievement from the current profile.
Expand All @@ -164,33 +165,33 @@ public void Revoke() {
/// The identifier of the achievement being added
/// Should be unique
/// </summary>
public abstract String AchievementIdentifier { get; }
public abstract string AchievementIdentifier { get; }
/// <summary>
/// The identifier of the unlockable granted when the achievement is completed
/// Should be unique
/// This is what is used when specifying an unlock condition for various things in the game
/// </summary>
public abstract String UnlockableIdentifier { get; }
public abstract string UnlockableIdentifier { get; }
/// <summary>
/// The unlockableIdentifier of a prerequisite
/// Should be used for skill unlocks for a custom character if the character has an unlock condition
/// Multiple prereqs are not supported (as far as I can tell)
/// </summary>
public abstract String PrerequisiteUnlockableIdentifier { get; }
public abstract string PrerequisiteUnlockableIdentifier { get; }
/// <summary>
/// The language token for the name to be shown in logbook for this achievement
/// </summary>
public abstract String AchievementNameToken { get; }
public abstract string AchievementNameToken { get; }
/// <summary>
/// The language token for the description to be shown in logbook for this achievement
/// Also used to create the 'How to unlock' text
/// </summary>
public abstract String AchievementDescToken { get; }
public abstract string AchievementDescToken { get; }
/// <summary>
/// The language token for the unlockable
/// Not 100% sure where this is shown in game
/// </summary>
public abstract String UnlockableNameToken { get; }
public abstract string UnlockableNameToken { get; }
#endregion

#region Virtuals
Expand Down Expand Up @@ -228,7 +229,7 @@ public void Revoke() {
/// <summary>
/// This actually does nothing in vanilla, it is here in case that changes in future updates.
/// </summary>
public override Boolean wantsBodyCallbacks { get => base.wantsBodyCallbacks; }
public override Boolean wantsBodyCallbacks { get => base.wantsBodyCallbacks; }
// This cannot be capitalized because it needs to match the base class defined in ror2.
#endregion
}
Expand Down
21 changes: 21 additions & 0 deletions R2API/MiscHelpers/KeyValuePairExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace R2API.MiscHelpers {
public static class KeyValuePairExtensions {
/// <summary>
/// Extension to allow tuple style deconstruction of keys and values when enumerating a dictionary.
/// Example: foreach(var (key, value) in myDictionary)
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="kvp"></param>
/// <param name="key"></param>
/// <param name="value"></param>
public static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> kvp, out TKey key, out TValue value) {
key = kvp.Key;
value = kvp.Value;
}
}
}
2 changes: 1 addition & 1 deletion R2API/R2API.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public R2API() {

Environment.SetEnvironmentVariable("MONOMOD_DMD_TYPE", "Cecil");

On.RoR2.RoR2Application.UnitySystemConsoleRedirector.Redirect += orig => { };
On.RoR2.UnitySystemConsoleRedirector.Redirect += orig => { };

var submoduleHandler = new APISubmoduleHandler(GameBuild, Logger);
loadedSubmodules = submoduleHandler.LoadRequested();
Expand Down
65 changes: 65 additions & 0 deletions R2API/UnlockablesAPI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using System.Reflection;
using BF = System.Reflection.BindingFlags;
using RoR2.Achievements;
using BepInEx;

namespace R2API {
[R2APISubmodule]
Expand Down Expand Up @@ -66,25 +67,79 @@ public static void AddUnlockable<TUnlockable>(Boolean serverTracked)

moddedUnlocks.Add((ach, unl));
}

/// <summary>
/// Adds an unlockable without a corresponding achievement. Generally useful for adding behind the scenes unlockables similar to finding all newt altars and eclipse tracking
/// </summary>
/// <param name="identifier"></param>
/// <param name="hidden"></param>
/// <param name="nameToken"></param>
/// <param name="displayModelPath"></param>
public static void AddUnlockableOnly(string identifier, bool hidden = false, string nameToken = null, string displayModelPath = null) {
if(!Loaded) throw new InvalidOperationException($"{nameof(UnlockablesAPI)} is not loaded. Try requesting the submodule with '[R2APISubmoduleDependency]'");
if(!AbleToAdd) throw new InvalidOperationException("Too late to add unlocks. Must be done during awake.");
var def = new UnlockableDef {
name = identifier,
hidden = hidden,
nameToken = nameToken,
displayModelPath = displayModelPath,
getHowToUnlockString = null,
getUnlockedString = null,
};
moddedUnlocksWithoutAchievements.Add(def);
}

public static void AddEclipseUnlockablesForSurvivor(string modGuid, SurvivorDef survivor) {
if(!Loaded) throw new InvalidOperationException($"{nameof(UnlockablesAPI)} is not loaded. Try requesting the submodule with '[R2APISubmoduleDependency]'");
if(!AbleToAdd) throw new InvalidOperationException("Too late to add unlocks. Must be done during awake.");
if(survivor is null) throw new ArgumentNullException(nameof(survivor));
if(survivor.name.IsNullOrWhiteSpace()) throw new ArgumentException("No name assigned", nameof(SurvivorDef));
var usedGuid = modGuid.Replace('.', '_');
eclipseUnlockInfos.Add((usedGuid, survivor));
}
private static readonly List<(string guid, SurvivorDef survivor)> eclipseUnlockInfos = new List<(string guid, SurvivorDef survivor)>();

#endregion
#region Internal
[R2APISubmoduleInit(Stage = InitStage.SetHooks)]
internal static void SetHooks() {
IL.RoR2.AchievementManager.CollectAchievementDefs += AchievementManager_CollectAchievementDefs;
IL.RoR2.UnlockableCatalog.Init += UnlockableCatalog_Init;
On.RoR2.EclipseRun.GetEclipseBaseUnlockableString += EclipseRun_GetEclipseBaseUnlockableString;
AbleToAdd = true;
}



[R2APISubmoduleInit(Stage = InitStage.UnsetHooks)]
internal static void UnsetHooks() {
IL.RoR2.AchievementManager.CollectAchievementDefs -= AchievementManager_CollectAchievementDefs;
IL.RoR2.UnlockableCatalog.Init -= UnlockableCatalog_Init;
On.RoR2.EclipseRun.GetEclipseBaseUnlockableString -= EclipseRun_GetEclipseBaseUnlockableString;
AbleToAdd = false;
}

private static bool _loaded = false;
private static bool _ableToAdd = false;

private static String EclipseRun_GetEclipseBaseUnlockableString(On.RoR2.EclipseRun.orig_GetEclipseBaseUnlockableString orig) {
var res = orig();
if(res == "") return res;
var spl = res.Split('.');
if(spl.Length != 2) return res;
if(Enum.TryParse<SurvivorIndex>(spl[1], out var i)) {
if(identities.TryGetValue(i, out var identity)) {
return $"{spl[0]}.{identity}";
}
}
return res;
}
private static readonly Dictionary<SurvivorIndex,String> identities = new Dictionary<SurvivorIndex, String>();
private static String CreateOrGetIdentity(string mod, SurvivorDef survivor) {
if(identities.TryGetValue(survivor.survivorIndex, out var id)) return id;
return identities[survivor.survivorIndex] = $"{mod}_{survivor.name.Replace('.', '_')}";
}

private static Action<string,UnlockableDef> RegisterUnlockable {
get {
if( _registerUnlockable is null ) {
Expand All @@ -109,6 +164,7 @@ private static Action<string,UnlockableDef> RegisterUnlockable {
private static Action<string, UnlockableDef> _registerUnlockable;

private static readonly List<(AchievementDef achievementDef, UnlockableDef unlockableDef)> moddedUnlocks = new List<(AchievementDef, UnlockableDef)>();
private static readonly List<UnlockableDef> moddedUnlocksWithoutAchievements = new List<UnlockableDef>();
private static readonly HashSet<string> usedRewardIds = new HashSet<string>();
private static readonly Action<string, UnlockableDef> registerUnlockable;

Expand All @@ -119,6 +175,15 @@ void EmittedDelegate() {
var (achievement, unlockable) = moddedUnlocks[i];
RegisterUnlockable(achievement.unlockableRewardIdentifier, unlockable);
}
for(Int32 i = 0; i < moddedUnlocksWithoutAchievements.Count; ++i) {
RegisterUnlockable(moddedUnlocksWithoutAchievements[i].name, moddedUnlocksWithoutAchievements[i]);
}
foreach(var (modName, survivor) in eclipseUnlockInfos) {
for(Int32 i = 1; i <= 8; ++i) {
var str = $"Eclipse.{CreateOrGetIdentity(modName, survivor)}.{i}";
RegisterUnlockable(str, new UnlockableDef());
}
}
}

var c = new ILCursor(il);
Expand Down