From 7fda25ec3e314f622ee3faba77b3c9b8b195c685 Mon Sep 17 00:00:00 2001 From: Byte-Nova <159603018+Byte-Nova@users.noreply.github.com> Date: Sat, 7 Sep 2024 04:16:21 +0200 Subject: [PATCH] Groundwork for rework --- .../Client/Managers/OfflineActivityManager.cs | 2 +- .../Client/Managers/OnlineActivityManager.cs | 1211 ++--------------- .../Client/Patches/OnlineActivityPatches.cs | 597 +------- Source/Client/Values/SessionValues.cs | 8 +- Source/Server/Managers/ChatManager.cs | 30 +- .../Server/Managers/OnlineActivityManager.cs | 90 +- Source/Server/Network/Clients/ServerClient.cs | 2 +- Source/Server/Network/Listener.cs | 2 +- Source/Shared/Misc/CommonEnumerators.cs | 2 +- .../Shared/PacketData/OnlineActivityData.cs | 10 +- 10 files changed, 169 insertions(+), 1785 deletions(-) diff --git a/Source/Client/Managers/OfflineActivityManager.cs b/Source/Client/Managers/OfflineActivityManager.cs index 93dfe622..a45371e6 100644 --- a/Source/Client/Managers/OfflineActivityManager.cs +++ b/Source/Client/Managers/OfflineActivityManager.cs @@ -41,7 +41,7 @@ public static void RequestOfflineActivity(OfflineActivityType activityType) return; } - SessionValues.ToggleOfflineFunction(activityType); + SessionValues.ToggleOfflineActivity(activityType); if (activityType == OfflineActivityType.Spy) { diff --git a/Source/Client/Managers/OnlineActivityManager.cs b/Source/Client/Managers/OnlineActivityManager.cs index 18cb6a44..6c513998 100644 --- a/Source/Client/Managers/OnlineActivityManager.cs +++ b/Source/Client/Managers/OnlineActivityManager.cs @@ -1,29 +1,16 @@ -using RimWorld.Planet; -using RimWorld; -using System; -using System.Collections.Generic; -using System.Linq; +using System; using Verse; -using Verse.AI; using Shared; using static Shared.CommonEnumerators; -using UnityEngine; +using System.Linq; +using RimWorld; +using RimWorld.Planet; +using System.Collections.Generic; namespace GameClient { public static class OnlineActivityManager { - public static List factionPawns = new List(); - public static List nonFactionPawns = new List(); - public static List mapThings = new List(); - public static Map onlineMap; - - public static Thing queuedThing; - public static int queuedTimeSpeed; - public static WeatherDef queuedWeather; - public static GameCondition queuedGameCondition; - public static TimeSpeed maximumAllowedTimeSpeed = TimeSpeed.Fast; - public static void ParseOnlineActivityPacket(Packet packet) { OnlineActivityData data = Serializer.ConvertBytesToObject(packet.contents); @@ -39,141 +26,48 @@ public static void ParseOnlineActivityPacket(Packet packet) break; case OnlineActivityStepMode.Reject: - OnActivityReject(); + OnActivityReject(data); break; case OnlineActivityStepMode.Unavailable: - OnActivityUnavailable(); - break; - - case OnlineActivityStepMode.Action: - OnlineManagerHelper.ReceivePawnOrder(data); - break; - - case OnlineActivityStepMode.Create: - OnlineManagerHelper.ReceiveCreationOrder(data); - break; - - case OnlineActivityStepMode.Destroy: - OnlineManagerHelper.ReceiveDestructionOrder(data); - break; - - case OnlineActivityStepMode.Damage: - OnlineManagerHelper.ReceiveDamageOrder(data); - break; - - case OnlineActivityStepMode.Hediff: - OnlineManagerHelper.ReceiveHediffOrder(data); - break; - - case OnlineActivityStepMode.TimeSpeed: - OnlineManagerHelper.ReceiveTimeSpeedOrder(data); - break; - - case OnlineActivityStepMode.GameCondition: - OnlineManagerHelper.ReceiveGameConditionOrder(data); - break; - - case OnlineActivityStepMode.Weather: - OnlineManagerHelper.ReceiveWeatherOrder(data); - break; - - case OnlineActivityStepMode.Kill: - OnlineManagerHelper.ReceiveKillOrder(data); + OnActivityUnavailable(data); break; case OnlineActivityStepMode.Stop: - OnActivityStop(); + OnActivityStop(data); break; } } - public static void RequestOnlineActivity(OnlineActivityType toRequest) + public static void RequestOnlineActivity(OnlineActivityType activityType) { - if (!SessionValues.actionValues.EnableOnlineActivities) - { - DialogManager.PushNewDialog(new RT_Dialog_Error("This feature has been disabled in this server!")); - return; - } - - else if (SessionValues.currentRealTimeEvent != OnlineActivityType.None) - { - DialogManager.PushNewDialog(new RT_Dialog_Error("You are already in a real time activity!")); - } - - else - { - OnlineManagerHelper.ClearAllQueues(); - ClientValues.ToggleRealTimeHost(false); - - DialogManager.PushNewDialog(new RT_Dialog_Wait("Waiting for server response")); - - OnlineActivityData data = new OnlineActivityData(); - data._stepMode = OnlineActivityStepMode.Request; - data._activityType = toRequest; - data._fromTile = Find.AnyPlayerHomeMap.Tile; - data._toTile = SessionValues.chosenSettlement.Tile; - data._caravanHumans = OnlineManagerHelper.GetActivityHumans(); - data._caravanAnimals = OnlineManagerHelper.GetActivityAnimals(); - - Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), data); - Network.listener.EnqueuePacket(packet); - } - } - - public static void RequestStopOnlineActivity() - { - OnlineActivityData data = new OnlineActivityData(); - data._stepMode = OnlineActivityStepMode.Stop; + OnlineActivityData onlineActivityData = new OnlineActivityData(); + onlineActivityData._stepMode = OnlineActivityStepMode.Request; + onlineActivityData._activityType = activityType; + onlineActivityData._fromTile = Find.AnyPlayerHomeMap.Tile; + onlineActivityData._toTile = SessionValues.chosenSettlement.Tile; + onlineActivityData._guestHumans = OnlineActivityManagerHelper.GetActivityHumans(); + onlineActivityData._guestAnimals = OnlineActivityManagerHelper.GetActivityAnimals(); - Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), data); + Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), onlineActivityData); Network.listener.EnqueuePacket(packet); - } - - private static void JoinMap(MapFile mapFile, OnlineActivityData activityData) - { - onlineMap = MapScribeManager.StringToMap(mapFile, true, true, false, false, false, false); - factionPawns = OnlineManagerHelper.GetCaravanPawns().ToList(); - mapThings = RimworldManager.GetThingsInMap(onlineMap).OrderBy(fetch => (fetch.PositionHeld.ToVector3() - Vector3.zero).sqrMagnitude).ToList(); - - OnlineManagerHelper.SpawnMapPawns(activityData); - OnlineManagerHelper.EnterMap(activityData); - - //ALWAYS BEFORE RECEIVING ANY ORDERS BECAUSE THEY WILL BE IGNORED OTHERWISE - SessionValues.ToggleOnlineFunction(activityData._activityType); - OnlineManagerHelper.ReceiveTimeSpeedOrder(activityData); - } - - private static void SendRequestedMap(OnlineActivityData data) - { - data._stepMode = OnlineActivityStepMode.Accept; - data._mapHumans = OnlineManagerHelper.GetActivityHumans(); - data._mapAnimals = OnlineManagerHelper.GetActivityAnimals(); - data._timeSpeedOrder = OnlineManagerHelper.CreateTimeSpeedOrder(); - data._mapData = MapManager.ParseMap(onlineMap, true, false, false, true); - - Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), data); - Network.listener.EnqueuePacket(packet); + DialogManager.PushNewDialog(new RT_Dialog_Wait("Waiting for server response")); } private static void OnActivityRequest(OnlineActivityData data) { Action r1 = delegate { - OnlineManagerHelper.ClearAllQueues(); - ClientValues.ToggleRealTimeHost(true); + data._stepMode = OnlineActivityStepMode.Accept; - onlineMap = Find.WorldObjects.Settlements.Find(fetch => fetch.Tile == data._toTile).Map; - factionPawns = OnlineManagerHelper.GetMapPawns().ToList(); - mapThings = RimworldManager.GetThingsInMap(onlineMap).OrderBy(fetch => (fetch.PositionHeld.ToVector3() - Vector3.zero).sqrMagnitude).ToList(); + Map toGet = Find.WorldObjects.Settlements.First(fetch => fetch.Tile == data._toTile && fetch.Faction == Faction.OfPlayer).Map; + data._mapFile = MapScribeManager.MapToString(toGet, true, true, true, true, true, true); - SendRequestedMap(data); - - OnlineManagerHelper.SpawnMapPawns(data); + Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), data); + Network.listener.EnqueuePacket(packet); - //ALWAYS LAST TO MAKE SURE WE DON'T SEND NON-NEEDED DETAILS BEFORE EVERYTHING IS READY - SessionValues.ToggleOnlineFunction(data._activityType); + DialogManager.PushNewDialog(new RT_Dialog_Wait("Waiting for server response")); }; Action r2 = delegate @@ -183,1072 +77,185 @@ private static void OnActivityRequest(OnlineActivityData data) Network.listener.EnqueuePacket(packet); }; - RT_Dialog_YesNo promptDialog = null; - if (data._activityType == OnlineActivityType.Visit) promptDialog = new RT_Dialog_YesNo($"Visited by {data._engagerName}, accept?", r1, r2); - else if (data._activityType == OnlineActivityType.Raid) promptDialog = new RT_Dialog_YesNo($"Raided by {data._engagerName}, accept?", r1, r2); - - DialogManager.PushNewDialog(promptDialog); + DialogManager.PushNewDialog(new RT_Dialog_YesNo($"Requested activity from '{data._engagerName}'. Accept?", r1, r2)); } - private static void OnActivityAccept(OnlineActivityData visitData) + private static void OnActivityAccept(OnlineActivityData data) { - DialogManager.PopWaitDialog(); + SessionValues.ToggleOnlineActivity(data._activityType); + OnlineActivityManagerHelper.SetActivityHost(data); + OnlineActivityManagerHelper.SetActivityMap(data); + OnlineActivityManagerHelper.SetActivityPawns(); + OnlineActivityManagerHelper.SetOtherSidePawns(data); + OnlineActivityManagerHelper.SetOtherSidePawnsFaction(); + + if (OnlineActivityManagerHelper.isHost) CameraJumper.TryJump(OnlineActivityManagerHelper.nonFactionPawns[0].Position, OnlineActivityManagerHelper.activityMap); + else OnlineActivityManagerHelper.JoinActivityMap(data._activityType); - Action r1 = delegate { JoinMap(visitData._mapData, visitData); }; - Action r2 = delegate { RequestStopOnlineActivity(); }; - if (!ModManager.CheckIfMapHasConflictingMods(visitData._mapData)) r1.Invoke(); - else DialogManager.PushNewDialog(new RT_Dialog_YesNo("Map received but contains unknown mod data, continue?", r1, r2)); + Logger.Warning($"My pawns > {OnlineActivityManagerHelper.factionPawns.Length}"); + foreach(Pawn pawn in OnlineActivityManagerHelper.factionPawns) Logger.Warning(pawn.def.defName); + + Logger.Warning($"Other pawns > {OnlineActivityManagerHelper.nonFactionPawns.Length}"); + foreach(Pawn pawn in OnlineActivityManagerHelper.nonFactionPawns) Logger.Warning(pawn.def.defName); + + DialogManager.PopWaitDialog(); + DialogManager.PushNewDialog(new RT_Dialog_OK($"Should start {OnlineActivityManagerHelper.isHost}")); } - private static void OnActivityReject() + private static void OnActivityReject(OnlineActivityData data) { DialogManager.PopWaitDialog(); - DialogManager.PushNewDialog(new RT_Dialog_Error("Player rejected the activity!")); + DialogManager.PushNewDialog(new RT_Dialog_OK($"Should cancel {OnlineActivityManagerHelper.isHost}")); } - private static void OnActivityUnavailable() + private static void OnActivityUnavailable(OnlineActivityData data) { DialogManager.PopWaitDialog(); - DialogManager.PushNewDialog(new RT_Dialog_Error("Player must be online!")); + DialogManager.PushNewDialog(new RT_Dialog_Error($"This user is currently unavailable! {OnlineActivityManagerHelper.isHost}")); } - private static void OnActivityStop() + private static void OnActivityStop(OnlineActivityData data) { - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return; - else - { - foreach (Pawn pawn in nonFactionPawns.ToArray()) - { - pawn.DeSpawn(); + SessionValues.ToggleOnlineActivity(OnlineActivityType.None); - if (Find.WorldPawns.AllPawnsAliveOrDead.Contains(pawn)) Find.WorldPawns.RemovePawn(pawn); - } - - if (!ClientValues.isRealTimeHost) CaravanExitMapUtility.ExitMapAndCreateCaravan(factionPawns, Faction.OfPlayer, onlineMap.Tile, Direction8Way.North, onlineMap.Tile); - - ClientValues.ToggleRealTimeHost(false); - - SessionValues.ToggleOnlineFunction(OnlineActivityType.None); - - DialogManager.PushNewDialog(new RT_Dialog_OK("Online activity ended")); - } + DialogManager.PopWaitDialog(); + DialogManager.PushNewDialog(new RT_Dialog_Error($"Activity has ended! {OnlineActivityManagerHelper.isHost}")); } } - public static class OnlineManagerHelper + public static class OnlineActivityManagerHelper { - //Create orders - - public static PawnOrderData CreatePawnOrder(Pawn pawn, Job newJob) - { - PawnOrderData pawnOrder = new PawnOrderData(); - pawnOrder._pawnIndex = OnlineActivityManager.factionPawns.IndexOf(pawn); - - pawnOrder._targetCount = newJob.count; - if (newJob.countQueue != null) pawnOrder._queueTargetCounts = newJob.countQueue.ToArray(); - - pawnOrder._defName = newJob.def.defName; - pawnOrder._targets = GetActionTargets(newJob); - pawnOrder._targetIndexes = GetActionIndexes(newJob); - pawnOrder._targetTypes = GetActionTypes(newJob); - pawnOrder._targetFactions = GetActionTargetFactions(newJob); - - pawnOrder._queueTargetsA = GetQueuedActionTargets(newJob, 0); - pawnOrder._queueTargetIndexesA = GetQueuedActionIndexes(newJob, 0); - pawnOrder._queueTargetTypesA = GetQueuedActionTypes(newJob, 0); - pawnOrder._queueTargetFactionsA = GetQueuedActionTargetFactions(newJob, 0); - - pawnOrder._queueTargetsB = GetQueuedActionTargets(newJob, 1); - pawnOrder._queueTargetIndexesB = GetQueuedActionIndexes(newJob, 1); - pawnOrder._queueTargetTypesB = GetQueuedActionTypes(newJob, 1); - pawnOrder._queueTargetFactionsB = GetQueuedActionTargetFactions(newJob, 1); - - pawnOrder._isDrafted = GetPawnDraftState(pawn); - pawnOrder._updatedPosition = ValueParser.IntVec3ToArray(pawn.Position); - pawnOrder._updatedRotation = ValueParser.Rot4ToInt(pawn.Rotation); - - return pawnOrder; - } - - //This function doesn't take into account non-host thing creation right now, handle with care - - public static CreationOrderData CreateCreationOrder(Thing thing) - { - CreationOrderData creationOrder = new CreationOrderData(); - - if (DeepScribeHelper.CheckIfThingIsHuman(thing)) creationOrder._creationType = CreationType.Human; - else if (DeepScribeHelper.CheckIfThingIsAnimal(thing)) creationOrder._creationType = CreationType.Animal; - else creationOrder._creationType = CreationType.Thing; - - if (creationOrder._creationType == CreationType.Human) creationOrder._dataToCreate = Serializer.ConvertObjectToBytes(HumanScribeManager.HumanToString((Pawn)thing)); - else if (creationOrder._creationType == CreationType.Animal) creationOrder._dataToCreate = Serializer.ConvertObjectToBytes(AnimalScribeManager.AnimalToString((Pawn)thing)); - else - { - //Modify position based on center cell because RimWorld doesn't store it by default - thing.Position = thing.OccupiedRect().CenterCell; - creationOrder._dataToCreate = Serializer.ConvertObjectToBytes(ThingScribeManager.ItemToString(thing, thing.stackCount)); - } - - return creationOrder; - } - - public static DestructionOrderData CreateDestructionOrder(Thing thing) - { - DestructionOrderData destructionOrder = new DestructionOrderData(); - destructionOrder._indexToDestroy = OnlineActivityManager.mapThings.IndexOf(thing); - - return destructionOrder; - } - - public static DamageOrderData CreateDamageOrder(DamageInfo damageInfo, Thing afectedThing) - { - DamageOrderData damageOrder = new DamageOrderData(); - damageOrder._defName = damageInfo.Def.defName; - damageOrder._damageAmount = damageInfo.Amount; - damageOrder._ignoreArmor = damageInfo.IgnoreArmor; - damageOrder._armorPenetration = damageInfo.ArmorPenetrationInt; - damageOrder._targetIndex = OnlineActivityManager.mapThings.IndexOf(afectedThing); - if (damageInfo.Weapon != null) damageOrder._weaponDefName = damageInfo.Weapon.defName; - if (damageInfo.HitPart != null) damageOrder._hitPartDefName = damageInfo.HitPart.def.defName; - - return damageOrder; - } - - public static HediffOrderData CreateHediffOrder(Hediff hediff, Pawn pawn, OnlineActivityApplyMode applyMode) - { - HediffOrderData hediffOrder = new HediffOrderData(); - hediffOrder._applyMode = applyMode; - - //Invert the enum because it needs to be mirrored for the non-host - - if (OnlineActivityManager.factionPawns.Contains(pawn)) - { - hediffOrder._pawnFaction = OnlineActivityTargetFaction.NonFaction; - hediffOrder._hediffTargetIndex = OnlineActivityManager.factionPawns.IndexOf(pawn); - } + public static bool isHost; - else - { - hediffOrder._pawnFaction = OnlineActivityTargetFaction.Faction; - hediffOrder._hediffTargetIndex = OnlineActivityManager.nonFactionPawns.IndexOf(pawn); - } - - hediffOrder._hediffDefName = hediff.def.defName; - if (hediff.Part != null) hediffOrder._hediffPartDefName = hediff.Part.def.defName; - if (hediff.sourceDef != null) hediffOrder._hediffWeaponDefName = hediff.sourceDef.defName; - hediffOrder._hediffSeverity = hediff.Severity; - hediffOrder._hediffPermanent = hediff.IsPermanent(); - - return hediffOrder; - } - - public static TimeSpeedOrderData CreateTimeSpeedOrder() - { - TimeSpeedOrderData timeSpeedOrder = new TimeSpeedOrderData(); - timeSpeedOrder._targetTimeSpeed = OnlineActivityManager.queuedTimeSpeed; - timeSpeedOrder._targetMapTicks = RimworldManager.GetGameTicks(); - - return timeSpeedOrder; - } - - public static GameConditionOrderData CreateGameConditionOrder(GameCondition gameCondition, OnlineActivityApplyMode applyMode) - { - GameConditionOrderData gameConditionOrder = new GameConditionOrderData(); - gameConditionOrder._conditionDefName = gameCondition.def.defName; - gameConditionOrder._duration = gameCondition.Duration; - gameConditionOrder._applyMode = applyMode; - - return gameConditionOrder; - } - - public static WeatherOrderData CreateWeatherOrder(WeatherDef weatherDef) - { - WeatherOrderData weatherOrder = new WeatherOrderData(); - weatherOrder._weatherDefName = weatherDef.defName; - - return weatherOrder; - } - - public static KillOrderData CreateKillOrder(Thing instance) - { - KillOrderData killOrder = new KillOrderData(); - - //Invert the enum because it needs to be mirrored for the non-host - - if (OnlineActivityManager.factionPawns.Contains(instance)) - { - killOrder._pawnFaction = OnlineActivityTargetFaction.NonFaction; - killOrder._killTargetIndex = OnlineActivityManager.factionPawns.IndexOf((Pawn)instance); - } - - else - { - killOrder._pawnFaction = OnlineActivityTargetFaction.Faction; - killOrder._killTargetIndex = OnlineActivityManager.nonFactionPawns.IndexOf((Pawn)instance); - } - - return killOrder; - } - - //Receive orders - - public static void ReceivePawnOrder(OnlineActivityData data) - { - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return; - - try - { - Pawn pawn = OnlineActivityManager.nonFactionPawns[data._pawnOrder._pawnIndex]; - IntVec3 jobPositionStart = ValueParser.ArrayToIntVec3(data._pawnOrder._updatedPosition); - Rot4 jobRotationStart = ValueParser.IntToRot4(data._pawnOrder._updatedRotation); - ChangePawnTransform(pawn, jobPositionStart, jobRotationStart); - SetPawnDraftState(pawn, data._pawnOrder._isDrafted); - - JobDef jobDef = RimworldManager.GetJobFromDef(data._pawnOrder._defName); - LocalTargetInfo targetA = SetActionTargetsFromString(data._pawnOrder, 0); - LocalTargetInfo targetB = SetActionTargetsFromString(data._pawnOrder, 1); - LocalTargetInfo targetC = SetActionTargetsFromString(data._pawnOrder, 2); - LocalTargetInfo[] targetQueueA = SetQueuedActionTargetsFromString(data._pawnOrder, 0); - LocalTargetInfo[] targetQueueB = SetQueuedActionTargetsFromString(data._pawnOrder, 1); - - Job newJob = RimworldManager.SetJobFromDef(jobDef, targetA, targetB, targetC); - newJob.count = data._pawnOrder._targetCount; - if (data._pawnOrder._queueTargetCounts != null) newJob.countQueue = data._pawnOrder._queueTargetCounts.ToList(); - - foreach (LocalTargetInfo target in targetQueueA) newJob.AddQueuedTarget(TargetIndex.A, target); - foreach (LocalTargetInfo target in targetQueueB) newJob.AddQueuedTarget(TargetIndex.B, target); - - EnqueueThing(pawn); - ChangeCurrentJob(pawn, newJob); - ChangeJobSpeedIfNeeded(newJob); - } - catch { Logger.Warning($"Couldn't set order for pawn with index '{data._pawnOrder._pawnIndex}'"); } - } - - //This function doesn't take into account non-host thing creation right now, handle with care - - public static void ReceiveCreationOrder(OnlineActivityData data) - { - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return; - - Thing toSpawn; - if (data._creationOrder._creationType == CreationType.Human) - { - HumanFile humanData = Serializer.ConvertBytesToObject(data._creationOrder._dataToCreate); - toSpawn = HumanScribeManager.StringToHuman(humanData); - toSpawn.SetFaction(FactionValues.allyPlayer); - } - - else if (data._creationOrder._creationType == CreationType.Animal) - { - AnimalFile animalData = Serializer.ConvertBytesToObject(data._creationOrder._dataToCreate); - toSpawn = AnimalScribeManager.StringToAnimal(animalData); - toSpawn.SetFaction(FactionValues.allyPlayer); - } - - else - { - ThingFile thingData = Serializer.ConvertBytesToObject(data._creationOrder._dataToCreate); - toSpawn = ThingScribeManager.StringToItem(thingData); - } + public static Map activityMap = new Map(); - EnqueueThing(toSpawn); + public static Pawn[] factionPawns = new Pawn[0]; - //Request - RimworldManager.PlaceThingIntoMap(toSpawn, OnlineActivityManager.onlineMap, ThingPlaceMode.Direct, false); - } + public static Pawn[] nonFactionPawns = new Pawn[0]; - public static void ReceiveDestructionOrder(OnlineActivityData data) + public static void SetActivityHost(OnlineActivityData data) { - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return; - - Thing toDestroy = OnlineActivityManager.mapThings[data._destructionOrder._indexToDestroy]; - - //Request - if (ClientValues.isRealTimeHost) toDestroy.Destroy(DestroyMode.Deconstruct); - else - { - EnqueueThing(toDestroy); - toDestroy.Destroy(DestroyMode.Vanish); - } + if (Find.WorldObjects.Settlements.FirstOrDefault(fetch => fetch.Tile == data._toTile && fetch.Faction == Faction.OfPlayer) != null) isHost = true; + else isHost = false; } - public static void ReceiveDamageOrder(OnlineActivityData data) + public static void SetActivityPawns() { - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return; - - try - { - BodyPartRecord bodyPartRecord = new BodyPartRecord(); - bodyPartRecord.def = DefDatabase.AllDefs.FirstOrDefault(fetch => fetch.defName == data._damageOrder._hitPartDefName); - - DamageDef damageDef = DefDatabase.AllDefs.First(fetch => fetch.defName == data._damageOrder._defName); - ThingDef thingDef = DefDatabase.AllDefs.FirstOrDefault(fetch => fetch.defName == data._damageOrder._weaponDefName); - - DamageInfo damageInfo = new DamageInfo(damageDef, data._damageOrder._damageAmount, data._damageOrder._armorPenetration, -1, null, bodyPartRecord, thingDef); - damageInfo.SetIgnoreArmor(data._damageOrder._ignoreArmor); - - Thing toApplyTo = OnlineActivityManager.mapThings[data._damageOrder._targetIndex]; - - EnqueueThing(toApplyTo); - - //Request - toApplyTo.TakeDamage(damageInfo); - } - catch (Exception e) { Logger.Warning($"Couldn't apply damage order. Reason: {e}"); } + if (isHost) factionPawns = activityMap.mapPawns.AllPawns.ToArray(); + else factionPawns = SessionValues.chosenCaravan.PawnsListForReading.ToArray(); } - public static void ReceiveHediffOrder(OnlineActivityData data) + public static void SetOtherSidePawns(OnlineActivityData data) { - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return; + List toSet = new List(); - try + if (isHost) { - Pawn toTarget = null; - if (data._hediffOrder._pawnFaction == OnlineActivityTargetFaction.Faction) toTarget = OnlineActivityManager.factionPawns[data._hediffOrder._hediffTargetIndex]; - else toTarget = OnlineActivityManager.nonFactionPawns[data._hediffOrder._hediffTargetIndex]; - - EnqueueThing(toTarget); - - BodyPartRecord bodyPartRecord = toTarget.RaceProps.body.AllParts.FirstOrDefault(fetch => fetch.def.defName == data._hediffOrder._hediffPartDefName); - - if (data._hediffOrder._applyMode == OnlineActivityApplyMode.Add) + foreach (HumanFile human in data._guestHumans) { - HediffDef hediffDef = DefDatabase.AllDefs.First(fetch => fetch.defName == data._hediffOrder._hediffDefName); - Hediff toMake = HediffMaker.MakeHediff(hediffDef, toTarget, bodyPartRecord); - - if (data._hediffOrder._hediffWeaponDefName != null) - { - ThingDef source = DefDatabase.AllDefs.First(fetch => fetch.defName == data._hediffOrder._hediffWeaponDefName); - toMake.sourceDef = source; - toMake.sourceLabel = source.label; - } + Pawn toSpawn = HumanScribeManager.StringToHuman(human); + toSpawn.Position = activityMap.Center; - toMake.Severity = data._hediffOrder._hediffSeverity; - - if (data._hediffOrder._hediffPermanent) - { - HediffComp_GetsPermanent hediffComp = toMake.TryGetComp(); - hediffComp.IsPermanent = true; - } - - //Request - toTarget.health.AddHediff(toMake, bodyPartRecord); + RimworldManager.PlaceThingIntoMap(toSpawn, activityMap); + toSet.Add(toSpawn); } - else + foreach (AnimalFile animal in data._guestAnimals) { - Hediff hediff = toTarget.health.hediffSet.hediffs.First(fetch => fetch.def.defName == data._hediffOrder._hediffDefName && - fetch.Part.def.defName == bodyPartRecord.def.defName); + Pawn toSpawn = AnimalScribeManager.StringToAnimal(animal); + toSpawn.Position = activityMap.Center; - //Request - toTarget.health.RemoveHediff(hediff); + RimworldManager.PlaceThingIntoMap(toSpawn, activityMap); + toSet.Add(toSpawn); } } - catch (Exception e) { Logger.Warning($"Couldn't apply hediff order. Reason: {e}"); } - } - - public static void ReceiveTimeSpeedOrder(OnlineActivityData data) - { - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return; - - try - { - EnqueueTimeSpeed(data._timeSpeedOrder._targetTimeSpeed); - RimworldManager.SetGameTicks(data._timeSpeedOrder._targetMapTicks); - } - catch (Exception e) { Logger.Warning($"Couldn't apply time speed order. Reason: {e}"); } - } - - public static void ReceiveGameConditionOrder(OnlineActivityData data) - { - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return; - - try - { - GameCondition gameCondition = null; - - if (data._gameConditionOrder._applyMode == OnlineActivityApplyMode.Add) - { - GameConditionDef conditionDef = DefDatabase.AllDefs.First(fetch => fetch.defName == data._gameConditionOrder._conditionDefName); - gameCondition = GameConditionMaker.MakeCondition(conditionDef); - gameCondition.Duration = data._gameConditionOrder._duration; - EnqueueGameCondition(gameCondition); - - //Request - Find.World.gameConditionManager.RegisterCondition(gameCondition); - } - - else - { - gameCondition = Find.World.gameConditionManager.ActiveConditions.First(fetch => fetch.def.defName == data._gameConditionOrder._conditionDefName); - EnqueueGameCondition(gameCondition); - - //Request - gameCondition.End(); - } - } - catch (Exception e) { Logger.Warning($"Couldn't apply game condition order. Reason: {e}"); } - } - - public static void ReceiveWeatherOrder(OnlineActivityData data) - { - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return; - - try - { - WeatherDef weatherDef = DefDatabase.AllDefs.First(fetch => fetch.defName == data._weatherOrder._weatherDefName); - - EnqueueWeather(weatherDef); - - //Request - OnlineActivityManager.onlineMap.weatherManager.TransitionTo(weatherDef); - } - catch (Exception e) { Logger.Warning($"Couldn't apply weather order. Reason: {e}"); } - } - - public static void ReceiveKillOrder(OnlineActivityData data) - { - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return; - - try - { - Pawn toTarget = null; - if (data._killOrder._pawnFaction == OnlineActivityTargetFaction.Faction) toTarget = OnlineActivityManager.factionPawns[data._killOrder._killTargetIndex]; - else toTarget = OnlineActivityManager.nonFactionPawns[data._killOrder._killTargetIndex]; - EnqueueThing(toTarget); - - //Request - toTarget.Kill(null); - } - catch (Exception e) { Logger.Warning($"Couldn't apply kill order. Reason: {e}"); } - } - - //Misc - - //This function doesn't take into account non-host thing creation right now, handle with care - - public static void AddThingToMap(Thing thing) - { - if (DeepScribeHelper.CheckIfThingIsHuman(thing) || DeepScribeHelper.CheckIfThingIsAnimal(thing)) - { - if (ClientValues.isRealTimeHost) OnlineActivityManager.factionPawns.Add((Pawn)thing); - else OnlineActivityManager.nonFactionPawns.Add((Pawn)thing); - } - else OnlineActivityManager.mapThings.Add(thing); - } - - public static void RemoveThingFromMap(Thing thing) - { - if (OnlineActivityManager.factionPawns.Contains(thing)) OnlineActivityManager.factionPawns.Remove((Pawn)thing); - else if (OnlineActivityManager.nonFactionPawns.Contains(thing)) OnlineActivityManager.nonFactionPawns.Remove((Pawn)thing); - else OnlineActivityManager.mapThings.Remove(thing); - } - - public static void ClearAllQueues() - { - ClearThingQueue(); - ClearTimeSpeedQueue(); - ClearWeatherQueue(); - ClearGameConditionQueue(); - } - - public static void EnqueueThing(Thing thing) { OnlineActivityManager.queuedThing = thing; } - - public static void EnqueueTimeSpeed(int timeSpeed) { OnlineActivityManager.queuedTimeSpeed = timeSpeed; } - - public static void EnqueueWeather(WeatherDef weatherDef) { OnlineActivityManager.queuedWeather = weatherDef; } - - public static void EnqueueGameCondition(GameCondition gameCondition) { OnlineActivityManager.queuedGameCondition = gameCondition; } - - public static void ClearThingQueue() { OnlineActivityManager.queuedThing = null; } - - public static void ClearTimeSpeedQueue() { OnlineActivityManager.queuedTimeSpeed = 0; } - - public static void ClearWeatherQueue() { OnlineActivityManager.queuedWeather = null; } - - public static void ClearGameConditionQueue() { OnlineActivityManager.queuedGameCondition = null; } - - public static string[] GetActionTargets(Job job) - { - List targetInfoList = new List(); - - for (int i = 0; i < 3; i++) - { - LocalTargetInfo target = null; - if (i == 0) target = job.targetA; - else if (i == 1) target = job.targetB; - else if (i == 2) target = job.targetC; - - try - { - if (target.Thing == null) targetInfoList.Add(ValueParser.Vector3ToString(target.Cell)); - else - { - if (DeepScribeHelper.CheckIfThingIsHuman(target.Thing)) targetInfoList.Add(Serializer.SerializeToString(HumanScribeManager.HumanToString(target.Pawn))); - else if (DeepScribeHelper.CheckIfThingIsAnimal(target.Thing)) targetInfoList.Add(Serializer.SerializeToString(AnimalScribeManager.AnimalToString(target.Pawn))); - else targetInfoList.Add(Serializer.SerializeToString(ThingScribeManager.ItemToString(target.Thing, target.Thing.stackCount))); - } - } - catch { Logger.Error($"failed to parse {target}"); } - } - - return targetInfoList.ToArray(); - } - - public static string[] GetQueuedActionTargets(Job job, int index) - { - List targetInfoList = new List(); - - List selectedQueue = new List(); - if (index == 0) selectedQueue = job.targetQueueA; - else if (index == 1) selectedQueue = job.targetQueueB; - - if (selectedQueue == null) return targetInfoList.ToArray(); - for (int i = 0; i < selectedQueue.Count; i++) - { - try - { - if (selectedQueue[i].Thing == null) targetInfoList.Add(ValueParser.Vector3ToString(selectedQueue[i].Cell)); - else - { - if (DeepScribeHelper.CheckIfThingIsHuman(selectedQueue[i].Thing)) targetInfoList.Add(Serializer.SerializeToString(HumanScribeManager.HumanToString(selectedQueue[i].Pawn))); - else if (DeepScribeHelper.CheckIfThingIsAnimal(selectedQueue[i].Thing)) targetInfoList.Add(Serializer.SerializeToString(AnimalScribeManager.AnimalToString(selectedQueue[i].Pawn))); - else targetInfoList.Add(Serializer.SerializeToString(ThingScribeManager.ItemToString(selectedQueue[i].Thing, 1))); - } - } - catch { Logger.Error($"failed to parse {selectedQueue[i]}"); } - } - - return targetInfoList.ToArray(); - } - - public static LocalTargetInfo SetActionTargetsFromString(PawnOrderData pawnOrder, int index) - { - LocalTargetInfo toGet = LocalTargetInfo.Invalid; - - try - { - switch (pawnOrder._targetTypes[index]) - { - case ActionTargetType.Thing: - toGet = new LocalTargetInfo(OnlineActivityManager.mapThings[pawnOrder._targetIndexes[index]]); - break; - - case ActionTargetType.Human: - if (pawnOrder._targetFactions[index] == OnlineActivityTargetFaction.Faction) - { - toGet = new LocalTargetInfo(OnlineActivityManager.factionPawns[pawnOrder._targetIndexes[index]]); - } - else if (pawnOrder._targetFactions[index] == OnlineActivityTargetFaction.NonFaction) - { - toGet = new LocalTargetInfo(OnlineActivityManager.nonFactionPawns[pawnOrder._targetIndexes[index]]); - } - break; - - case ActionTargetType.Animal: - if (pawnOrder._targetFactions[index] == OnlineActivityTargetFaction.Faction) - { - toGet = new LocalTargetInfo(OnlineActivityManager.factionPawns[pawnOrder._targetIndexes[index]]); - } - else if (pawnOrder._targetFactions[index] == OnlineActivityTargetFaction.NonFaction) - { - toGet = new LocalTargetInfo(OnlineActivityManager.nonFactionPawns[pawnOrder._targetIndexes[index]]); - } - break; - - case ActionTargetType.Cell: - toGet = new LocalTargetInfo(ValueParser.StringToVector3(pawnOrder._targets[index])); - break; - } - } - catch (Exception e) { Logger.Error(e.ToString()); } - - return toGet; - } - - public static LocalTargetInfo[] SetQueuedActionTargetsFromString(PawnOrderData pawnOrder, int index) - { - List toGet = new List(); - - int[] actionTargetIndexes = null; - string[] actionTargets = null; - ActionTargetType[] actionTargetTypes = null; - - if (index == 0) - { - actionTargetIndexes = pawnOrder._queueTargetIndexesA.ToArray(); - actionTargets = pawnOrder._queueTargetsA.ToArray(); - actionTargetTypes = pawnOrder._queueTargetTypesA.ToArray(); - } - - else if (index == 1) - { - actionTargetIndexes = pawnOrder._queueTargetIndexesB.ToArray(); - actionTargets = pawnOrder._queueTargetsB.ToArray(); - actionTargetTypes = pawnOrder._queueTargetTypesB.ToArray(); - } - - for (int i = 0; i < actionTargets.Length; i++) - { - try - { - switch (actionTargetTypes[index]) - { - case ActionTargetType.Thing: - toGet.Add(new LocalTargetInfo(OnlineActivityManager.mapThings[actionTargetIndexes[i]])); - break; - - case ActionTargetType.Human: - if (pawnOrder._targetFactions[index] == OnlineActivityTargetFaction.Faction) - { - toGet.Add(new LocalTargetInfo(OnlineActivityManager.factionPawns[pawnOrder._targetIndexes[index]])); - } - else if (pawnOrder._targetFactions[index] == OnlineActivityTargetFaction.NonFaction) - { - toGet.Add(new LocalTargetInfo(OnlineActivityManager.nonFactionPawns[pawnOrder._targetIndexes[index]])); - } - break; - - case ActionTargetType.Animal: - if (pawnOrder._targetFactions[index] == OnlineActivityTargetFaction.Faction) - { - toGet.Add(new LocalTargetInfo(OnlineActivityManager.factionPawns[pawnOrder._targetIndexes[index]])); - } - else if (pawnOrder._targetFactions[index] == OnlineActivityTargetFaction.NonFaction) - { - toGet.Add(new LocalTargetInfo(OnlineActivityManager.nonFactionPawns[pawnOrder._targetIndexes[index]])); - } - break; - - case ActionTargetType.Cell: - toGet.Add(new LocalTargetInfo(ValueParser.StringToVector3(actionTargets[i]))); - break; - } - } - catch (Exception e) { Logger.Error(e.ToString()); } - } - - return toGet.ToArray(); - } - - public static OnlineActivityTargetFaction[] GetActionTargetFactions(Job job) - { - List targetFactions = new List(); - - for (int i = 0; i < 3; i++) - { - LocalTargetInfo target = null; - if (i == 0) target = job.targetA; - else if (i == 1) target = job.targetB; - else if (i == 2) target = job.targetC; - - try - { - if (target.Thing == null) targetFactions.Add(OnlineActivityTargetFaction.None); - else - { - //Faction and non-faction pawns get inverted in here to send into the other side - - if (OnlineActivityManager.factionPawns.Contains(target.Thing)) targetFactions.Add(OnlineActivityTargetFaction.NonFaction); - else if (OnlineActivityManager.nonFactionPawns.Contains(target.Thing)) targetFactions.Add(OnlineActivityTargetFaction.Faction); - else if (OnlineActivityManager.mapThings.Contains(target.Thing)) targetFactions.Add(OnlineActivityTargetFaction.None); - } - } - catch { Logger.Error($"failed to parse {target}"); } - } - - return targetFactions.ToArray(); - } - - public static OnlineActivityTargetFaction[] GetQueuedActionTargetFactions(Job job, int index) - { - List targetFactions = new List(); - - List selectedQueue = new List(); - if (index == 0) selectedQueue = job.targetQueueA; - else if (index == 1) selectedQueue = job.targetQueueB; - - if (selectedQueue == null) return targetFactions.ToArray(); - for (int i = 0; i < selectedQueue.Count; i++) + else { - try + foreach (Pawn pawn in activityMap.mapPawns.AllPawns.Where(fetch => fetch.Faction != Faction.OfPlayer)) { - if (selectedQueue[i].Thing == null) targetFactions.Add(OnlineActivityTargetFaction.None); - else - { - //Faction and non-faction pawns get inverted in here to send into the other side - - if (OnlineActivityManager.factionPawns.Contains(selectedQueue[i].Thing)) targetFactions.Add(OnlineActivityTargetFaction.NonFaction); - else if (OnlineActivityManager.nonFactionPawns.Contains(selectedQueue[i].Thing)) targetFactions.Add(OnlineActivityTargetFaction.Faction); - else if (OnlineActivityManager.mapThings.Contains(selectedQueue[i].Thing)) targetFactions.Add(OnlineActivityTargetFaction.None); - } + toSet.Add(pawn); } - catch { Logger.Error($"failed to parse {selectedQueue[i]}"); } } - return targetFactions.ToArray(); + nonFactionPawns = toSet.ToArray(); } - public static int[] GetActionIndexes(Job job) + public static void SetOtherSidePawnsFaction() { - List targetIndexList = new List(); - - for (int i = 0; i < 3; i++) + foreach (Pawn pawn in nonFactionPawns) { - LocalTargetInfo target = null; - if (i == 0) target = job.targetA; - else if (i == 1) target = job.targetB; - else if (i == 2) target = job.targetC; - - try - { - if (target.Thing == null) targetIndexList.Add(0); - else - { - if (OnlineActivityManager.factionPawns.Contains(target.Thing)) targetIndexList.Add(OnlineActivityManager.factionPawns.IndexOf((Pawn)target.Thing)); - else if (OnlineActivityManager.nonFactionPawns.Contains(target.Thing)) targetIndexList.Add(OnlineActivityManager.nonFactionPawns.IndexOf((Pawn)target.Thing)); - else if (OnlineActivityManager.mapThings.Contains(target.Thing)) targetIndexList.Add(OnlineActivityManager.mapThings.IndexOf(target.Thing)); - } - } - catch { Logger.Error($"failed to parse {target}"); } + if (SessionValues.currentRealTimeEvent == OnlineActivityType.Visit) pawn.SetFactionDirect(FactionValues.allyPlayer); + else pawn.SetFactionDirect(FactionValues.enemyPlayer); } - - return targetIndexList.ToArray(); } - public static int[] GetQueuedActionIndexes(Job job, int index) + public static void SetActivityMap(OnlineActivityData data) { - List targetIndexList = new List(); - - List selectedQueue = new List(); - if (index == 0) selectedQueue = job.targetQueueA; - else if (index == 1) selectedQueue = job.targetQueueB; - - if (selectedQueue == null) return targetIndexList.ToArray(); - for (int i = 0; i < selectedQueue.Count; i++) - { - try - { - if (selectedQueue[i].Thing == null) targetIndexList.Add(0); - else - { - if (OnlineActivityManager.factionPawns.Contains(selectedQueue[i].Thing)) targetIndexList.Add(OnlineActivityManager.factionPawns.IndexOf((Pawn)selectedQueue[i].Thing)); - else if (OnlineActivityManager.nonFactionPawns.Contains(selectedQueue[i].Thing)) targetIndexList.Add(OnlineActivityManager.nonFactionPawns.IndexOf((Pawn)selectedQueue[i].Thing)); - else if (OnlineActivityManager.mapThings.Contains(selectedQueue[i].Thing)) targetIndexList.Add(OnlineActivityManager.mapThings.IndexOf(selectedQueue[i].Thing)); - } - } - catch { Logger.Error($"failed to parse {selectedQueue[i]}"); } - } - - return targetIndexList.ToArray(); + if (isHost) activityMap = Find.WorldObjects.Settlements.FirstOrDefault(fetch => fetch.Tile == data._toTile && fetch.Faction == Faction.OfPlayer).Map; + else activityMap = MapScribeManager.StringToMap(data._mapFile, true, true, true, true, true, true); } - public static ActionTargetType[] GetActionTypes(Job job) + public static void JoinActivityMap(OnlineActivityType activityType) { - List targetTypeList = new List(); - - for (int i = 0; i < 3; i++) + if (activityType == OnlineActivityType.Visit) { - LocalTargetInfo target = null; - if (i == 0) target = job.targetA; - else if (i == 1) target = job.targetB; - else if (i == 2) target = job.targetC; - - try - { - if (target.Thing == null) targetTypeList.Add(ActionTargetType.Cell); - else - { - if (DeepScribeHelper.CheckIfThingIsHuman(target.Thing)) targetTypeList.Add(ActionTargetType.Human); - else if (DeepScribeHelper.CheckIfThingIsAnimal(target.Thing)) targetTypeList.Add(ActionTargetType.Animal); - else targetTypeList.Add(ActionTargetType.Thing); - } - } - catch { Logger.Error($"failed to parse {target}"); } + CaravanEnterMapUtility.Enter(SessionValues.chosenCaravan, activityMap, CaravanEnterMode.Edge, + CaravanDropInventoryMode.DoNotDrop, draftColonists: false); } - return targetTypeList.ToArray(); - } - - public static ActionTargetType[] GetQueuedActionTypes(Job job, int index) - { - List targetTypeList = new List(); - - List selectedQueue = new List(); - if (index == 0) selectedQueue = job.targetQueueA; - else if (index == 1) selectedQueue = job.targetQueueB; - - if (selectedQueue == null) return targetTypeList.ToArray(); - for (int i = 0; i < selectedQueue.Count; i++) + else if (activityType == OnlineActivityType.Raid) { - try - { - if (selectedQueue[i].Thing == null) targetTypeList.Add(ActionTargetType.Cell); - else - { - if (DeepScribeHelper.CheckIfThingIsHuman(selectedQueue[i].Thing)) targetTypeList.Add(ActionTargetType.Human); - else if (DeepScribeHelper.CheckIfThingIsAnimal(selectedQueue[i].Thing)) targetTypeList.Add(ActionTargetType.Animal); - else targetTypeList.Add(ActionTargetType.Thing); - } - } - catch { Logger.Error($"failed to parse {selectedQueue[i]}"); } - } - - return targetTypeList.ToArray(); - } - - public static void SetPawnDraftState(Pawn pawn, bool shouldBeDrafted) - { - try - { - pawn.drafter ??= new Pawn_DraftController(pawn); - - if (shouldBeDrafted) pawn.drafter.Drafted = true; - else { pawn.drafter.Drafted = false; } + SettlementUtility.Attack(SessionValues.chosenCaravan, SessionValues.chosenSettlement); } - catch (Exception e) { Logger.Warning($"Couldn't apply pawn draft state for {pawn.Label}. Reason: {e}"); } - } - public static bool GetPawnDraftState(Pawn pawn) - { - if (pawn.drafter == null) return false; - else return pawn.drafter.Drafted; + CameraJumper.TryJump(factionPawns[0].Position, activityMap); } - public static void ChangePawnTransform(Pawn pawn, IntVec3 pawnPosition, Rot4 pawnRotation) + public static HumanFile[] GetActivityHumans() { - pawn.Position = pawnPosition; - pawn.Rotation = pawnRotation; - pawn.pather.Notify_Teleported_Int(); - } - - public static void ChangeCurrentJob(Pawn pawn, Job newJob) - { - pawn.jobs.ClearQueuedJobs(); - if (pawn.jobs.curJob != null) pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, false); - - //TODO - //Investigate if this can be implemented - //pawn.Reserve(newJob.targetA, newJob); - - newJob.TryMakePreToilReservations(pawn, false); - pawn.jobs.StartJob(newJob); - } + List toGet = new List(); - public static void ChangeJobSpeedIfNeeded(Job job) - { - if (job.def == JobDefOf.GotoWander) job.locomotionUrgency = LocomotionUrgency.Walk; - else if (job.def == JobDefOf.Wait_Wander) job.locomotionUrgency = LocomotionUrgency.Walk; - } - - public static void SpawnMapPawns(OnlineActivityData activityData) - { - if (ClientValues.isRealTimeHost) + if (isHost) { - OnlineActivityManager.nonFactionPawns = GetCaravanPawns(activityData).ToList(); - foreach (Pawn pawn in OnlineActivityManager.nonFactionPawns) + foreach (Pawn pawn in activityMap.mapPawns.AllPawns.Where(fetch => fetch.Faction == Faction.OfPlayer && DeepScribeHelper.CheckIfThingIsHuman(fetch))) { - if (activityData._activityType == OnlineActivityType.Visit) pawn.SetFaction(FactionValues.allyPlayer); - else if (activityData._activityType == OnlineActivityType.Raid) pawn.SetFaction(FactionValues.enemyPlayer); - - //Initial position and rotation left to default since caravan doesn't have it stored - GenSpawn.Spawn(pawn, OnlineActivityManager.onlineMap.Center, OnlineActivityManager.onlineMap, Rot4.Random); + toGet.Add(HumanScribeManager.HumanToString(pawn)); } } else { - OnlineActivityManager.nonFactionPawns = GetMapPawns(activityData).ToList(); - foreach (Pawn pawn in OnlineActivityManager.nonFactionPawns) - { - if (activityData._activityType == OnlineActivityType.Visit) pawn.SetFaction(FactionValues.allyPlayer); - else if (activityData._activityType == OnlineActivityType.Raid) pawn.SetFaction(FactionValues.enemyPlayer); - - //Initial position and rotation grabbed from online details - GenSpawn.Spawn(pawn, pawn.Position, OnlineActivityManager.onlineMap, pawn.Rotation); - } - } - } - - public static Pawn[] GetMapPawns(OnlineActivityData activityData = null) - { - if (ClientValues.isRealTimeHost) - { - List mapHumans = OnlineActivityManager.onlineMap.mapPawns.AllPawns - .FindAll(fetch => DeepScribeHelper.CheckIfThingIsHuman(fetch)) - .OrderBy(p => p.def.defName) - .ToList(); - - List mapAnimals = OnlineActivityManager.onlineMap.mapPawns.AllPawns - .FindAll(fetch => DeepScribeHelper.CheckIfThingIsAnimal(fetch)) - .OrderBy(p => p.def.defName) - .ToList(); - - List allPawns = new List(); - foreach (Pawn pawn in mapHumans) allPawns.Add(pawn); - foreach (Pawn pawn in mapAnimals) allPawns.Add(pawn); - - return allPawns.ToArray(); - } - - else - { - List pawnList = new List(); - - foreach (HumanFile humanData in activityData._mapHumans) - { - Pawn human = HumanScribeManager.StringToHuman(humanData); - pawnList.Add(human); - } - - foreach (AnimalFile animalData in activityData._mapAnimals) + foreach (Pawn pawn in SessionValues.chosenCaravan.PawnsListForReading.Where(fetch => DeepScribeHelper.CheckIfThingIsHuman(fetch))) { - Pawn animal = AnimalScribeManager.StringToAnimal(animalData); - pawnList.Add(animal); + toGet.Add(HumanScribeManager.HumanToString(pawn)); } - - return pawnList.ToArray(); } - } - public static Pawn[] GetCaravanPawns(OnlineActivityData activityData = null) - { - if (ClientValues.isRealTimeHost) - { - List pawnList = new List(); - - foreach (HumanFile humanData in activityData._caravanHumans) - { - Pawn human = HumanScribeManager.StringToHuman(humanData); - pawnList.Add(human); - } - - foreach (AnimalFile animalData in activityData._caravanAnimals) - { - Pawn animal = AnimalScribeManager.StringToAnimal(animalData); - pawnList.Add(animal); - } - - return pawnList.ToArray(); - } - - else - { - List caravanHumans = SessionValues.chosenCaravan.PawnsListForReading - .FindAll(fetch => DeepScribeHelper.CheckIfThingIsHuman(fetch)) - .OrderBy(p => p.def.defName) - .ToList(); - - List caravanAnimals = SessionValues.chosenCaravan.PawnsListForReading - .FindAll(fetch => DeepScribeHelper.CheckIfThingIsAnimal(fetch)) - .OrderBy(p => p.def.defName) - .ToList(); - - List allPawns = new List(); - foreach (Pawn pawn in caravanHumans) allPawns.Add(pawn); - foreach (Pawn pawn in caravanAnimals) allPawns.Add(pawn); - - return allPawns.ToArray(); - } + return toGet.ToArray(); } - public static List GetActivityHumans() + public static AnimalFile[] GetActivityAnimals() { - if (ClientValues.isRealTimeHost) - { - List mapHumans = OnlineActivityManager.onlineMap.mapPawns.AllPawns - .FindAll(fetch => DeepScribeHelper.CheckIfThingIsHuman(fetch)) - .OrderBy(p => p.def.defName) - .ToList(); - - List convertedList = new List(); - foreach (Pawn human in mapHumans) - { - HumanFile data = HumanScribeManager.HumanToString(human); - convertedList.Add(data); - } - - return convertedList; - } - - else - { - List caravanHumans = SessionValues.chosenCaravan.PawnsListForReading - .FindAll(fetch => DeepScribeHelper.CheckIfThingIsHuman(fetch)) - .OrderBy(p => p.def.defName) - .ToList(); - - List convertedList = new List(); - foreach (Pawn human in caravanHumans) - { - HumanFile data = HumanScribeManager.HumanToString(human); - convertedList.Add(data); - } - - return convertedList; - } - } + List toGet = new List(); - public static List GetActivityAnimals() - { - if (ClientValues.isRealTimeHost) + if (isHost) { - List mapAnimals = OnlineActivityManager.onlineMap.mapPawns.AllPawns - .FindAll(fetch => DeepScribeHelper.CheckIfThingIsAnimal(fetch)) - .OrderBy(p => p.def.defName) - .ToList(); - - List convertedList = new List(); - foreach (Pawn animal in mapAnimals) + foreach (Pawn pawn in activityMap.mapPawns.AllPawns.Where(fetch => fetch.Faction == Faction.OfPlayer && DeepScribeHelper.CheckIfThingIsAnimal(fetch))) { - AnimalFile data = AnimalScribeManager.AnimalToString(animal); - convertedList.Add(data); + toGet.Add(AnimalScribeManager.AnimalToString(pawn)); } - - return convertedList; } else { - List caravanAnimals = SessionValues.chosenCaravan.PawnsListForReading - .FindAll(fetch => DeepScribeHelper.CheckIfThingIsAnimal(fetch)) - .OrderBy(p => p.def.defName) - .ToList(); - - List convertedList = new List(); - foreach (Pawn animal in caravanAnimals) + foreach (Pawn pawn in SessionValues.chosenCaravan.PawnsListForReading.Where(fetch => fetch.Faction == Faction.OfPlayer && DeepScribeHelper.CheckIfThingIsAnimal(fetch))) { - AnimalFile data = AnimalScribeManager.AnimalToString(animal); - convertedList.Add(data); + toGet.Add(AnimalScribeManager.AnimalToString(pawn)); } - - return convertedList; - } - } - - public static bool CheckIfIgnoreThingSync(Thing toCheck) - { - if (toCheck is Projectile) return true; - else if (toCheck is Mote) return true; - else return false; - } - - public static void EnterMap(OnlineActivityData activityData) - { - if (activityData._activityType == OnlineActivityType.Visit) - { - CaravanEnterMapUtility.Enter(SessionValues.chosenCaravan, OnlineActivityManager.onlineMap, CaravanEnterMode.Edge, - CaravanDropInventoryMode.DoNotDrop, draftColonists: false); - } - - else if (activityData._activityType == OnlineActivityType.Raid) - { - SettlementUtility.Attack(SessionValues.chosenCaravan, SessionValues.chosenSettlement); } - CameraJumper.TryJump(OnlineActivityManager.factionPawns[0].Position, OnlineActivityManager.onlineMap); + return toGet.ToArray(); } } } diff --git a/Source/Client/Patches/OnlineActivityPatches.cs b/Source/Client/Patches/OnlineActivityPatches.cs index fb7745a7..b666e802 100644 --- a/Source/Client/Patches/OnlineActivityPatches.cs +++ b/Source/Client/Patches/OnlineActivityPatches.cs @@ -10,158 +10,6 @@ namespace GameClient { - [HarmonyPatch(typeof(Thing), nameof(Thing.SpawnSetup))] - public static class PatchCreateThing - { - [HarmonyPrefix] - public static bool DoPre(Map map, Thing __instance) - { - if (Network.state == ClientNetworkState.Disconnected) return true; - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return true; - if (OnlineManagerHelper.CheckIfIgnoreThingSync(__instance)) return true; - - //Don't execute patch if is different than the online one - if (OnlineActivityManager.onlineMap != map) return true; - else - { - if (ClientValues.isRealTimeHost) - { - OnlineActivityData OnlineActivityData = new OnlineActivityData(); - OnlineActivityData._stepMode = OnlineActivityStepMode.Create; - OnlineActivityData._creationOrder = OnlineManagerHelper.CreateCreationOrder(__instance); - - Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), OnlineActivityData); - Network.listener.EnqueuePacket(packet); - - //KEEP ALWAYS AS AT THE BOTTOM AS POSSIBLE - OnlineManagerHelper.AddThingToMap(__instance); - return true; - } - - else - { - //IF COMING FROM HOST - - if (OnlineActivityManager.queuedThing == __instance) - { - OnlineManagerHelper.ClearThingQueue(); - OnlineManagerHelper.AddThingToMap(__instance); - return true; - } - - //IF PLAYER ASKING FOR - - else return false; - } - } - } - } - - [HarmonyPatch(typeof(Thing), nameof(Thing.Destroy))] - public static class PatchDestroyThing - { - [HarmonyPrefix] - public static bool DoPre(Thing __instance) - { - if (Network.state == ClientNetworkState.Disconnected) return true; - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return true; - if (OnlineManagerHelper.CheckIfIgnoreThingSync(__instance)) return true; - - //Don't execute patch if map doesn't contain the thing already - bool shouldPatch = false; - if (OnlineActivityManager.factionPawns.Contains(__instance)) shouldPatch = true; - else if (OnlineActivityManager.nonFactionPawns.Contains(__instance)) shouldPatch = true; - else if (OnlineActivityManager.mapThings.Contains(__instance)) shouldPatch = true; - - if (!shouldPatch) return true; - else - { - if (ClientValues.isRealTimeHost) - { - OnlineActivityData onlineActivityData = new OnlineActivityData(); - onlineActivityData._stepMode = OnlineActivityStepMode.Destroy; - onlineActivityData._destructionOrder = OnlineManagerHelper.CreateDestructionOrder(__instance); - - Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), onlineActivityData); - Network.listener.EnqueuePacket(packet); - - //KEEP ALWAYS AS AT THE BOTTOM AS POSSIBLE - OnlineManagerHelper.RemoveThingFromMap(__instance); - return true; - } - - else - { - //IF COMING FROM HOST - - if (OnlineActivityManager.queuedThing == __instance) - { - OnlineManagerHelper.ClearThingQueue(); - OnlineManagerHelper.RemoveThingFromMap(__instance); - return true; - } - - //IF PLAYER ASKING FOR - - else return false; - } - } - } - } - - //TODO - //GIVE THIS PATCH SOME MORE LOVE - - [HarmonyPatch(typeof(Thing), nameof(Thing.Kill))] - public static class PatchKillThing - { - [HarmonyPrefix] - public static bool DoPre(Thing __instance) - { - if (Network.state == ClientNetworkState.Disconnected) return true; - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return true; - - //Don't execute patch if map doesn't contain the thing already - bool shouldPatch = false; - if (OnlineActivityManager.factionPawns.Contains(__instance)) shouldPatch = true; - else if (OnlineActivityManager.nonFactionPawns.Contains(__instance)) shouldPatch = true; - - if (!shouldPatch) return true; - else - { - if (ClientValues.isRealTimeHost) - { - OnlineActivityData onlineActivityData = new OnlineActivityData(); - onlineActivityData._stepMode = OnlineActivityStepMode.Kill; - onlineActivityData._killOrder = OnlineManagerHelper.CreateKillOrder(__instance); - - Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), onlineActivityData); - Network.listener.EnqueuePacket(packet); - - //KEEP ALWAYS AS AT THE BOTTOM AS POSSIBLE - OnlineManagerHelper.RemoveThingFromMap(__instance); - return true; - } - - else - { - //IF COMING FROM HOST - - if (OnlineActivityManager.queuedThing == __instance) - { - OnlineManagerHelper.ClearThingQueue(); - OnlineManagerHelper.RemoveThingFromMap(__instance); - return true; - } - - //IF PLAYER ASKING FOR - - else return false; - } - } - } - } - [HarmonyPatch(typeof(Pawn_JobTracker), nameof(Pawn_JobTracker.StartJob))] public static class PatchStartNewJob { @@ -173,459 +21,26 @@ public static bool DoPre(Job newJob, Pawn ___pawn) //Don't execute patch if map doesn't contain the pawn bool shouldPatch = false; - if (OnlineActivityManager.factionPawns.Contains(___pawn)) shouldPatch = true; - else if (OnlineActivityManager.nonFactionPawns.Contains(___pawn)) shouldPatch = true; + if (OnlineActivityManagerHelper.factionPawns.Contains(___pawn)) shouldPatch = true; + else if (OnlineActivityManagerHelper.nonFactionPawns.Contains(___pawn)) shouldPatch = true; if (!shouldPatch) return true; else { - if (OnlineActivityManager.factionPawns.Contains(___pawn)) + if (OnlineActivityManagerHelper.factionPawns.Contains(___pawn)) { - OnlineActivityData data = new OnlineActivityData(); - data._stepMode = OnlineActivityStepMode.Action; - data._pawnOrder = OnlineManagerHelper.CreatePawnOrder(___pawn, newJob); + //This is our pawn and we prepare the packet for the other player - Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), data); - Network.listener.EnqueuePacket(packet); return true; } else { - //IF COMING FROM HOST - - if (OnlineActivityManager.queuedThing == ___pawn) - { - OnlineManagerHelper.ClearThingQueue(); - return true; - } - - //IF PLAYER ASKING FOR - - else return false; - } - } - } - } - - [HarmonyPatch(typeof(Thing), nameof(Thing.TakeDamage))] - public static class PatchApplyDamage - { - [HarmonyPrefix] - public static bool DoPre(DamageInfo dinfo, Thing __instance, ref DamageWorker.DamageResult __result) - { - if (Network.state == ClientNetworkState.Disconnected) return true; - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return true; - - if (!OnlineActivityManager.mapThings.Contains(__instance)) return true; - else - { - if (ClientValues.isRealTimeHost) - { - OnlineActivityData onlineActivityData = new OnlineActivityData(); - onlineActivityData._stepMode = OnlineActivityStepMode.Damage; - onlineActivityData._damageOrder = OnlineManagerHelper.CreateDamageOrder(dinfo, __instance); - - Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), onlineActivityData); - Network.listener.EnqueuePacket(packet); - return true; - } - - else - { - //IF COMING FROM HOST - - if (OnlineActivityManager.queuedThing == __instance) - { - OnlineManagerHelper.ClearThingQueue(); - return true; - } - - //IF PLAYER ASKING FOR - - else - { - //Create empty DamageWorker.DamageResult so the functions expecting it don't freak out - __result = new DamageWorker.DamageResult(); - __result.totalDamageDealt = 0f; - return false; - } - } - } - } - } - - [HarmonyPatch(typeof(Pawn_HealthTracker), nameof(Pawn_HealthTracker.AddHediff), new[] { typeof(Hediff), typeof(BodyPartRecord), typeof(DamageInfo), typeof(DamageWorker.DamageResult), })] - public static class PatchAddHediff - { - [HarmonyPrefix] - public static bool DoPre(Hediff hediff, BodyPartRecord part, DamageInfo? dinfo, DamageWorker.DamageResult result, Pawn ___pawn) - { - if (Network.state == ClientNetworkState.Disconnected) return true; - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return true; - - bool shouldPatch = false; - if (OnlineActivityManager.factionPawns.Contains(___pawn)) shouldPatch = true; - else if (OnlineActivityManager.nonFactionPawns.Contains(___pawn)) shouldPatch = true; - - if (!shouldPatch) return true; - else - { - if (ClientValues.isRealTimeHost) - { - OnlineActivityData onlineActivityData = new OnlineActivityData(); - onlineActivityData._stepMode = OnlineActivityStepMode.Hediff; - onlineActivityData._hediffOrder = OnlineManagerHelper.CreateHediffOrder(hediff, ___pawn, OnlineActivityApplyMode.Add); - - Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), onlineActivityData); - Network.listener.EnqueuePacket(packet); - return true; - } - - else - { - //IF COMING FROM HOST - - if (OnlineActivityManager.queuedThing == ___pawn) - { - OnlineManagerHelper.ClearThingQueue(); - return true; - } - - //IF PLAYER ASKING FOR - - else return false; - } - } - } - } - - [HarmonyPatch(typeof(Pawn_HealthTracker), nameof(Pawn_HealthTracker.RemoveHediff))] - public static class PatchRemoveHediff - { - [HarmonyPrefix] - public static bool DoPre(Hediff hediff, Pawn ___pawn) - { - if (Network.state == ClientNetworkState.Disconnected) return true; - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return true; - - bool shouldPatch = false; - if (OnlineActivityManager.factionPawns.Contains(___pawn)) shouldPatch = true; - else if (OnlineActivityManager.nonFactionPawns.Contains(___pawn)) shouldPatch = true; - - if (!shouldPatch) return true; - else - { - if (ClientValues.isRealTimeHost) - { - OnlineActivityData onlineActivityData = new OnlineActivityData(); - onlineActivityData._stepMode = OnlineActivityStepMode.Hediff; - onlineActivityData._hediffOrder = OnlineManagerHelper.CreateHediffOrder(hediff, ___pawn, OnlineActivityApplyMode.Remove); - - Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), onlineActivityData); - Network.listener.EnqueuePacket(packet); - return true; - } - - else - { - //IF COMING FROM HOST - - if (OnlineActivityManager.queuedThing == ___pawn) - { - OnlineManagerHelper.ClearThingQueue(); - return true; - } - - //IF PLAYER ASKING FOR - - else return false; - } - } - } - } - - [HarmonyPatch(typeof(GameConditionManager), nameof(GameConditionManager.RegisterCondition))] - public static class PatchAddGameCondition - { - [HarmonyPrefix] - public static bool DoPre(GameCondition cond) - { - if (Network.state == ClientNetworkState.Disconnected) return true; - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return true; - - if (ClientValues.isRealTimeHost) - { - OnlineActivityData OnlineActivityData = new OnlineActivityData(); - OnlineActivityData._stepMode = OnlineActivityStepMode.GameCondition; - OnlineActivityData._gameConditionOrder = OnlineManagerHelper.CreateGameConditionOrder(cond, OnlineActivityApplyMode.Add); - - Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), OnlineActivityData); - Network.listener.EnqueuePacket(packet); - return true; - } - - else - { - //IF COMING FROM HOST - - if (OnlineActivityManager.queuedGameCondition == cond) - { - OnlineManagerHelper.ClearGameConditionQueue(); - return true; - } - - //IF PLAYER ASKING FOR - - else return false; - } - } - } - - [HarmonyPatch(typeof(GameCondition), nameof(GameCondition.End))] - public static class PatchRemoveGameCondition - { - [HarmonyPrefix] - public static bool DoPre(GameCondition __instance) - { - if (Network.state == ClientNetworkState.Disconnected) return true; - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return true; - - if (ClientValues.isRealTimeHost) - { - OnlineActivityData OnlineActivityData = new OnlineActivityData(); - OnlineActivityData._stepMode = OnlineActivityStepMode.GameCondition; - OnlineActivityData._gameConditionOrder = OnlineManagerHelper.CreateGameConditionOrder(__instance, OnlineActivityApplyMode.Remove); - - Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), OnlineActivityData); - Network.listener.EnqueuePacket(packet); - return true; - } + //This is not our pawn and we shouldn't handle him from here - else - { - //IF COMING FROM HOST - - if (OnlineActivityManager.queuedGameCondition == __instance) - { - OnlineManagerHelper.ClearGameConditionQueue(); - return true; - } - - //IF PLAYER ASKING FOR - - else return false; - } - } - } - - [HarmonyPatch(typeof(TickManager), nameof(TickManager.TickManagerUpdate))] - public static class PatchTickSpeedChange - { - [HarmonyPrefix] - public static bool DoPre(TickManager __instance) - { - if (Network.state == ClientNetworkState.Disconnected) return true; - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return true; - - if (ClientValues.isRealTimeHost) - { - if (__instance.CurTimeSpeed > OnlineActivityManager.maximumAllowedTimeSpeed) __instance.CurTimeSpeed = OnlineActivityManager.maximumAllowedTimeSpeed; - - if (OnlineActivityManager.queuedTimeSpeed != (int)__instance.CurTimeSpeed) - { - OnlineActivityManager.queuedTimeSpeed = (int)__instance.CurTimeSpeed; - - OnlineActivityData onlineActivityData = new OnlineActivityData(); - onlineActivityData._stepMode = OnlineActivityStepMode.TimeSpeed; - onlineActivityData._timeSpeedOrder = OnlineManagerHelper.CreateTimeSpeedOrder(); - - Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), onlineActivityData); - Network.listener.EnqueuePacket(packet); + return false; } } - - else - { - //Always change the CurTimeSpeed to whatever last update we got from host - - if (__instance.CurTimeSpeed != (TimeSpeed)OnlineActivityManager.queuedTimeSpeed) - { - __instance.CurTimeSpeed = (TimeSpeed)OnlineActivityManager.queuedTimeSpeed; - } - } - - return true; - } - } - - [HarmonyPatch(typeof(WeatherManager), nameof(WeatherManager.TransitionTo))] - public static class PatchWeatherChange - { - [HarmonyPrefix] - public static bool DoPre(WeatherManager __instance, WeatherDef newWeather) - { - if (Network.state == ClientNetworkState.Disconnected) return true; - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return true; - if (OnlineActivityManager.onlineMap != __instance.map) return true; - - if (ClientValues.isRealTimeHost) - { - OnlineManagerHelper.EnqueueWeather(newWeather); - - OnlineActivityData onlineActivityData = new OnlineActivityData(); - onlineActivityData._stepMode = OnlineActivityStepMode.Weather; - onlineActivityData._weatherOrder = OnlineManagerHelper.CreateWeatherOrder(newWeather); - - Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), onlineActivityData); - Network.listener.EnqueuePacket(packet); - return true; - } - - else - { - //IF COMING FROM HOST - - if (OnlineActivityManager.queuedWeather == newWeather) - { - OnlineManagerHelper.ClearWeatherQueue(); - return true; - } - - //IF PLAYER ASKING FOR - - else return false; - } - } - } - - //Not really needed, used to make the non-host player console not freak out when trying to spawn non-requested things - - [HarmonyPatch(typeof(Pawn), nameof(Pawn.SpawnSetup))] - public static class PatchCreatePawn - { - [HarmonyPrefix] - public static bool DoPre(Map map, Thing __instance) - { - if (Network.state == ClientNetworkState.Disconnected) return true; - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return true; - if (OnlineActivityManager.onlineMap != map) return true; - - if (ClientValues.isRealTimeHost) return true; - else - { - //IF COMING FROM HOST - - if (OnlineActivityManager.queuedThing == __instance) return true; - - //IF PLAYER ASKING FOR - - else return false; - } - } - } - - [HarmonyPatch(typeof(Building), nameof(Building.SpawnSetup))] - public static class PatchCreateBuilding - { - [HarmonyPrefix] - public static bool DoPre(Map map, Thing __instance) - { - if (Network.state == ClientNetworkState.Disconnected) return true; - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return true; - if (OnlineActivityManager.onlineMap != map) return true; - - if (ClientValues.isRealTimeHost) return true; - else - { - //IF COMING FROM HOST - - if (OnlineActivityManager.queuedThing == __instance) return true; - - //IF PLAYER ASKING FOR - - else return false; - } - } - } - - [HarmonyPatch(typeof(Filth), nameof(Filth.SpawnSetup))] - public static class PatchCreateFilth - { - [HarmonyPrefix] - public static bool DoPre(Map map, Thing __instance) - { - if (Network.state == ClientNetworkState.Disconnected) return true; - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return true; - if (OnlineActivityManager.onlineMap != map) return true; - - if (ClientValues.isRealTimeHost) return true; - else - { - //IF COMING FROM HOST - - if (OnlineActivityManager.queuedThing == __instance) return true; - - //IF PLAYER ASKING FOR - - else return false; - } - } - } - - //[HarmonyPatch(typeof(Corpse), nameof(Corpse.SpawnSetup))] - //public static class PatchCreateCorpse - //{ - // [HarmonyPrefix] - // public static bool DoPre(Map map) - // { - // if (Network.state == NetworkState.Disconnected) return true; - // if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return true; - // if (OnlineActivityManager.onlineMap != map) return true; - - // if (ClientValues.isRealTimeHost) return false; - // else return false; - // } - //} - - //Patches to make online events finish correctly when getting out of the map - - [HarmonyPatch(typeof(CaravanExitMapUtility), nameof(CaravanExitMapUtility.ExitMapAndCreateCaravan), new[] { typeof(IEnumerable), typeof(Faction), typeof(int), typeof(Direction8Way), typeof(int), typeof(bool) })] - public static class PatchCaravanExitMap1 - { - [HarmonyPostfix] - public static void DoPost() - { - if (Network.state == ClientNetworkState.Disconnected) return; - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return; - - OnlineActivityManager.RequestStopOnlineActivity(); - } - } - - [HarmonyPatch(typeof(CaravanExitMapUtility), nameof(CaravanExitMapUtility.ExitMapAndCreateCaravan), new[] { typeof(IEnumerable), typeof(Faction), typeof(int), typeof(int), typeof(int), typeof(bool) })] - public static class PatchCaravanExitMap2 - { - [HarmonyPostfix] - public static void DoPost() - { - if (Network.state == ClientNetworkState.Disconnected) return; - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return; - - OnlineActivityManager.RequestStopOnlineActivity(); - } - } - - [HarmonyPatch(typeof(CaravanExitMapUtility), nameof(CaravanExitMapUtility.ExitMapAndJoinOrCreateCaravan))] - public static class PatchCaravanExitMap3 - { - [HarmonyPostfix] - public static void DoPost() - { - if (Network.state == ClientNetworkState.Disconnected) return; - if (SessionValues.currentRealTimeEvent == OnlineActivityType.None) return; - - OnlineActivityManager.RequestStopOnlineActivity(); } } } diff --git a/Source/Client/Values/SessionValues.cs b/Source/Client/Values/SessionValues.cs index 67c51887..b9380ae6 100644 --- a/Source/Client/Values/SessionValues.cs +++ b/Source/Client/Values/SessionValues.cs @@ -33,14 +33,14 @@ public static void SetValues(ServerGlobalData serverGlobalData) actionValues = serverGlobalData._actionValues; } - public static void ToggleOnlineFunction(OnlineActivityType type) { currentRealTimeEvent = type; } + public static void ToggleOnlineActivity(OnlineActivityType type) { currentRealTimeEvent = type; } - public static void ToggleOfflineFunction(OfflineActivityType type) { latestOfflineActivity = type; } + public static void ToggleOfflineActivity(OfflineActivityType type) { latestOfflineActivity = type; } public static void CleanValues() { - ToggleOnlineFunction(OnlineActivityType.None); - ToggleOfflineFunction(OfflineActivityType.None); + ToggleOnlineActivity(OnlineActivityType.None); + ToggleOfflineActivity(OfflineActivityType.None); chosenSettlement = null; chosenCaravan = null; diff --git a/Source/Server/Managers/ChatManager.cs b/Source/Server/Managers/ChatManager.cs index 129f3963..81f6cc46 100644 --- a/Source/Server/Managers/ChatManager.cs +++ b/Source/Server/Managers/ChatManager.cs @@ -143,27 +143,27 @@ public static class ChatCommandManager private static readonly ChatCommand helpCommand = new ChatCommand("/help", 0, "Shows a list of all available commands", - ChatHelpCommandAction); + HelpCommandAction); private static readonly ChatCommand toolsCommand = new ChatCommand("/tools", 0, "Shows a list of all available chat tools", - ChatToolsCommandAction); + ToolsCommandAction); private static readonly ChatCommand pingCommand = new ChatCommand("/ping", 0, "Checks if the connection to the server is working", - ChatPingCommandAction); + PingCommandAction); private static readonly ChatCommand disconnectCommand = new ChatCommand("/dc", 0, "Forcefully disconnects you from the server", - ChatDisconnectCommandAction); + DisconnectCommandAction); - private static readonly ChatCommand stopOnlineActivityCommand = new ChatCommand("/sv", 0, - "Forcefully disconnects you from a visit", - ChatStopOnlineActivityCommandAction); + private static readonly ChatCommand stopOnlineActivityCommand = new ChatCommand("/stopactivity", 0, + "Forcefully disconnects you from an activity", + StopOnlineActivityCommandAction); private static readonly ChatCommand privateMessage = new ChatCommand("/w", 0, "Sends a private message to a specific user", - ChatPrivateMessageCommandAction); + PrivateMessageCommandAction); public static readonly ChatCommand[] chatCommands = new ChatCommand[] { @@ -175,7 +175,7 @@ public static class ChatCommandManager privateMessage }; - private static void ChatHelpCommandAction() + private static void HelpCommandAction() { if (targetClient == null) return; else @@ -187,7 +187,7 @@ private static void ChatHelpCommandAction() } } - private static void ChatToolsCommandAction() + private static void ToolsCommandAction() { if (targetClient == null) return; else @@ -199,25 +199,25 @@ private static void ChatToolsCommandAction() } } - private static void ChatPingCommandAction() + private static void PingCommandAction() { if (targetClient == null) return; else ChatManager.SendSystemMessage(targetClient, "Pong!"); } - private static void ChatDisconnectCommandAction() + private static void DisconnectCommandAction() { if (targetClient == null) return; else targetClient.listener.disconnectFlag = true; } - private static void ChatStopOnlineActivityCommandAction() + private static void StopOnlineActivityCommandAction() { if (targetClient == null) return; - else OnlineActivityManager.SendVisitStop(targetClient); + else OnlineActivityManager.StopActivity(targetClient); } - private static void ChatPrivateMessageCommandAction() + private static void PrivateMessageCommandAction() { if (targetClient == null) return; else diff --git a/Source/Server/Managers/OnlineActivityManager.cs b/Source/Server/Managers/OnlineActivityManager.cs index 9f222300..6500a982 100644 --- a/Source/Server/Managers/OnlineActivityManager.cs +++ b/Source/Server/Managers/OnlineActivityManager.cs @@ -13,68 +13,32 @@ public static void ParseOnlineActivityPacket(ServerClient client, Packet packet) return; } - OnlineActivityData visitData = Serializer.ConvertBytesToObject(packet.contents); + OnlineActivityData data = Serializer.ConvertBytesToObject(packet.contents); - switch (visitData._stepMode) + switch (data._stepMode) { case OnlineActivityStepMode.Request: - SendVisitRequest(client, visitData); + RequestActivity(client, data); break; case OnlineActivityStepMode.Accept: - AcceptVisitRequest(client, visitData); + AcceptActivity(client, data); break; case OnlineActivityStepMode.Reject: - RejectVisitRequest(client, visitData); - break; - - case OnlineActivityStepMode.Action: - SendVisitActions(client, visitData); - break; - - case OnlineActivityStepMode.Create: - SendVisitActions(client, visitData); - break; - - case OnlineActivityStepMode.Destroy: - SendVisitActions(client, visitData); - break; - - case OnlineActivityStepMode.Damage: - SendVisitActions(client, visitData); - break; - - case OnlineActivityStepMode.Hediff: - SendVisitActions(client, visitData); - break; - - case OnlineActivityStepMode.TimeSpeed: - SendVisitActions(client, visitData); - break; - - case OnlineActivityStepMode.GameCondition: - SendVisitActions(client, visitData); - break; - - case OnlineActivityStepMode.Weather: - SendVisitActions(client, visitData); - break; - - case OnlineActivityStepMode.Kill: - SendVisitActions(client, visitData); + RejectActivity(client, data); break; case OnlineActivityStepMode.Stop: - SendVisitStop(client); + StopActivity(client); break; } } - private static void SendVisitRequest(ServerClient client, OnlineActivityData data) + private static void RequestActivity(ServerClient client, OnlineActivityData data) { SettlementFile settlementFile = SettlementManager.GetSettlementFileFromTile(data._toTile); - if (settlementFile == null) ResponseShortcutManager.SendIllegalPacket(client, $"Player {client.userFile.Username} tried to visit a settlement at tile {data._toTile}, but no settlement could be found"); + if (settlementFile == null) ResponseShortcutManager.SendIllegalPacket(client, $"Player {client.userFile.Username} tried to engage with settlement at tile {data._toTile}, but no settlement could be found"); else { ServerClient toGet = UserManagerHelper.GetConnectedClientFromUsername(settlementFile.Owner); @@ -87,7 +51,7 @@ private static void SendVisitRequest(ServerClient client, OnlineActivityData dat else { - if (toGet.inVisitWith != null) + if (toGet.activityPartner != null) { data._stepMode = OnlineActivityStepMode.Unavailable; Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), data); @@ -104,7 +68,7 @@ private static void SendVisitRequest(ServerClient client, OnlineActivityData dat } } - private static void AcceptVisitRequest(ServerClient client, OnlineActivityData data) + private static void AcceptActivity(ServerClient client, OnlineActivityData data) { SettlementFile settlementFile = SettlementManager.GetSettlementFileFromTile(data._fromTile); if (settlementFile == null) return; @@ -114,16 +78,17 @@ private static void AcceptVisitRequest(ServerClient client, OnlineActivityData d if (toGet == null) return; else { - client.inVisitWith = toGet; - toGet.inVisitWith = client; + client.activityPartner = toGet; + toGet.activityPartner = client; Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), data); + client.listener.EnqueuePacket(packet); toGet.listener.EnqueuePacket(packet); } } } - private static void RejectVisitRequest(ServerClient client, OnlineActivityData data) + private static void RejectActivity(ServerClient client, OnlineActivityData data) { SettlementFile settlementFile = SettlementManager.GetSettlementFileFromTile(data._fromTile); if (settlementFile == null) return; @@ -134,14 +99,15 @@ private static void RejectVisitRequest(ServerClient client, OnlineActivityData d else { Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), data); + client.listener.EnqueuePacket(packet); toGet.listener.EnqueuePacket(packet); } } } - private static void SendVisitActions(ServerClient client, OnlineActivityData data) + private static void SendActions(ServerClient client, OnlineActivityData data) { - if (client.inVisitWith == null) + if (client.activityPartner == null) { data._stepMode = OnlineActivityStepMode.Stop; Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), data); @@ -151,25 +117,25 @@ private static void SendVisitActions(ServerClient client, OnlineActivityData dat else { Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), data); - client.inVisitWith.listener.EnqueuePacket(packet); + client.activityPartner.listener.EnqueuePacket(packet); } } - public static void SendVisitStop(ServerClient client) + public static void StopActivity(ServerClient client) { - OnlineActivityData visitData = new OnlineActivityData(); - visitData._stepMode = OnlineActivityStepMode.Stop; + OnlineActivityData data = new OnlineActivityData(); + data._stepMode = OnlineActivityStepMode.Stop; - Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), visitData); - client.listener.EnqueuePacket(packet); + Packet packet = Packet.CreatePacketFromObject(nameof(PacketHandler.OnlineActivityPacket), data); - ServerClient otherPlayer = client.inVisitWith; - if (otherPlayer != null) + if (client.activityPartner != null) { - otherPlayer.listener.EnqueuePacket(packet); - otherPlayer.inVisitWith = null; - client.inVisitWith = null; + client.activityPartner.listener.EnqueuePacket(packet); + client.activityPartner.activityPartner = null; } + + client.listener.EnqueuePacket(packet); + client.activityPartner = null; } } } diff --git a/Source/Server/Network/Clients/ServerClient.cs b/Source/Server/Network/Clients/ServerClient.cs index c311d8d5..c57b4986 100644 --- a/Source/Server/Network/Clients/ServerClient.cs +++ b/Source/Server/Network/Clients/ServerClient.cs @@ -16,7 +16,7 @@ public class ServerClient [NonSerialized] public Listener listener; - [NonSerialized] public ServerClient inVisitWith; + [NonSerialized] public ServerClient activityPartner; public ServerClient(TcpClient tcp) { diff --git a/Source/Server/Network/Listener.cs b/Source/Server/Network/Listener.cs index 21c4904c..0179c200 100644 --- a/Source/Server/Network/Listener.cs +++ b/Source/Server/Network/Listener.cs @@ -150,7 +150,7 @@ public void DestroyConnection() connection.Close(); uploadManager?.fileStream.Close(); downloadManager?.fileStream.Close(); - if (targetClient.inVisitWith != null) OnlineActivityManager.SendVisitStop(targetClient); + if (targetClient.activityPartner != null) OnlineActivityManager.StopActivity(targetClient); } } } diff --git a/Source/Shared/Misc/CommonEnumerators.cs b/Source/Shared/Misc/CommonEnumerators.cs index 6b1b6cd6..37fa95b3 100644 --- a/Source/Shared/Misc/CommonEnumerators.cs +++ b/Source/Shared/Misc/CommonEnumerators.cs @@ -36,7 +36,7 @@ public enum TransferStepMode { TradeRequest, TradeAccept, TradeReject, TradeReRe public enum OfflineActivityStepMode { Request, Deny, Unavailable } - public enum OnlineActivityStepMode { Request, Accept, Reject, Unavailable, Action, Create, Destroy, Damage, Hediff, Kill, TimeSpeed, GameCondition, Weather, Stop } + public enum OnlineActivityStepMode { Request, Accept, Reject, Unavailable, Stop } public enum OnlineActivityTargetFaction { Faction, NonFaction, None } diff --git a/Source/Shared/PacketData/OnlineActivityData.cs b/Source/Shared/PacketData/OnlineActivityData.cs index 09c0fb09..f2033451 100644 --- a/Source/Shared/PacketData/OnlineActivityData.cs +++ b/Source/Shared/PacketData/OnlineActivityData.cs @@ -13,15 +13,11 @@ public class OnlineActivityData //Map - public MapFile _mapData; + public MapFile _mapFile; - public List _mapHumans = new List(); + public HumanFile[] _guestHumans = new HumanFile[0]; - public List _mapAnimals = new List(); - - public List _caravanHumans = new List(); - - public List _caravanAnimals = new List(); + public AnimalFile[] _guestAnimals = new AnimalFile[0]; //Misc