Skip to content

Commit

Permalink
Merge pull request #258 from WakooMan/features/sync-time
Browse files Browse the repository at this point in the history
Automatic Sync initializing bugfix (Based on 1.7.2 patch PR)
  • Loading branch information
garrettluskey authored Jul 11, 2022
2 parents 1ccfd98 + f98d183 commit c411c46
Show file tree
Hide file tree
Showing 15 changed files with 164 additions and 10 deletions.
3 changes: 3 additions & 0 deletions prepare-links.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ While ($key -eq 0)
{
#create junction link for game in project directory
New-Item -ItemType Junction -Path .\mb2 -Target $path
$COOPLOGdir = $PSScriptRoot + "\COOP_LOG"
New-Item -ItemType "directory" -Path $COOPLOGdir
[Environment]::SetEnvironmentVariable('COOP_LOG',$COOPLOGdir,[System.EnvironmentVariableTarget]::User)
Write-Output "*** Link to the game path succesfully created ***" | Green
}
elseif ($key -eq 78)
Expand Down
3 changes: 3 additions & 0 deletions source/Coop/Coop.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,8 @@
<Compile Include="Mod\MbLogTarget.cs" />
<Compile Include="Mod\GameSync\Party\CampaignMapMovement.cs" />
<Compile Include="Mod\GameSync\Party\CampaignMapPositions.cs" />
<Compile Include="Mod\Patch\CampaignPatches\CompanionsCampaignBehaviorPatches.cs" />
<Compile Include="Mod\Patch\Hero\HeroPatches.cs" />
<Compile Include="Mod\Patch\MobilePartyPatches\DisablePartyDecisionMaking.cs" />
<Compile Include="Mod\GameSync\Party\MobilePartyUpdatable.cs" />
<Compile Include="Mod\Patch\Party\GarrisonTroopsCampaignBehavior.cs" />
Expand All @@ -310,6 +312,7 @@
<Compile Include="Mod\GameSync\Fief\FiefSync.cs" />
<Compile Include="Mod\GameSync\HeroSync.cs" />
<Compile Include="Mod\GameSync\SettlementSync.cs" />
<Compile Include="Mod\Patch\World\TimeCommands.cs" />
<Compile Include="Mod\Patch\World\TimeSynchronization.cs" />
<Compile Include="Mod\Patch\CampaignPatches\SetTimeSpeedPatch.cs" />
<Compile Include="Mod\Patch\CampaignPatches\TimeControlModePatch.cs" />
Expand Down
2 changes: 1 addition & 1 deletion source/Coop/Mod/DebugUtil/DebugLogging.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ private static void RegisterCustomTargets()
/// <returns></returns>
private static string GetLogFileName()
{
return $"{Environment.GetEnvironmentVariable("COOP_LOG", EnvironmentVariableTarget.User)}/Coop_{(Utilities.GetFullCommandLineString().Contains("/server") ? "server" : "client")}.log";
return $"{Directory.GetCurrentDirectory()}/Coop_{(Utilities.GetFullCommandLineString().Contains("/server") ? "server" : "client")}.log";
}

/// <summary>
Expand Down
5 changes: 4 additions & 1 deletion source/Coop/Mod/GameSync/Initializer.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Coop.Mod.GameSync.Party;
using Coop.Mod.GameSync.Roster;
using Coop.Mod.Patch.World;
using Coop.Mod.Persistence.Party;
using NLog;
using RailgunNet.Logic;
Expand Down Expand Up @@ -31,7 +32,9 @@ public static void SetupSyncAfterLoad()
FiefSync.MakeManaged(town);
}

if(Coop.IsServer)
TimeControl.Instance();

if (Coop.IsServer)
{
CoopServer.Instance.Persistence.MobilePartyEntityManager.OnBeforePartyScopeEnter += OnBeforePartyScopeEnter;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TaleWorlds.CampaignSystem.CampaignBehaviors;

namespace Coop.Mod.Patch.CampaignPatches
{
[HarmonyPatch(typeof(CompanionsCampaignBehavior))]
internal class CompanionsCampaignBehaviorPatches
{
[HarmonyPrefix]
[HarmonyPatch("CreateCompanionAndAddToSettlement")]
private static bool Prefix()
{
return false;
}
}
}
4 changes: 2 additions & 2 deletions source/Coop/Mod/Patch/CampaignPatches/SetTimeSpeedPatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ static class SetTimeSpeedPatch
static void Prefix(Campaign __instance, int speed)
{

if ( ShouldEnableTimeControlMode(__instance.TimeControlMode, speed) )
if (ShouldEnableTimeControlMode(__instance.TimeControlMode, speed))
{
TimeControl.CanSyncTimeControlMode = true;
}

}
}

private static bool ShouldEnableTimeControlMode(CampaignTimeControlMode campaignTimeControlMode, int speed)
{
Expand Down
4 changes: 2 additions & 2 deletions source/Coop/Mod/Patch/CampaignPatches/TimeControlModePatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ static class TimeControlModePatch
/// <summary>
/// Grants access to the private field of the property <see cref="TaleWorlds.CampaignSystem.Campaign.TimeControlMode"/> used to override the setter logic.
/// </summary>
static readonly AccessTools.FieldRef<Campaign, CampaignTimeControlMode> _timeControlModeRef =
static readonly AccessTools.FieldRef<Campaign, CampaignTimeControlMode> _timeControlModeRef =
AccessTools.FieldRefAccess<Campaign, CampaignTimeControlMode>("_timeControlMode");

/// <summary>
Expand All @@ -40,7 +40,7 @@ static class TimeControlModePatch
[HarmonyPatch(MethodType.Setter)]
static bool Prefix(Campaign __instance, ref CampaignTimeControlMode value)
{
if (__instance != null && !__instance.TimeControlModeLock &&
if (__instance != null && !__instance.TimeControlModeLock &&
value != __instance.TimeControlMode && TimeControl.CanSyncTimeControlMode)
{
_timeControlModeRef(__instance) = value;
Expand Down
34 changes: 34 additions & 0 deletions source/Coop/Mod/Patch/Hero/HeroPatches.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using HarmonyLib;
using TaleWorlds.CampaignSystem;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLog;

namespace Coop.Mod.Patch
{
[HarmonyPatch(typeof(Hero))]
internal class HeroPatches
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

[HarmonyPostfix]
[HarmonyPatch(MethodType.Constructor)]
static void Postfix(Hero __instance)
{

if(Coop.IsServer)
{
string stacktrace = Environment.StackTrace;
Logger.Info($"Creating new hero, {__instance.Name}");
}
else if(CoopClient.Instance.ClientPlaying)
{
string stacktrace = Environment.StackTrace;
Logger.Info($"Creating new hero, {__instance.Name}");
}

}
}
}
53 changes: 53 additions & 0 deletions source/Coop/Mod/Patch/World/TimeCommands.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TaleWorlds.CampaignSystem;
using TaleWorlds.Library;

namespace Coop.Mod.Patch.World
{
class TimeCommands
{
private const string sGroupName = "coop";
private const string sTestGroupName = "test";
private static Dictionary<string, CampaignTimeControlMode> TimeControlModes = new Dictionary<string, CampaignTimeControlMode>();
static TimeCommands()
{
foreach(var e in Enum.GetValues(typeof(CampaignTimeControlMode)).Cast<CampaignTimeControlMode>())
{
TimeControlModes.Add(e.ToString(),e);
}
}

/// <summary>
/// Sets time speed for to the speed given as argument.
/// </summary>
/// <param name="parameters">Expects a speed value to set speed</param>
/// <returns>Changed value in TimeControlMode.</returns>
[CommandLineFunctionality.CommandLineArgumentFunction("set_time_speed", sTestGroupName)]
public static string SetTimeSpeed(List<string> parameters)
{
if (parameters.Count != 1 || !int.TryParse(parameters[0], out int timeSpeed) || timeSpeed < 0 || timeSpeed > 2)
{
return $"Usage: \"{sTestGroupName}.set_time_speed [time_speed (0-2)].";
}

var oldTimeControlMode = Campaign.Current.TimeControlMode;
Campaign.Current.SetTimeSpeed(timeSpeed);

return $"Campaign TimeControlMode changed from {oldTimeControlMode} to {Campaign.Current.TimeControlMode}";
}

/// <summary>
/// Gets time control mode for the Campaign.
/// </summary>
/// <returns>TimeControlMode value.</returns>
[CommandLineFunctionality.CommandLineArgumentFunction("get_time_speed", sTestGroupName)]
public static string GetTimeSpeed(List<string> parameters)
{
return $"Campaign TimeControlMode is {Campaign.Current.TimeControlMode}";
}
}
}
11 changes: 11 additions & 0 deletions source/Coop/Mod/Patch/World/TimeControl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public string GetReasonForRejection()
return "Some players are currently connecting";
}
}

public TimeControl([NotNull] Campaign instance) : base(instance)
{
}
Expand All @@ -68,5 +69,15 @@ private static ECallPropagation SetIsMainPartyWaiting(IPendingMethodCall call)
}

private static readonly Condition CanChangeTimeClientside = new Condition((eOrigin, _) => CanSyncTimeControlMode);
#region Utils
public static TimeControl Instance()
{
if (Instances.TryGetValue(Campaign.Current, out TimeControl instance))
{
return instance;
}
return new TimeControl(Campaign.Current);
}
#endregion
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,9 @@ public HeroSerializer(Hero hero) : base(hero)
case "<Issue>k__BackingField":
// TODO: Fix this joke
break;
case "<BannerItem>k__BackingField":
// TODO: Fix this joke
break;
case "_characterObject":
case "<Template>k__BackingField":
case "_clan":
Expand Down
2 changes: 1 addition & 1 deletion source/Coop/Mod/Serializers/PartyComponentSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ public object Deserialize()
typeof(CaravanPartyComponent),
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new object[] { null, null },
new object[] { null, null, null },
null);
return CaravanPartyComponent;
}
Expand Down
13 changes: 12 additions & 1 deletion source/CoopFramework/CoopFramework.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using NLog;
using TaleWorlds.SaveSystem;

namespace CoopFramework
{
Expand All @@ -21,6 +23,8 @@ public static class CoopFramework
/// </summary>
[CanBeNull] public static IObjectManager ObjectManager { get; private set; }

internal static readonly Dictionary<Type, MethodInfo> LoadInitializationCallbacks = new Dictionary<Type, MethodInfo>();

/// <summary>
/// Initializes all patches that are generated through <see cref="CoopManaged{TSelf,TExtended}"/>.
/// To be called once on start up after all assemblies that need patching are loaded.
Expand All @@ -36,8 +40,15 @@ public static void InitPatches([CanBeNull] IObjectManager objectManager, Func<bo
Logger.Error("CoopFramework.InitPatches can only be called once.");
return;
}

var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
BindingFlags Flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
foreach (Assembly assembly in loadedAssemblies)
{
foreach (Type type in assembly.GetTypes().Where(t => t.GetMethods(Flags).Any(m => m.GetCustomAttributes<LoadInitializationCallback>().Any())))
{
LoadInitializationCallbacks.Add(type, type.GetMethods(Flags).Where(m => m.GetCustomAttributes<LoadInitializationCallback>().Any()).First());
}
}
AppDomain.CurrentDomain.AssemblyLoad += (sender, args) => PatchAssembly(args.LoadedAssembly);
foreach (var assembly in loadedAssemblies) PatchAssembly(assembly);

Expand Down
11 changes: 10 additions & 1 deletion source/CoopFramework/CoopFramework.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net472</TargetFramework>
Expand All @@ -22,4 +22,13 @@
<PackageReference Include="NLog" Version="4.7.2" />
</ItemGroup>

<ItemGroup>
<Reference Include="TaleWorlds.ObjectSystem">
<HintPath>..\..\mb2\bin\Win64_Shipping_Client\TaleWorlds.ObjectSystem.dll</HintPath>
</Reference>
<Reference Include="TaleWorlds.SaveSystem">
<HintPath>..\..\mb2\bin\Win64_Shipping_Client\TaleWorlds.SaveSystem.dll</HintPath>
</Reference>
</ItemGroup>

</Project>
5 changes: 4 additions & 1 deletion source/RemoteAction/Argument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,10 @@ public Argument(bool b) : this()
/// </summary>
public Argument(Guid guid, bool isCoopObjectReference) : this()
{
if(isCoopObjectReference)
if (guid == System.Guid.Empty)
throw new ArgumentNullException("Guid is invalid.");

if (isCoopObjectReference)
{
EventType = EventArgType.CoopObjectManagerId;
CoopObjectManagerId = guid;
Expand Down

0 comments on commit c411c46

Please sign in to comment.