public override void LoadData() { Logger.WriteLog("Mod Version: " + ReleaseVersion); if (MyAPIGateway.Multiplayer.IsServer == false) { return; } //if(MyAPIGateway.Utilities.GamePaths.ModScopeName.StartsWith("RivalAI (Unstable)")) Instance = this; foreach (var mod in MyAPIGateway.Session.Mods) { if (mod.PublishedFileId == ShieldModId) { Logger.WriteLog("Defense Shield Mod Detected"); ShieldMod = true; continue; } if (mod.PublishedFileId == WeaponCoreModId || mod.Name.Contains("WeaponCore-Local")) { Logger.WriteLog("WeaponCore Mod Detected"); WeaponCoreMod = true; } } MESApi.RegisterAPIListener(); }
public override void LoadData() { if (MyAPIGateway.Multiplayer.IsServer == false) { return; } Instance = this; foreach (var mod in MyAPIGateway.Session.Mods) { if (mod.PublishedFileId == ShieldModId) { Logger.WriteLog("Defense Shield Mod Detected"); ShieldMod = true; continue; } if (mod.PublishedFileId == WeaponCoreModId || mod.Name.Contains("WeaponCore-Local")) { Logger.WriteLog("WeaponCore Mod Detected"); WeaponCoreMod = true; } } MESApi.RegisterAPIListener(); }
protected override void UnloadData() { if (ShieldApiLoaded) { SApi.Unload(); } if (WeaponCoreLoaded) { WeaponCore.Unload(); } if (MESApi.MESApiReady) { MESApi.UnregisterListener(); } if (WaterMod.Registered) { WaterMod.Unregister(); WaterMod.OnRegisteredEvent -= WaterLogged; WaterMod.WaterCreatedEvent -= WaterHelper.WaterAdded; WaterMod.WaterRemovedEvent -= WaterHelper.WaterRemoved; } DebugTerminalControls.RegisterControls(false); Instance = null; SyncManager.Close(); DamageHelper.UnregisterEntityWatchers(); BehaviorManager.Behaviors.Clear(); EntityWatcher.UnregisterWatcher(); }
//------------------------------------------------------------------------ //----------------END INTERFACE METHODS----------------------------------- //------------------------------------------------------------------------ public virtual void MainBehavior() { if (!_registeredRemoteCode) { _registeredRemoteCode = true; if (MESApi.MESApiReady && !string.IsNullOrWhiteSpace(RemoteControlCode)) { MESApi.RegisterRemoteControlCode(this.RemoteControl, RemoteControlCode); } } if (!_despawnTriggersRegistered) { _despawnTriggersRegistered = true; foreach (var trigger in Trigger.Triggers) { if (!MESApi.MESApiReady) { break; } if (trigger.Type == "DespawnMES") { MESApi.RegisterDespawnWatcher(this.RemoteControl?.SlimBlock?.CubeGrid, Trigger.DespawnFromMES); break; } } } }
protected override void UnloadData() { if (ShieldApiLoaded) { SApi.Unload(); } if (WeaponCoreLoaded) { WeaponCore.Unload(); } if (MESApi.MESApiReady) { MESApi.UnregisterListener(); } Instance = null; SyncManager.Close(); DamageHelper.UnregisterEntityWatchers(); BehaviorManager.Behaviors.Clear(); EntityWatcher.UnregisterWatcher(); }
public bool AreConditionsMets() { if (!_gotWatchedBlocks) { SetupWatchedBlocks(); } if (UseConditions == false) { return(true); } int usedConditions = 0; int satisfiedConditions = 0; if (_behavior == null) { _behavior = BehaviorManager.GetBehavior(_remoteControl); if (_behavior == null) { return(false); } } if (CheckAllLoadedModIDs == true) { usedConditions++; bool missingMod = false; foreach (var mod in AllModIDsToCheck) { if (Utilities.ModIDs.Contains(mod) == false) { Logger.MsgDebug(ProfileSubtypeId + ": Mod ID Not Present", DebugTypeEnum.Condition); missingMod = true; break; } } if (!missingMod) { satisfiedConditions++; } } if (CheckAnyLoadedModIDs == true) { usedConditions++; foreach (var mod in AllModIDsToCheck) { if (Utilities.ModIDs.Contains(mod)) { Logger.MsgDebug(ProfileSubtypeId + ": A Mod ID was Found: " + mod.ToString(), DebugTypeEnum.Condition); satisfiedConditions++; break; } } } if (CheckTrueBooleans == true) { usedConditions++; bool failedCheck = false; foreach (var boolName in TrueBooleans) { if (!_settings.GetCustomBoolResult(boolName)) { Logger.MsgDebug(ProfileSubtypeId + ": Boolean Not True: " + boolName, DebugTypeEnum.Condition); failedCheck = true; break; } } if (!failedCheck) { satisfiedConditions++; } } if (CheckCustomCounters == true) { usedConditions++; bool failedCheck = false; if (CustomCounters.Count == CustomCountersTargets.Count) { for (int i = 0; i < CustomCounters.Count; i++) { try { var compareType = CounterCompareEnum.GreaterOrEqual; if (i <= CounterCompareTypes.Count - 1) { compareType = CounterCompareTypes[i]; } if (_settings.GetCustomCounterResult(CustomCounters[i], CustomCountersTargets[i], compareType) == false) { Logger.MsgDebug(ProfileSubtypeId + ": Counter Amount Condition Not Satisfied: " + CustomCounters[i], DebugTypeEnum.Condition); failedCheck = true; break; } } catch (Exception e) { Logger.MsgDebug("Exception: ", DebugTypeEnum.Condition); Logger.MsgDebug(e.ToString(), DebugTypeEnum.Condition); } } } else { Logger.MsgDebug(ProfileSubtypeId + ": Counter Names and Targets List Counts Don't Match. Check Your Condition Profile", DebugTypeEnum.Condition); failedCheck = true; } if (!failedCheck) { satisfiedConditions++; } } if (CheckTrueSandboxBooleans == true) { usedConditions++; bool failedCheck = false; for (int i = 0; i < TrueSandboxBooleans.Count; i++) { try { bool output = false; var result = MyAPIGateway.Utilities.GetVariable(TrueSandboxBooleans[i], out output); if (!result || !output) { Logger.MsgDebug(ProfileSubtypeId + ": Sandbox Boolean False: " + TrueSandboxBooleans[i], DebugTypeEnum.Condition); failedCheck = true; break; } } catch (Exception e) { Logger.MsgDebug("Exception: ", DebugTypeEnum.Condition); Logger.MsgDebug(e.ToString(), DebugTypeEnum.Condition); } } if (!failedCheck) { satisfiedConditions++; } } if (CheckCustomSandboxCounters == true) { usedConditions++; bool failedCheck = false; if (CustomSandboxCounters.Count == CustomSandboxCountersTargets.Count) { for (int i = 0; i < CustomSandboxCounters.Count; i++) { try { int counter = 0; var result = MyAPIGateway.Utilities.GetVariable(CustomSandboxCounters[i], out counter); var compareType = CounterCompareEnum.GreaterOrEqual; if (i <= SandboxCounterCompareTypes.Count - 1) { compareType = SandboxCounterCompareTypes[i]; } bool counterResult = false; if (compareType == CounterCompareEnum.GreaterOrEqual) { counterResult = (counter >= CustomSandboxCountersTargets[i]); } if (compareType == CounterCompareEnum.Greater) { counterResult = (counter > CustomSandboxCountersTargets[i]); } if (compareType == CounterCompareEnum.Equal) { counterResult = (counter == CustomSandboxCountersTargets[i]); } if (compareType == CounterCompareEnum.NotEqual) { counterResult = (counter != CustomSandboxCountersTargets[i]); } if (compareType == CounterCompareEnum.Less) { counterResult = (counter < CustomSandboxCountersTargets[i]); } if (compareType == CounterCompareEnum.LessOrEqual) { counterResult = (counter <= CustomSandboxCountersTargets[i]); } if (!result || !counterResult) { Logger.MsgDebug(ProfileSubtypeId + ": Sandbox Counter Amount Condition Not Satisfied: " + CustomSandboxCounters[i], DebugTypeEnum.Condition); failedCheck = true; break; } } catch (Exception e) { Logger.MsgDebug("Exception: ", DebugTypeEnum.Condition); Logger.MsgDebug(e.ToString(), DebugTypeEnum.Condition); } } } else { Logger.MsgDebug(ProfileSubtypeId + ": Sandbox Counter Names and Targets List Counts Don't Match. Check Your Condition Profile", DebugTypeEnum.Condition); failedCheck = true; } if (!failedCheck) { satisfiedConditions++; } } if (CheckGridSpeed == true) { usedConditions++; float speed = (float)_remoteControl.GetShipSpeed(); if ((MinGridSpeed == -1 || speed >= MinGridSpeed) && (MaxGridSpeed == -1 || speed <= MaxGridSpeed)) { Logger.MsgDebug(ProfileSubtypeId + ": Grid Speed High Enough", DebugTypeEnum.Condition); satisfiedConditions++; } else { Logger.MsgDebug(ProfileSubtypeId + ": Grid Speed Not High Enough", DebugTypeEnum.Condition); } } if (MESApi.MESApiReady && CheckMESBlacklistedSpawnGroups) { var blackList = MESApi.GetSpawnGroupBlackList(); if (SpawnGroupBlacklistContainsAll.Count > 0) { usedConditions++; bool failedCheck = false; foreach (var group in SpawnGroupBlacklistContainsAll) { if (blackList.Contains(group) == false) { Logger.MsgDebug(ProfileSubtypeId + ": A Spawngroup was not on MES BlackList: " + group, DebugTypeEnum.Condition); failedCheck = true; break; } } if (!failedCheck) { satisfiedConditions++; } } if (SpawnGroupBlacklistContainsAny.Count > 0) { usedConditions++; foreach (var group in SpawnGroupBlacklistContainsAll) { if (blackList.Contains(group)) { Logger.MsgDebug(ProfileSubtypeId + ": A Spawngroup was on MES BlackList: " + group, DebugTypeEnum.Condition); satisfiedConditions++; break; } } } } if (UseAccumulatedDamageWatcher) { usedConditions++; bool failedCheck = false; if (MinAccumulatedDamage >= 0 && MinAccumulatedDamage < _settings.TotalDamageAccumulated) { failedCheck = true; } if (MaxAccumulatedDamage >= 0 && MaxAccumulatedDamage > _settings.TotalDamageAccumulated) { failedCheck = true; } if (!failedCheck) { satisfiedConditions++; } } if (UseRequiredFunctionalBlocks) { if (_watchingAllBlocks) { usedConditions++; if (_watchedAllBlocksResult) { satisfiedConditions++; } } if (_watchingAnyBlocks) { usedConditions++; if (_watchedAnyBlocksResult) { satisfiedConditions++; } } if (_watchingNoneBlocks) { usedConditions++; if (_watchedNoneBlocksResult) { satisfiedConditions++; } } } if (CheckTargetAltitudeDifference) { usedConditions++; if (_behavior.AutoPilot.Targeting.HasTarget() && _behavior.AutoPilot.InGravity()) { var planetPos = _behavior.AutoPilot.CurrentPlanet.PositionComp.WorldAABB.Center; var targetCoreDist = _behavior.AutoPilot.Targeting.Target.Distance(planetPos); var myCoreDist = Vector3D.Distance(planetPos, _remoteControl.GetPosition()); var difference = targetCoreDist - myCoreDist; if (difference >= this.MinTargetAltitudeDifference && difference <= this.MaxTargetAltitudeDifference) { satisfiedConditions++; } } } if (CheckTargetDistance) { usedConditions++; if (_behavior.AutoPilot.Targeting.HasTarget()) { var dist = _behavior.AutoPilot.Targeting.Target.Distance(_remoteControl.GetPosition()); if ((this.MinTargetDistance == -1 || dist >= this.MinTargetDistance) && (this.MaxTargetDistance == -1 || dist <= this.MaxTargetDistance)) { satisfiedConditions++; } } } if (CheckTargetAngleFromForward) { usedConditions++; if (_behavior.AutoPilot.Targeting.HasTarget()) { var dirToTarget = Vector3D.Normalize(_behavior.AutoPilot.Targeting.GetTargetCoords() - _remoteControl.GetPosition()); var myForward = _behavior.AutoPilot.RefBlockMatrixRotation.Forward; var angle = VectorHelper.GetAngleBetweenDirections(dirToTarget, myForward); if ((this.MinTargetAngle == -1 || angle >= this.MinTargetAngle) && (this.MaxTargetAngle == -1 || angle <= this.MaxTargetAngle)) { satisfiedConditions++; } } } if (CheckIfTargetIsChasing) { usedConditions++; if (_behavior.AutoPilot.Targeting.HasTarget()) { var dirFromTarget = Vector3D.Normalize(_remoteControl.GetPosition() - _behavior.AutoPilot.Targeting.GetTargetCoords()); var targetVelocity = Vector3D.Normalize(_behavior.AutoPilot.Targeting.Target.CurrentVelocity()); if (targetVelocity.IsValid() && targetVelocity.Length() > 0) { var angle = VectorHelper.GetAngleBetweenDirections(dirFromTarget, targetVelocity); if ((this.MinTargetChaseAngle == -1 || angle >= this.MinTargetChaseAngle) && (this.MaxTargetChaseAngle == -1 || angle <= this.MaxTargetChaseAngle)) { satisfiedConditions++; } } } } if (CheckIfGridNameMatches) { usedConditions++; if (!string.IsNullOrWhiteSpace(_remoteControl.SlimBlock.CubeGrid.CustomName)) { bool pass = false; foreach (var name in GridNamesToCheck) { if (AllowPartialGridNameMatches) { if (_remoteControl.SlimBlock.CubeGrid.CustomName.Contains(name)) { pass = true; } } else { if (_remoteControl.SlimBlock.CubeGrid.CustomName == name) { pass = true; } } } if (pass) { satisfiedConditions++; } } } if (UnderwaterCheck) { usedConditions++; if (WaterHelper.UnderwaterAndDepthCheck(_remoteControl.GetPosition(), _behavior.AutoPilot.CurrentWater, IsUnderwater, MinDistanceUnderwater, MaxDistanceUnderwater)) { satisfiedConditions++; } } if (TargetUnderwaterCheck) { usedConditions++; if (WaterHelper.UnderwaterAndDepthCheck(_remoteControl.GetPosition(), _behavior.AutoPilot.CurrentWater, TargetIsUnderwater, MinTargetDistanceUnderwater, MaxTargetDistanceUnderwater)) { satisfiedConditions++; } } if (BehaviorModeCheck) { usedConditions++; if (_behavior.Mode == CurrentBehaviorMode) { satisfiedConditions++; } } if (MatchAnyCondition == false) { bool result = satisfiedConditions >= usedConditions; Logger.MsgDebug(ProfileSubtypeId + ": All Condition Satisfied: " + result.ToString(), DebugTypeEnum.Condition); Logger.MsgDebug(string.Format("Used Conditions: {0} // Satisfied Conditions: {1}", usedConditions, satisfiedConditions), DebugTypeEnum.Condition); return(result); } else { bool result = satisfiedConditions > 0; Logger.MsgDebug(ProfileSubtypeId + ": Any Condition(s) Satisfied: " + result.ToString(), DebugTypeEnum.Condition); Logger.MsgDebug(string.Format("Used Conditions: {0} // Satisfied Conditions: {1}", usedConditions, satisfiedConditions), DebugTypeEnum.Condition); return(result); } }
//A: Found Target (Approach) //B: Lost Target (Still Approach) //C: Lost Target (Go To Despawn) //D: Engage Target //E: Engage In Range //F: Engage Out Range public override void MainBehavior() { if (RAI_SessionCore.IsServer == false) { return; } base.MainBehavior(); //Logger.MsgDebug(Mode.ToString(), DebugTypeEnum.General); if (Mode != BehaviorMode.Retreat && Despawn.DoRetreat == true) { ChangeCoreBehaviorMode(BehaviorMode.Retreat); AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.RotateToWaypoint | NewAutoPilotMode.ThrustForward | NewAutoPilotMode.PlanetaryPathing | AutoPilot.UserCustomMode); } if (Mode == BehaviorMode.Init) { if (Settings.DespawnCoords == Vector3D.Zero) { Settings.DespawnCoords = MESApi.GetDespawnCoords(RemoteControl.SlimBlock.CubeGrid); if (Settings.DespawnCoords == Vector3D.Zero) { Settings.DespawnCoords = AutoPilot.CalculateDespawnCoords(this.RemoteControl.GetPosition()); } } ReturnToDespawn(); } if (BehaviorActionA && Mode != BehaviorMode.EngageTarget) { //Logger.MsgDebug("Hunter BehaviorActionA Triggered", DebugTypeEnum.General); BehaviorActionA = false; if (Settings.LastDamagerEntity != 0) { //Logger.MsgDebug("Damager Entity Id Valid" + Settings.LastDamagerEntity.ToString(), DebugTypeEnum.General); IMyEntity tempEntity = null; if (MyAPIGateway.Entities.TryGetEntityById(Settings.LastDamagerEntity, out tempEntity)) { //Logger.MsgDebug("Damager Entity Valid", DebugTypeEnum.General); var parentEnt = tempEntity.GetTopMostParent(); if (parentEnt != null) { //Logger.MsgDebug("Damager Parent Entity Valid", DebugTypeEnum.General); var gridGroup = MyAPIGateway.GridGroups.GetGroup(RemoteControl.SlimBlock.CubeGrid, GridLinkTypeEnum.Physical); bool isSameGridConstrust = false; foreach (var grid in gridGroup) { if (grid.EntityId == tempEntity.GetTopMostParent().EntityId) { //Logger.MsgDebug("Damager Parent Entity Was Same Grid", DebugTypeEnum.General); isSameGridConstrust = true; break; } } if (!isSameGridConstrust) { //Logger.MsgDebug("Damager Parent Entity Was External", DebugTypeEnum.General); AutoPilot.Targeting.ForceTargetEntityId = parentEnt.EntityId; AutoPilot.Targeting.ForceTargetEntity = parentEnt; AutoPilot.Targeting.ForceRefresh = true; AutoPilot.SetAutoPilotDataMode(AutoPilotDataMode.Secondary); AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.RotateToWaypoint | NewAutoPilotMode.ThrustForward | NewAutoPilotMode.PlanetaryPathing | NewAutoPilotMode.WaypointFromTarget | AutoPilot.UserCustomMode); ChangeCoreBehaviorMode(BehaviorMode.ApproachTarget); Logger.MsgDebug("Hunter Approaching Potential Target From Damage", DebugTypeEnum.BehaviorSpecific); return; } } } } } if (Mode == BehaviorMode.ApproachWaypoint) { var time = MyAPIGateway.Session.GameDateTime - _checkActiveTargetTimer; if (time.TotalSeconds > TimeBetweenNewTargetChecks) { _checkActiveTargetTimer = MyAPIGateway.Session.GameDateTime; if (AutoPilot.Targeting.HasTarget()) { ChangeCoreBehaviorMode(BehaviorMode.ApproachTarget); _lostTargetTimer = MyAPIGateway.Session.GameDateTime; BehaviorTriggerA = true; AutoPilot.SetAutoPilotDataMode(AutoPilotDataMode.Secondary); AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.RotateToWaypoint | NewAutoPilotMode.ThrustForward | NewAutoPilotMode.PlanetaryPathing | NewAutoPilotMode.WaypointFromTarget | AutoPilot.UserCustomMode); Logger.MsgDebug("Hunter Approaching Potential Target", DebugTypeEnum.BehaviorSpecific); } } } if (Mode == BehaviorMode.ApproachTarget) { if (!AutoPilot.Targeting.HasTarget()) { AutoPilot.SetInitialWaypoint(AutoPilot.Targeting.TargetLastKnownCoords); var time = MyAPIGateway.Session.GameDateTime - _lostTargetTimer; if (time.TotalSeconds > LostTargetTimerTrigger) { Logger.MsgDebug("Hunter Returning To Despawn", DebugTypeEnum.BehaviorSpecific); ReturnToDespawn(); return; } return; } _lostTargetTimer = MyAPIGateway.Session.GameDateTime; bool engageTarget = false; var targetDist = Vector3D.Distance(RemoteControl.GetPosition(), AutoPilot.Targeting.TargetLastKnownCoords); //Check Turret if (EngageOnWeaponActivation == true) { if (AutoPilot.Weapons.GetTurretTarget() != 0) { Logger.MsgDebug("Hunter Turrets Detected Target", DebugTypeEnum.BehaviorSpecific); engageTarget = true; } } //Check Visual Range if (!engageTarget && EngageOnCameraDetection && targetDist < CameraDetectionMaxRange) { if (Grid.RaycastGridCheck(AutoPilot.Targeting.TargetLastKnownCoords)) { Logger.MsgDebug("Hunter Raycast Target Success", DebugTypeEnum.BehaviorSpecific); } engageTarget = true; } //Check Collision Data if (!engageTarget && EngageOnTargetLineOfSight && AutoPilot.Targeting.Data.MaxLineOfSight > 0 && AutoPilot.Collision.TargetResult.HasTarget(AutoPilot.Targeting.Data.MaxLineOfSight)) { if (AutoPilot.Targeting.Target.GetParentEntity().EntityId == AutoPilot.Collision.TargetResult.GetCollisionEntity().EntityId) { Logger.MsgDebug("Hunter Has Line of Sight to Target", DebugTypeEnum.BehaviorSpecific); engageTarget = true; } } if (engageTarget) { Logger.MsgDebug("Hunter Engaging Target", DebugTypeEnum.BehaviorSpecific); BehaviorTriggerD = true; ChangeCoreBehaviorMode(BehaviorMode.EngageTarget); } } //Engage if (Mode == BehaviorMode.EngageTarget) { if (AutoPilot.Targeting.HasTarget()) { var targetDist = Vector3D.Distance(RemoteControl.GetPosition(), AutoPilot.Targeting.TargetLastKnownCoords); if (!_inRange) { if (targetDist < (AutoPilot.InGravity() ? AutoPilot.Data.EngageDistancePlanet : AutoPilot.Data.EngageDistanceSpace)) { Logger.MsgDebug("Hunter Within Engage Range", DebugTypeEnum.BehaviorSpecific); _inRange = true; BehaviorTriggerE = true; AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.RotateToWaypoint | NewAutoPilotMode.Strafe | NewAutoPilotMode.WaypointFromTarget | AutoPilot.UserCustomMode); } } else { if (targetDist > (AutoPilot.InGravity() ? AutoPilot.Data.DisengageDistancePlanet : AutoPilot.Data.DisengageDistanceSpace)) { Logger.MsgDebug("Hunter Outside Engage Range", DebugTypeEnum.BehaviorSpecific); _inRange = false; BehaviorTriggerF = true; AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.RotateToWaypoint | NewAutoPilotMode.ThrustForward | NewAutoPilotMode.PlanetaryPathing | NewAutoPilotMode.WaypointFromTarget | AutoPilot.UserCustomMode); } } } else { Logger.MsgDebug("Hunter Lost Target While Engaging", DebugTypeEnum.BehaviorSpecific); BehaviorTriggerB = true; _inRange = false; AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.RotateToWaypoint | NewAutoPilotMode.ThrustForward | NewAutoPilotMode.PlanetaryPathing | NewAutoPilotMode.WaypointFromTarget | AutoPilot.UserCustomMode); ChangeCoreBehaviorMode(BehaviorMode.ApproachTarget); } } //Retreat if (Mode == BehaviorMode.Retreat) { if (Despawn.NearestPlayer?.Controller?.ControlledEntity?.Entity != null) { //Logger.AddMsg("DespawnCoordsCreated", true); AutoPilot.SetInitialWaypoint(VectorHelper.GetDirectionAwayFromTarget(this.RemoteControl.GetPosition(), Despawn.NearestPlayer.GetPosition()) * 1000 + this.RemoteControl.GetPosition()); } } }
public bool EvaluateTarget(ITarget target, TargetProfile data, bool skipExpensiveChecks = false) { if (target == null) { Logger.MsgDebug("Target Is Null, Cannot Evaluate", DebugTypeEnum.TargetEvaluation); return(false); } if (!target.ActiveEntity()) { Logger.MsgDebug("Target Invalid, Cannot Evaluate", DebugTypeEnum.TargetEvaluation); return(false); } Logger.MsgDebug(string.Format(" - Evaluating Target: {0} using profile {1}", target.Name(), data.ProfileSubtypeId), DebugTypeEnum.TargetEvaluation); if (!data.BuiltUniqueFilterList) { foreach (var filter in data.MatchAllFilters) { if (!data.AllUniqueFilters.Contains(filter)) { data.AllUniqueFilters.Add(filter); } } foreach (var filter in data.MatchAnyFilters) { if (!data.AllUniqueFilters.Contains(filter)) { data.AllUniqueFilters.Add(filter); } } foreach (var filter in data.MatchNoneFilters) { if (!data.AllUniqueFilters.Contains(filter)) { data.AllUniqueFilters.Add(filter); } } data.BuiltUniqueFilterList = true; } List <TargetFilterEnum> FilterHits = new List <TargetFilterEnum>(); //Distance var distance = target.Distance(RemoteControl.GetPosition()); if (distance > data.MaxDistance) { return(false); } //Altitude if (data.AllUniqueFilters.Contains(TargetFilterEnum.Altitude)) { var altitude = target.CurrentAltitude(); if (altitude == -1000000 || (altitude >= data.MinAltitude && altitude <= data.MaxAltitude)) { FilterHits.Add(TargetFilterEnum.Altitude); } Logger.MsgDebug(string.Format(" - Evaluated Altitude: {0}", altitude), DebugTypeEnum.TargetEvaluation); } //Broadcasting if (data.AllUniqueFilters.Contains(TargetFilterEnum.Broadcasting)) { var range = target.BroadcastRange(data.BroadcastOnlyAntenna); if (range > distance || distance < data.NonBroadcastVisualRange) { FilterHits.Add(TargetFilterEnum.Broadcasting); } Logger.MsgDebug(string.Format(" - Evaluated Broadcast Range vs Distance: {0} / {1}", range, distance), DebugTypeEnum.TargetEvaluation); } //Faction if (data.AllUniqueFilters.Contains(TargetFilterEnum.Faction)) { var faction = target.FactionOwner() ?? ""; if (data.PrioritizeSpecifiedFactions || data.FactionTargets.Contains(faction)) { FilterHits.Add(TargetFilterEnum.Faction); } Logger.MsgDebug(string.Format(" - Evaluated Faction: {0}", faction), DebugTypeEnum.TargetEvaluation); } //Gravity if (data.AllUniqueFilters.Contains(TargetFilterEnum.Gravity)) { var gravity = target.CurrentGravity(); if (gravity >= data.MinGravity && gravity <= data.MaxGravity) { FilterHits.Add(TargetFilterEnum.Gravity); } Logger.MsgDebug(string.Format(" - Evaluated Gravity: {0}", gravity), DebugTypeEnum.TargetEvaluation); } //LineOfSight if (!skipExpensiveChecks && data.AllUniqueFilters.Contains(TargetFilterEnum.LineOfSight) && _behavior.AutoPilot.Collision.TargetResult.HasTarget()) { bool targetMatch = (target.GetParentEntity().EntityId == _behavior.AutoPilot.Collision.TargetResult.GetCollisionEntity().EntityId); if (targetMatch) { FilterHits.Add(TargetFilterEnum.MovementScore); } } //MovementScore if (data.AllUniqueFilters.Contains(TargetFilterEnum.MovementScore)) { if (distance < data.MaxMovementDetectableDistance || data.MaxMovementDetectableDistance < 0) { var score = target.MovementScore(); if ((data.MinMovementScore == -1 || score >= data.MinMovementScore) && (data.MaxMovementScore == -1 || score <= data.MaxMovementScore)) { FilterHits.Add(TargetFilterEnum.MovementScore); } } } //Name if (data.AllUniqueFilters.Contains(TargetFilterEnum.Name)) { var name = target.Name(); string successName = "N/A"; foreach (var allowedName in data.Names) { if (string.IsNullOrWhiteSpace(allowedName)) { continue; } if (data.UsePartialNameMatching) { if (name.Contains(allowedName)) { successName = allowedName; break; } } else { if (name == allowedName) { successName = allowedName; break; } } } if (successName != "N/A") { FilterHits.Add(TargetFilterEnum.Name); } Logger.MsgDebug(string.Format(" - Evaluated Name: {0} // {1}", name, successName), DebugTypeEnum.TargetEvaluation); } //OutsideOfSafezone if (data.AllUniqueFilters.Contains(TargetFilterEnum.OutsideOfSafezone)) { bool inZone = target.InSafeZone(); if (!inZone) { FilterHits.Add(TargetFilterEnum.OutsideOfSafezone); } Logger.MsgDebug(string.Format(" - Evaluated Outside Safezone: {0}", !inZone), DebugTypeEnum.TargetEvaluation); } //Owner if (data.AllUniqueFilters.Contains(TargetFilterEnum.Owner)) { var owners = target.OwnerTypes(data.OnlyGetFromEntityOwner, data.GetFromMinorityGridOwners); bool gotRelation = false; var values = Enum.GetValues(typeof(OwnerTypeEnum)).Cast <OwnerTypeEnum>(); foreach (var ownerType in values) { if (ownerType == OwnerTypeEnum.None) { continue; } if (owners.HasFlag(ownerType) && data.Owners.HasFlag(ownerType)) { gotRelation = true; break; } } if (gotRelation) { FilterHits.Add(TargetFilterEnum.Owner); } Logger.MsgDebug(string.Format(" - Evaluated Owners: Required: {0}", data.Owners.ToString()), DebugTypeEnum.TargetEvaluation); Logger.MsgDebug(string.Format(" - Evaluated Owners: Found: {0}", owners.ToString()), DebugTypeEnum.TargetEvaluation); Logger.MsgDebug(string.Format(" - Evaluated Target Owners: {0} / Passed: {1}", owners.ToString(), gotRelation), DebugTypeEnum.TargetEvaluation); } //PlayerControlled if (data.AllUniqueFilters.Contains(TargetFilterEnum.PlayerControlled)) { var controlled = target.PlayerControlled(); if (data.PrioritizePlayerControlled || controlled) { FilterHits.Add(TargetFilterEnum.PlayerControlled); } Logger.MsgDebug(string.Format(" - Evaluated Player Controlled: {0}", controlled), DebugTypeEnum.TargetEvaluation); } //PlayerKnownLocation if (data.AllUniqueFilters.Contains(TargetFilterEnum.PlayerKnownLocation)) { bool inKnownLocation = false; if (MESApi.MESApiReady) { if (MESApi.IsPositionInKnownPlayerLocation(target.GetPosition(), true, string.IsNullOrWhiteSpace(data.PlayerKnownLocationFactionOverride) ? _behavior.Owner.Faction?.Tag : data.PlayerKnownLocationFactionOverride)) { ; } FilterHits.Add(TargetFilterEnum.PlayerKnownLocation); } Logger.MsgDebug(string.Format(" - Evaluated Player Known Location: {0}", inKnownLocation), DebugTypeEnum.TargetEvaluation); } //Powered if (data.AllUniqueFilters.Contains(TargetFilterEnum.Powered)) { bool powered = target.IsPowered(); if (powered) { FilterHits.Add(TargetFilterEnum.Powered); } Logger.MsgDebug(string.Format(" - Evaluated Power: {0}", powered), DebugTypeEnum.TargetEvaluation); } //Relation if (data.AllUniqueFilters.Contains(TargetFilterEnum.Relation)) { var relations = target.RelationTypes(RemoteControl.OwnerId, data.OnlyGetFromEntityOwner, data.GetFromMinorityGridOwners); bool gotRelation = false; var values = Enum.GetValues(typeof(RelationTypeEnum)).Cast <RelationTypeEnum>(); foreach (var relationType in values) { if (relationType == RelationTypeEnum.None) { continue; } if (relations.HasFlag(relationType) && data.Relations.HasFlag(relationType)) { gotRelation = true; break; } } if (gotRelation) { FilterHits.Add(TargetFilterEnum.Relation); } Logger.MsgDebug(string.Format(" - Evaluated Relations: Required: {0}", data.Relations.ToString()), DebugTypeEnum.TargetEvaluation); Logger.MsgDebug(string.Format(" - Evaluated Relations: Found: {0}", relations.ToString()), DebugTypeEnum.TargetEvaluation); Logger.MsgDebug(string.Format(" - Evaluated Relations: {0} / Passed: {1}", relations.ToString(), gotRelation), DebugTypeEnum.TargetEvaluation); } //Shielded if (data.AllUniqueFilters.Contains(TargetFilterEnum.Shielded)) { bool shielded = target.ProtectedByShields(); if (shielded) { FilterHits.Add(TargetFilterEnum.Shielded); } Logger.MsgDebug(string.Format(" - Evaluated Shields: {0}", shielded), DebugTypeEnum.TargetEvaluation); } //Speed if (data.AllUniqueFilters.Contains(TargetFilterEnum.Speed)) { var speed = target.CurrentSpeed(); if ((data.MinSpeed < 0 || speed >= data.MinSpeed) && (data.MaxSpeed < 0 || speed <= data.MaxSpeed)) { FilterHits.Add(TargetFilterEnum.Speed); } Logger.MsgDebug(string.Format(" - Evaluated Speed: {0}", speed), DebugTypeEnum.TargetEvaluation); } //Static if (data.IsStatic != CheckEnum.Ignore && data.AllUniqueFilters.Contains(TargetFilterEnum.Static)) { var staticGrid = target.IsStatic(); if ((staticGrid && data.IsStatic == CheckEnum.Yes) || (!staticGrid && data.IsStatic == CheckEnum.No)) { FilterHits.Add(TargetFilterEnum.Static); } Logger.MsgDebug(string.Format(" - Evaluated Static Grid: {0}", staticGrid), DebugTypeEnum.TargetEvaluation); } //TargetValue if (data.AllUniqueFilters.Contains(TargetFilterEnum.TargetValue)) { var targetValue = target.TargetValue(); if (targetValue >= data.MinTargetValue && targetValue <= data.MaxTargetValue) { FilterHits.Add(TargetFilterEnum.TargetValue); } Logger.MsgDebug(string.Format(" - Evaluated Target Value: {0}", targetValue), DebugTypeEnum.TargetEvaluation); } //Underwater if (data.AllUniqueFilters.Contains(TargetFilterEnum.Underwater)) { bool result = false; if (WaterHelper.Enabled) { result = WaterHelper.UnderwaterAndDepthCheck(target.GetPosition(), _behavior.AutoPilot.CurrentWater, true, Data.MinUnderWaterDepth, Data.MaxUnderWaterDepth); } if (result) { FilterHits.Add(TargetFilterEnum.Underwater); } Logger.MsgDebug(string.Format(" - Evaluated Underwater: {0}", result), DebugTypeEnum.TargetEvaluation); } //Any Conditions Check bool anyConditionPassed = false; if (data.MatchAnyFilters.Count > 0) { foreach (var filter in data.MatchAnyFilters) { if (FilterHits.Contains(filter)) { anyConditionPassed = true; break; } } } else { anyConditionPassed = true; } if (!anyConditionPassed) { Logger.MsgDebug(" - Evaluation Condition -Any- Failed", DebugTypeEnum.TargetEvaluation); return(false); } //All Condition Checks foreach (var filter in data.MatchAllFilters) { if (!FilterHits.Contains(filter)) { Logger.MsgDebug(" - Evaluation Condition -All- Failed", DebugTypeEnum.TargetEvaluation); return(false); } } //None Condition Checks foreach (var filter in data.MatchNoneFilters) { if (FilterHits.Contains(filter)) { Logger.MsgDebug(" - Evaluation Condition -None- Failed", DebugTypeEnum.TargetEvaluation); return(false); } } Logger.MsgDebug(" - Evaluation Passed", DebugTypeEnum.TargetEvaluation); TargetLastKnownCoords = target.GetPosition(); return(true); }
public void BroadcastRequest(ChatProfile chat) { string message = ""; string sound = ""; string avatar = ""; var broadcastType = BroadcastType.None; if (chat.ProcessChat(ref message, ref sound, ref broadcastType, ref avatar) == false) { Logger.MsgDebug(chat.ProfileSubtypeId + ": Process Chat Fail", DebugTypeEnum.Chat); return; } if (this.LastChatMessageSent == message || string.IsNullOrWhiteSpace(message) == true) { Logger.MsgDebug(chat.ProfileSubtypeId + ": Last Message Same", DebugTypeEnum.Chat); return; } if (chat.IgnoreAntennaRequirement || chat.SendToAllOnlinePlayers) { this.HighestRadius = chat.IgnoredAntennaRangeOverride; this.HighestAntennaRangeName = ""; this.AntennaCoords = this.RemoteControl.GetPosition(); } else { GetHighestAntennaRange(); if (this.HighestRadius == 0) { Logger.MsgDebug(chat.ProfileSubtypeId + ": No Valid Antenna", DebugTypeEnum.Chat); return; } } var playerList = new List <IMyPlayer>(); MyAPIGateway.Players.GetPlayers(playerList); Logger.MsgDebug(chat.ProfileSubtypeId + ": Sending Chat to all Players within distance: " + this.HighestRadius.ToString(), DebugTypeEnum.Chat); if (message.Contains("{AntennaName}")) { message = message.Replace("{AntennaName}", this.HighestAntennaRangeName); } if (this.RemoteControl?.SlimBlock?.CubeGrid?.CustomName != null && message.Contains("{GridName}")) { message = message.Replace("{GridName}", this.RemoteControl.SlimBlock.CubeGrid.CustomName); } if (chat.UseRandomNameGeneratorFromMES && MESApi.MESApiReady) { message = MESApi.ConvertRandomNamePatterns(message); } var authorName = chat.Author; if (authorName.Contains("{AntennaName}")) { authorName = authorName.Replace("{AntennaName}", this.HighestAntennaRangeName); } if (this.RemoteControl?.SlimBlock?.CubeGrid?.CustomName != null && authorName.Contains("{GridName}")) { authorName = authorName.Replace("{GridName}", this.RemoteControl.SlimBlock.CubeGrid.CustomName); } bool sentToAll = false; foreach (var player in playerList) { var playerId = chat.SendToAllOnlinePlayers ? 0 : player.IdentityId; var playerName = chat.SendToAllOnlinePlayers ? "Player" : player.DisplayName; if (!chat.SendToAllOnlinePlayers && (player.IsBot == true || player.Character == null)) { continue; } if (!chat.SendToAllOnlinePlayers && (Vector3D.Distance(player.GetPosition(), this.AntennaCoords) > this.HighestRadius)) { continue; //player too far } var modifiedMsg = message; if (modifiedMsg.Contains("{PlayerName}") == true) { modifiedMsg = modifiedMsg.Replace("{PlayerName}", playerName); } if (modifiedMsg.Contains("{PlayerFactionName}") == true) { var playerFaction = MyAPIGateway.Session.Factions.TryGetPlayerFaction(player.IdentityId); if (playerFaction != null) { modifiedMsg = modifiedMsg.Replace("{PlayerFactionName}", playerFaction.Name); } else { modifiedMsg = modifiedMsg.Replace("{PlayerFactionName}", "Unaffiliated"); } } var authorColor = chat.Color; if (authorColor != "White" && authorColor != "Red" && authorColor != "Green" && authorColor != "Blue") { authorColor = "White"; } if (!sentToAll) { if (broadcastType == BroadcastType.Chat || broadcastType == BroadcastType.Both) { MyVisualScriptLogicProvider.SendChatMessage(modifiedMsg, authorName, playerId, authorColor); } if (broadcastType == BroadcastType.Notify || broadcastType == BroadcastType.Both) { if (playerId == 0) { MyVisualScriptLogicProvider.ShowNotificationToAll(modifiedMsg, 6000, authorColor); } else { MyVisualScriptLogicProvider.ShowNotification(modifiedMsg, 6000, authorColor, playerId); } } } if (string.IsNullOrWhiteSpace(sound) == false && sound != "None") { var effect = new Effects(); effect.Mode = EffectSyncMode.PlayerSound; effect.SoundId = sound; effect.AvatarId = avatar; var sync = new SyncContainer(effect); SyncManager.SendSyncMesage(sync, player.SteamUserId); } if (playerId == 0) { sentToAll = true; } } }
public void ProcessTrigger(TriggerProfile trigger, long attackerEntityId = 0, bool skipOnComplete = false) { if (this.RemoteControl?.SlimBlock?.CubeGrid == null) { return; } if (trigger.Triggered == false || trigger.Actions == null) { return; } long detectedEntity = attackerEntityId; if (trigger.DetectedEntityId != 0 && detectedEntity == 0) { detectedEntity = trigger.DetectedEntityId; } trigger.DetectedEntityId = 0; trigger.Triggered = false; trigger.CooldownTime = trigger.Rnd.Next((int)trigger.MinCooldownMs, (int)trigger.MaxCooldownMs); trigger.LastTriggerTime = MyAPIGateway.Session.GameDateTime; trigger.TriggerCount++; Logger.MsgDebug(trigger.Actions.ProfileSubtypeId + ": Performing Eligible Actions", DebugTypeEnum.Action); //ChatBroadcast if (trigger.Actions.UseChatBroadcast == true) { Logger.MsgDebug(trigger.Actions.ProfileSubtypeId + ": Attempting Chat Broadcast", DebugTypeEnum.Action); _broadcast.BroadcastRequest(trigger.Actions.ChatData); } //BarrellRoll - Implement Post Release if (trigger.Actions.BarrelRoll == true) { //_autopilot.ChangeAutoPilotMode(AutoPilotMode.BarrelRoll); } //Strafe - Implement Post Release if (trigger.Actions.Strafe == true) { //_autopilot.ChangeAutoPilotMode(AutoPilotMode.Strafe); } //ChangeAutopilotSpeed if (trigger.Actions.ChangeAutopilotSpeed == true) { Logger.MsgDebug(trigger.Actions.ProfileSubtypeId + ": Changing AutoPilot Speed To: " + trigger.Actions.NewAutopilotSpeed.ToString(), DebugTypeEnum.Action); _autopilot.IdealMaxSpeed = trigger.Actions.NewAutopilotSpeed; var blockList = TargetHelper.GetAllBlocks(RemoteControl.SlimBlock.CubeGrid); foreach (var block in blockList.Where(x => x.FatBlock != null)) { var tBlock = block.FatBlock as IMyRemoteControl; if (tBlock != null) { tBlock.SpeedLimit = trigger.Actions.NewAutopilotSpeed; } } } //SpawnReinforcements if (trigger.Actions.SpawnEncounter == true && trigger.Actions.Spawner.UseSpawn) { Logger.MsgDebug(trigger.Actions.ProfileSubtypeId + ": Attempting Spawn", DebugTypeEnum.Spawn); if (trigger.Actions.Spawner.IsReadyToSpawn()) { //Logger.AddMsg("Do Spawn", true); trigger.Actions.Spawner.CurrentPositionMatrix = this.RemoteControl.WorldMatrix; trigger.Actions.Spawner.CurrentFactionTag = (trigger.Actions.Spawner.ForceSameFactionOwnership && !string.IsNullOrWhiteSpace(_owner.Faction?.Tag)) ? _owner.Faction.Tag : ""; SpawnHelper.SpawnRequest(trigger.Actions.Spawner); } } else { } //SelfDestruct if (trigger.Actions.SelfDestruct == true) { Logger.MsgDebug(trigger.Actions.ProfileSubtypeId + ": Attempting SelfDestruct", DebugTypeEnum.Action); var blockList = TargetHelper.GetAllBlocks(RemoteControl.SlimBlock.CubeGrid); int totalWarheads = 0; foreach (var block in blockList.Where(x => x.FatBlock != null)) { var tBlock = block.FatBlock as IMyWarhead; if (tBlock != null) { if (!trigger.Actions.StaggerWarheadDetonation) { tBlock.IsArmed = true; tBlock.DetonationTime = 0; tBlock.Detonate(); totalWarheads++; } else { tBlock.DetonationTime = totalWarheads + 1; tBlock.StartCountdown(); totalWarheads++; } } } //Logger.AddMsg("TotalBlocks: " + blockList.Count.ToString(), true); //Logger.AddMsg("TotalWarheads: " + totalWarheads.ToString(), true); //TODO: Shield EMP } //Retreat if (trigger.Actions.Retreat) { Logger.MsgDebug(trigger.Actions.ProfileSubtypeId + ": Attempting Retreat", DebugTypeEnum.Action); _despawn.Retreat(); } //ForceDespawn if (trigger.Actions.ForceDespawn) { _despawn.DespawnGrid(); } //TerminateBehavior if (trigger.Actions.TerminateBehavior) { Logger.MsgDebug(trigger.Actions.ProfileSubtypeId + ": Attempting Termination Of Behavior", DebugTypeEnum.Action); _autopilot.ActivateAutoPilot(AutoPilotType.None, NewAutoPilotMode.None, Vector3D.Zero); _behavior.BehaviorTerminated = true; } //BroadcastGenericCommand if (trigger.Actions.BroadcastGenericCommand == true) { Logger.MsgDebug(trigger.Actions.ProfileSubtypeId + ": Attempting Broadcast of Generic Command", DebugTypeEnum.Action); var antenna = BlockHelper.GetAntennaWithHighestRange(this.AntennaList); if (antenna != null) { CommandHelper.CommandTrigger?.Invoke(trigger.Actions.BroadcastSendCode, this.RemoteControl, (double)antenna.Radius, 0); } } //BroadcastCurrentTarget if (trigger.Actions.BroadcastCurrentTarget == true && detectedEntity != 0) { Logger.MsgDebug(trigger.Actions.ProfileSubtypeId + ": Attempting Broadcast of Current Target", DebugTypeEnum.Action); var antenna = BlockHelper.GetAntennaWithHighestRange(this.AntennaList); if (antenna != null) { CommandHelper.CommandTrigger?.Invoke(trigger.Actions.BroadcastSendCode, this.RemoteControl, (double)antenna.Radius, detectedEntity); } } //SwitchToReceivedTarget if (trigger.Actions.SwitchToReceivedTarget == true && detectedEntity != 0) { Logger.MsgDebug(trigger.Actions.ProfileSubtypeId + ": Attempting Switch to Received Target Data", DebugTypeEnum.Action); _autopilot.Targeting.ForceTargetEntity = detectedEntity; _autopilot.Targeting.ForceRefresh = true; } //SwitchToBehavior if (trigger.Actions.SwitchToBehavior == true) { _behavior.ChangeBehavior(trigger.Actions.NewBehavior, trigger.Actions.PreserveSettingsOnBehaviorSwitch, trigger.Actions.PreserveTriggersOnBehaviorSwitch, trigger.Actions.PreserveTargetDataOnBehaviorSwitch); } //RefreshTarget if (trigger.Actions.RefreshTarget == true) { Logger.MsgDebug(trigger.Actions.ProfileSubtypeId + ": Attempting Target Refresh", DebugTypeEnum.Action); _autopilot.Targeting.ForceRefresh = true; } //ChangeTargetProfile if (trigger.Actions.ChangeTargetProfile == true) { Logger.MsgDebug(trigger.Actions.ProfileSubtypeId + ": Attempting Target Change", DebugTypeEnum.Action); _autopilot.Targeting.UseNewTargetProfile = true; _autopilot.Targeting.NewTargetProfileName = trigger.Actions.NewTargetProfileId; } //ChangeReputationWithPlayers if (trigger.Actions.ChangeReputationWithPlayers == true) { Logger.MsgDebug(trigger.Actions.ProfileSubtypeId + ": Attempting Reputation Change With Players In Radius", DebugTypeEnum.Action); OwnershipHelper.ChangeReputationWithPlayersInRadius(this.RemoteControl, trigger.Actions.ReputationChangeRadius, trigger.Actions.ReputationChangeAmount, trigger.Actions.ReputationChangeFactions, trigger.Actions.ReputationChangesForAllRadiusPlayerFactionMembers); } //ChangeAttackerReputation if (trigger.Actions.ChangeAttackerReputation == true && detectedEntity != 0) { Logger.MsgDebug(trigger.Actions.ProfileSubtypeId + ": Attempting Reputation Change for Attacker", DebugTypeEnum.Action); OwnershipHelper.ChangeDamageOwnerReputation(trigger.Actions.ChangeAttackerReputationFaction, detectedEntity, trigger.Actions.ChangeAttackerReputationAmount, trigger.Actions.ReputationChangesForAllAttackPlayerFactionMembers); } //TriggerTimerBlock if (trigger.Actions.TriggerTimerBlocks == true) { Logger.MsgDebug(trigger.Actions.ProfileSubtypeId + ": Attempting Trigger of Timer Blocks", DebugTypeEnum.Action); var blockList = BlockHelper.GetBlocksWithNames(RemoteControl.SlimBlock.CubeGrid, trigger.Actions.TimerBlockNames); foreach (var block in blockList) { var tBlock = block as IMyTimerBlock; if (tBlock != null) { tBlock.Trigger(); } } } //ChangeBlockNames if (trigger.Actions.ChangeBlockNames) { BlockHelper.RenameBlocks(RemoteControl.CubeGrid, trigger.Actions.ChangeBlockNamesFrom, trigger.Actions.ChangeBlockNamesTo, trigger.Actions.ProfileSubtypeId); } //ChangeAntennaRanges if (trigger.Actions.ChangeAntennaRanges) { BlockHelper.SetGridAntennaRanges(AntennaList, trigger.Actions.AntennaNamesForRangeChange, trigger.Actions.AntennaRangeChangeType, trigger.Actions.AntennaRangeChangeAmount); } //ChangeAntennaOwnership if (trigger.Actions.ChangeAntennaOwnership == true) { Logger.MsgDebug(trigger.Actions.ProfileSubtypeId + ": Attempting Antenna Ownership Change", DebugTypeEnum.Action); OwnershipHelper.ChangeAntennaBlockOwnership(AntennaList, trigger.Actions.AntennaFactionOwner); } //CreateKnownPlayerArea if (trigger.Actions.CreateKnownPlayerArea == true) { Logger.MsgDebug(trigger.Actions.ProfileSubtypeId + ": Attempting Creation of Known Player Area in MES", DebugTypeEnum.Action); MESApi.AddKnownPlayerLocation(this.RemoteControl.GetPosition(), _owner.Faction?.Tag, trigger.Actions.KnownPlayerAreaRadius, trigger.Actions.KnownPlayerAreaTimer, trigger.Actions.KnownPlayerAreaMaxSpawns); } //DamageAttacker if (trigger.Actions.DamageToolAttacker == true && detectedEntity != 0) { Logger.MsgDebug(trigger.Actions.ProfileSubtypeId + ": Attempting Damage to Tool User", DebugTypeEnum.Action); DamageHelper.ApplyDamageToTarget(attackerEntityId, trigger.Actions.DamageToolAttackerAmount, trigger.Actions.DamageToolAttackerParticle, trigger.Actions.DamageToolAttackerSound); } //PlayParticleEffectAtRemote if (trigger.Actions.PlayParticleEffectAtRemote == true) { EffectManager.SendParticleEffectRequest(trigger.Actions.ParticleEffectId, this.RemoteControl.WorldMatrix, trigger.Actions.ParticleEffectOffset, trigger.Actions.ParticleEffectScale, trigger.Actions.ParticleEffectMaxTime, trigger.Actions.ParticleEffectColor); } //ResetCooldownTimeOfTriggers if (trigger.Actions.ResetCooldownTimeOfTriggers) { foreach (var resetTrigger in Triggers) { if (trigger.Actions.ResetTriggerCooldownNames.Contains(resetTrigger.ProfileSubtypeId)) { resetTrigger.LastTriggerTime = MyAPIGateway.Session.GameDateTime; } } foreach (var resetTrigger in DamageTriggers) { if (trigger.Actions.ResetTriggerCooldownNames.Contains(resetTrigger.ProfileSubtypeId)) { resetTrigger.LastTriggerTime = MyAPIGateway.Session.GameDateTime; } } foreach (var resetTrigger in CommandTriggers) { if (trigger.Actions.ResetTriggerCooldownNames.Contains(resetTrigger.ProfileSubtypeId)) { resetTrigger.LastTriggerTime = MyAPIGateway.Session.GameDateTime; } } } if (trigger.Actions.EnableTriggers) { foreach (var resetTrigger in Triggers) { if (trigger.Actions.EnableTriggerNames.Contains(resetTrigger.ProfileSubtypeId)) { resetTrigger.UseTrigger = true; } } foreach (var resetTrigger in DamageTriggers) { if (trigger.Actions.EnableTriggerNames.Contains(resetTrigger.ProfileSubtypeId)) { resetTrigger.UseTrigger = true; } } foreach (var resetTrigger in CommandTriggers) { if (trigger.Actions.EnableTriggerNames.Contains(resetTrigger.ProfileSubtypeId)) { resetTrigger.UseTrigger = true; } } } if (trigger.Actions.DisableTriggers) { foreach (var resetTrigger in Triggers) { if (trigger.Actions.DisableTriggerNames.Contains(resetTrigger.ProfileSubtypeId)) { resetTrigger.UseTrigger = false; } } foreach (var resetTrigger in DamageTriggers) { if (trigger.Actions.DisableTriggerNames.Contains(resetTrigger.ProfileSubtypeId)) { resetTrigger.UseTrigger = false; } } foreach (var resetTrigger in CommandTriggers) { if (trigger.Actions.DisableTriggerNames.Contains(resetTrigger.ProfileSubtypeId)) { resetTrigger.UseTrigger = false; } } } //ChangeInertiaDampeners if (trigger.Actions.ChangeInertiaDampeners) { RemoteControl.DampenersOverride = trigger.Actions.InertiaDampenersEnable; } //ChangeRotationDirection if (trigger.Actions.ChangeRotationDirection) { _behavior.Settings.SetRotation(trigger.Actions.RotationDirection); } //GenerateExplosion if (trigger.Actions.GenerateExplosion) { var coords = Vector3D.Transform(trigger.Actions.ExplosionOffsetFromRemote, RemoteControl.WorldMatrix); MyVisualScriptLogicProvider.CreateExplosion(coords, trigger.Actions.ExplosionRange, trigger.Actions.ExplosionDamage); } //SetBooleansTrue foreach (var variable in trigger.Actions.SetBooleansTrue) { _settings.SetCustomBool(variable, true); } //SetBooleansFalse foreach (var variable in trigger.Actions.SetBooleansFalse) { _settings.SetCustomBool(variable, false); } //IncreaseCounters foreach (var variable in trigger.Actions.IncreaseCounters) { _settings.SetCustomCounter(variable, 1); } //DecreaseCounters foreach (var variable in trigger.Actions.DecreaseCounters) { _settings.SetCustomCounter(variable, -1); } //ResetCounters foreach (var variable in trigger.Actions.ResetCounters) { _settings.SetCustomCounter(variable, 0, true); } //SetSandboxBooleansTrue foreach (var variable in trigger.Actions.SetSandboxBooleansTrue) { SetSandboxBool(variable, true); } //SetSandboxBooleansFalse foreach (var variable in trigger.Actions.SetSandboxBooleansFalse) { SetSandboxBool(variable, false); } //IncreaseSandboxCounters foreach (var variable in trigger.Actions.IncreaseSandboxCounters) { SetSandboxCounter(variable, 1); } //DecreaseSandboxCounters foreach (var variable in trigger.Actions.DecreaseSandboxCounters) { SetSandboxCounter(variable, -1); } //ResetSandboxCounters foreach (var variable in trigger.Actions.ResetSandboxCounters) { SetSandboxCounter(variable, 0); } //BehaviorSpecificEventA if (trigger.Actions.BehaviorSpecificEventA) { BehaviorEventA?.Invoke(); } //BehaviorSpecificEventB if (trigger.Actions.BehaviorSpecificEventB) { BehaviorEventB?.Invoke(); } //BehaviorSpecificEventC if (trigger.Actions.BehaviorSpecificEventC) { BehaviorEventC?.Invoke(); } //BehaviorSpecificEventD if (trigger.Actions.BehaviorSpecificEventD) { BehaviorEventD?.Invoke(); } //BehaviorSpecificEventE if (trigger.Actions.BehaviorSpecificEventE) { BehaviorEventE?.Invoke(); } //BehaviorSpecificEventF if (trigger.Actions.BehaviorSpecificEventF) { BehaviorEventF?.Invoke(); } //BehaviorSpecificEventG if (trigger.Actions.BehaviorSpecificEventG) { BehaviorEventG?.Invoke(); } //BehaviorSpecificEventH if (trigger.Actions.BehaviorSpecificEventH) { BehaviorEventH?.Invoke(); } }
public void ProcessAction(TriggerProfile trigger, ActionProfile actions, long attackerEntityId = 0, long detectedEntity = 0, Command command = null) { Logger.MsgDebug(trigger.ProfileSubtypeId + " Attempting To Execute Action Profile " + actions.ProfileSubtypeId, DebugTypeEnum.Action); if (actions.Chance < 100) { var roll = Utilities.Rnd.Next(0, 101); if (roll > actions.Chance) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Did Not Pass Chance Check", DebugTypeEnum.Action); return; } } Logger.MsgDebug(actions.ProfileSubtypeId + ": Performing Eligible Actions", DebugTypeEnum.Action); //ChatBroadcast if (actions.UseChatBroadcast == true) { foreach (var chatData in actions.ChatData) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Attempting Chat Broadcast", DebugTypeEnum.Action); _broadcast.BroadcastRequest(chatData); } } //BarrellRoll if (actions.BarrelRoll == true) { _behavior.AutoPilot.ActivateBarrelRoll(); } //Ramming if (actions.Ramming == true) { _behavior.AutoPilot.ActivateRamming(); } //Strafe - Implement Post Release if (actions.Strafe == true) { //_autopilot.ChangeAutoPilotMode(AutoPilotMode.Strafe); } //ChangeAutopilotSpeed if (actions.ChangeAutopilotSpeed == true) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Changing AutoPilot Speed To: " + actions.NewAutopilotSpeed.ToString(), DebugTypeEnum.Action); _autopilot.Data.IdealMaxSpeed = actions.NewAutopilotSpeed; var blockList = TargetHelper.GetAllBlocks(RemoteControl.SlimBlock.CubeGrid); foreach (var block in blockList.Where(x => x.FatBlock != null)) { var tBlock = block.FatBlock as IMyRemoteControl; if (tBlock != null) { tBlock.SpeedLimit = actions.NewAutopilotSpeed; } } } //SpawnReinforcements if (actions.SpawnEncounter == true) { foreach (var spawner in actions.Spawner) { if (spawner.UseSpawn) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Attempting Spawn", DebugTypeEnum.Spawn); if (spawner.IsReadyToSpawn()) { //Logger.AddMsg("Do Spawn", true); spawner.AssignInitialMatrix(RemoteControl.WorldMatrix); spawner.CurrentFactionTag = spawner.ForceSameFactionOwnership && !string.IsNullOrWhiteSpace(_owner.Faction?.Tag) ? _owner.Faction.Tag : ""; SpawnHelper.SpawnRequest(spawner); } } } } else { } //SelfDestruct if (actions.SelfDestruct == true) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Attempting SelfDestruct", DebugTypeEnum.Action); var blockList = TargetHelper.GetAllBlocks(RemoteControl.SlimBlock.CubeGrid); int totalWarheads = 0; foreach (var block in blockList.Where(x => x.FatBlock != null)) { var tBlock = block.FatBlock as IMyWarhead; if (tBlock != null) { if (!actions.StaggerWarheadDetonation) { tBlock.IsArmed = true; tBlock.DetonationTime = 0; tBlock.Detonate(); totalWarheads++; } else { totalWarheads++; tBlock.IsArmed = true; tBlock.DetonationTime = (totalWarheads * actions.SelfDestructTimeBetweenBlasts) + actions.SelfDestructTimerPadding; tBlock.StartCountdown(); } } } //Logger.AddMsg("TotalBlocks: " + blockList.Count.ToString(), true); //Logger.AddMsg("TotalWarheads: " + totalWarheads.ToString(), true); //TODO: Shield EMP } //Retreat if (actions.Retreat) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Attempting Retreat", DebugTypeEnum.Action); _despawn.Retreat(); } //ForceDespawn if (actions.ForceDespawn) { _despawn.DespawnGrid(); } //TerminateBehavior if (actions.TerminateBehavior) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Attempting Termination Of Behavior", DebugTypeEnum.Action); _autopilot.ActivateAutoPilot(Vector3D.Zero, NewAutoPilotMode.None); _behavior.BehaviorTerminated = true; } //BroadcastGenericCommand if (actions.BroadcastGenericCommand == true) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Attempting Broadcast of Generic Command", DebugTypeEnum.Action); double sendRadius = 0; if (actions.SendCommandWithoutAntenna) { sendRadius = actions.SendCommandWithoutAntennaRadius; } else { var antenna = _behavior.Grid.GetAntennaWithHighestRange(); if (antenna != null) { sendRadius = antenna.Radius; } } if (sendRadius != 0) { var newCommand = new Command(); newCommand.CommandCode = actions.BroadcastSendCode; newCommand.RemoteControl = RemoteControl; newCommand.Radius = sendRadius; CommandHelper.CommandTrigger?.Invoke(newCommand); } } //BroadcastDamagerTarget if (actions.BroadcastDamagerTarget == true && detectedEntity != 0) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Attempting Broadcast of Damager", DebugTypeEnum.Action); double sendRadius = 0; if (actions.SendCommandWithoutAntenna) { sendRadius = actions.SendCommandWithoutAntennaRadius; } else { var antenna = _behavior.Grid.GetAntennaWithHighestRange(); if (antenna != null) { sendRadius = antenna.Radius; } } if (sendRadius != 0) { var newCommand = new Command(); newCommand.CommandCode = actions.BroadcastSendCode; newCommand.RemoteControl = RemoteControl; newCommand.Radius = sendRadius; newCommand.TargetEntityId = detectedEntity; CommandHelper.CommandTrigger?.Invoke(newCommand); } } //SwitchToReceivedTarget if (actions.SwitchToReceivedTarget == true && (command != null || detectedEntity != 0)) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Attempting Switch to Received Target Data", DebugTypeEnum.Action); long switchToId = 0; if (command != null && command.TargetEntityId != 0) { switchToId = command.TargetEntityId; } else if (detectedEntity != 0) { switchToId = detectedEntity; } IMyEntity tempEntity = null; if (MyAPIGateway.Entities.TryGetEntityById(switchToId, out tempEntity)) { _autopilot.Targeting.ForceTargetEntityId = switchToId; _autopilot.Targeting.ForceTargetEntity = tempEntity; _autopilot.Targeting.ForceRefresh = true; } } //SwitchToDamagerTarget if (actions.SwitchToDamagerTarget == true && detectedEntity != 0) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Attempting Switch to Damager Target Data", DebugTypeEnum.Action); _autopilot.Targeting.ForceTargetEntityId = detectedEntity; _autopilot.Targeting.ForceRefresh = true; } //SwitchToBehavior if (actions.SwitchToBehavior == true) { _behavior.ChangeBehavior(actions.NewBehavior, actions.PreserveSettingsOnBehaviorSwitch, actions.PreserveTriggersOnBehaviorSwitch, actions.PreserveTargetDataOnBehaviorSwitch); } //ChangePlayerCredits if (actions.ChangePlayerCredits && command != null && command.Type == CommandType.PlayerChat) { if (command.PlayerIdentity != 0) { var playerList = new List <IMyPlayer>(); MyAPIGateway.Players.GetPlayers(playerList, p => p.IdentityId == command.PlayerIdentity); foreach (var player in playerList) { long credits = 0; player.TryGetBalanceInfo(out credits); if (actions.ChangePlayerCreditsAmount > 0) { player.RequestChangeBalance(actions.ChangePlayerCreditsAmount); PaymentSuccessTriggered = true; } else { if (actions.ChangePlayerCreditsAmount > credits) { PaymentFailureTriggered = true; } else { player.RequestChangeBalance(actions.ChangePlayerCreditsAmount); PaymentSuccessTriggered = true; } } } } } //ChangeNpcFactionCredits if (actions.ChangeNpcFactionCredits) { IMyFaction faction = null; if (string.IsNullOrWhiteSpace(actions.ChangeNpcFactionCreditsTag)) { faction = _behavior.Owner.Faction; } else { faction = MyAPIGateway.Session.Factions.TryGetFactionByTag(actions.ChangeNpcFactionCreditsTag); } if (faction != null) { long credits = 0; faction.TryGetBalanceInfo(out credits); if (actions.ChangePlayerCreditsAmount > 0) { faction.RequestChangeBalance(actions.ChangePlayerCreditsAmount); PaymentSuccessTriggered = true; } else { if (actions.ChangePlayerCreditsAmount > credits) { PaymentFailureTriggered = true; } else { faction.RequestChangeBalance(actions.ChangePlayerCreditsAmount); PaymentSuccessTriggered = true; } } } } //RefreshTarget if (actions.RefreshTarget == true) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Attempting Target Refresh", DebugTypeEnum.Action); _autopilot.Targeting.ForceRefresh = true; } //ChangeTargetProfile if (actions.ChangeTargetProfile == true) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Attempting Target Profile Change", DebugTypeEnum.Action); _autopilot.Targeting.UseNewTargetProfile = true; _autopilot.Targeting.NewTargetProfileName = actions.NewTargetProfileId; } //ChangeReputationWithPlayers if (actions.ChangeReputationWithPlayers == true) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Attempting Reputation Change With Players In Radius", DebugTypeEnum.Action); OwnershipHelper.ChangeReputationWithPlayersInRadius(RemoteControl, actions.ReputationChangeRadius, actions.ReputationChangeAmount, actions.ReputationChangeFactions, actions.ReputationChangesForAllRadiusPlayerFactionMembers); } //ChangeAttackerReputation if (actions.ChangeAttackerReputation == true && detectedEntity != 0) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Attempting Reputation Change for Attacker", DebugTypeEnum.Action); OwnershipHelper.ChangeDamageOwnerReputation(actions.ChangeAttackerReputationFaction, detectedEntity, actions.ChangeAttackerReputationAmount, actions.ReputationChangesForAllAttackPlayerFactionMembers); } //TriggerTimerBlock if (actions.TriggerTimerBlocks == true) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Attempting Trigger of Timer Blocks", DebugTypeEnum.Action); var blockList = BlockHelper.GetBlocksWithNames(RemoteControl.SlimBlock.CubeGrid, actions.TimerBlockNames); foreach (var block in blockList) { var tBlock = block as IMyTimerBlock; if (tBlock != null) { tBlock.Trigger(); } } } //ChangeBlockNames if (actions.ChangeBlockNames) { _behavior.Grid.RenameBlocks(actions.ChangeBlockNamesFrom, actions.ChangeBlockNamesTo, actions.ProfileSubtypeId); } //ChangeAntennaRanges if (actions.ChangeAntennaRanges) { _behavior.Grid.SetGridAntennaRanges(actions.AntennaNamesForRangeChange, actions.AntennaRangeChangeType, actions.AntennaRangeChangeAmount); } //ChangeAntennaOwnership if (actions.ChangeAntennaOwnership == true) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Attempting Antenna Ownership Change", DebugTypeEnum.Action); OwnershipHelper.ChangeAntennaBlockOwnership(AntennaList, actions.AntennaFactionOwner); } //CreateKnownPlayerArea if (actions.CreateKnownPlayerArea == true) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Attempting Creation of Known Player Area in MES", DebugTypeEnum.Action); MESApi.AddKnownPlayerLocation(RemoteControl.GetPosition(), _owner.Faction?.Tag, actions.KnownPlayerAreaRadius, actions.KnownPlayerAreaTimer, actions.KnownPlayerAreaMaxSpawns, actions.KnownPlayerAreaMinThreatForAvoidingAbandonment); } //RemoveKnownPlayerLocation if (actions.RemoveKnownPlayerArea == true) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Attempting Removal of Known Player Area in MES", DebugTypeEnum.Action); MESApi.RemoveKnownPlayerLocation(RemoteControl.GetPosition(), _owner.Faction?.Tag, actions.RemoveAllKnownPlayerAreas); } //DamageAttacker if (actions.DamageToolAttacker == true && detectedEntity != 0) { Logger.MsgDebug(actions.ProfileSubtypeId + ": Attempting Damage to Tool User", DebugTypeEnum.Action); DamageHelper.ApplyDamageToTarget(attackerEntityId, actions.DamageToolAttackerAmount, actions.DamageToolAttackerParticle, actions.DamageToolAttackerSound); } //PlayParticleEffectAtRemote if (actions.PlayParticleEffectAtRemote == true) { EffectManager.SendParticleEffectRequest(actions.ParticleEffectId, RemoteControl.WorldMatrix, actions.ParticleEffectOffset, actions.ParticleEffectScale, actions.ParticleEffectMaxTime, actions.ParticleEffectColor); } //ResetCooldownTimeOfTriggers if (actions.ResetCooldownTimeOfTriggers) { foreach (var resetTrigger in Triggers) { if (actions.ResetTriggerCooldownNames.Contains(resetTrigger.ProfileSubtypeId)) { resetTrigger.LastTriggerTime = MyAPIGateway.Session.GameDateTime; } } foreach (var resetTrigger in DamageTriggers) { if (actions.ResetTriggerCooldownNames.Contains(resetTrigger.ProfileSubtypeId)) { resetTrigger.LastTriggerTime = MyAPIGateway.Session.GameDateTime; } } foreach (var resetTrigger in CommandTriggers) { if (actions.ResetTriggerCooldownNames.Contains(resetTrigger.ProfileSubtypeId)) { resetTrigger.LastTriggerTime = MyAPIGateway.Session.GameDateTime; } } } //EnableTriggers if (actions.EnableTriggers) { Logger.MsgDebug(actions.ProfileSubtypeId + " Attempting To Enable Triggers.", DebugTypeEnum.Action); foreach (var resetTrigger in Triggers) { if (actions.EnableTriggerNames.Contains(resetTrigger.ProfileSubtypeId)) { resetTrigger.UseTrigger = true; } } foreach (var resetTrigger in DamageTriggers) { if (actions.EnableTriggerNames.Contains(resetTrigger.ProfileSubtypeId)) { resetTrigger.UseTrigger = true; } } foreach (var resetTrigger in CommandTriggers) { if (actions.EnableTriggerNames.Contains(resetTrigger.ProfileSubtypeId)) { resetTrigger.UseTrigger = true; } } } //DisableTriggers if (actions.DisableTriggers) { Logger.MsgDebug(actions.ProfileSubtypeId + " Attempting To Disable Triggers.", DebugTypeEnum.Action); foreach (var resetTrigger in Triggers) { if (actions.DisableTriggerNames.Contains(resetTrigger.ProfileSubtypeId)) { resetTrigger.UseTrigger = false; } } foreach (var resetTrigger in DamageTriggers) { if (actions.DisableTriggerNames.Contains(resetTrigger.ProfileSubtypeId)) { resetTrigger.UseTrigger = false; } } foreach (var resetTrigger in CommandTriggers) { if (actions.DisableTriggerNames.Contains(resetTrigger.ProfileSubtypeId)) { resetTrigger.UseTrigger = false; } } } //ManuallyActivateTrigger if (actions.ManuallyActivateTrigger) { Logger.MsgDebug(actions.ProfileSubtypeId + " Attempting To Manually Activate Triggers.", DebugTypeEnum.Action); foreach (var manualTrigger in Triggers) { if (actions.ManuallyActivatedTriggerNames.Contains(manualTrigger.ProfileSubtypeId)) { ProcessManualTrigger(manualTrigger, actions.ForceManualTriggerActivation); } } } //ChangeInertiaDampeners if (actions.ChangeInertiaDampeners) { RemoteControl.DampenersOverride = actions.InertiaDampenersEnable; } //ChangeRotationDirection if (actions.ChangeRotationDirection) { _behavior.Settings.SetRotation(actions.RotationDirection); } //GenerateExplosion if (actions.GenerateExplosion) { var coords = Vector3D.Transform(actions.ExplosionOffsetFromRemote, RemoteControl.WorldMatrix); DamageHelper.CreateExplosion(coords, actions.ExplosionRange, actions.ExplosionDamage, RemoteControl, actions.ExplosionIgnoresVoxels); } //GridEditable if (actions.GridEditable != CheckEnum.Ignore) { _behavior.Grid.SetGridEditable(RemoteControl.SlimBlock.CubeGrid, actions.GridEditable == CheckEnum.Yes); if (actions.SubGridsEditable != CheckEnum.Ignore) { foreach (var cubeGrid in MyAPIGateway.GridGroups.GetGroup(RemoteControl.SlimBlock.CubeGrid, GridLinkTypeEnum.Physical)) { _behavior.Grid.SetGridEditable(cubeGrid, actions.SubGridsEditable == CheckEnum.Yes); } } } //GridDestructible if (actions.GridDestructible != CheckEnum.Ignore) { _behavior.Grid.SetGridDestructible(RemoteControl.SlimBlock.CubeGrid, actions.GridDestructible == CheckEnum.Yes); if (actions.SubGridsDestructible != CheckEnum.Ignore) { foreach (var cubeGrid in MyAPIGateway.GridGroups.GetGroup(RemoteControl.SlimBlock.CubeGrid, GridLinkTypeEnum.Physical)) { _behavior.Grid.SetGridDestructible(cubeGrid, actions.SubGridsDestructible == CheckEnum.Yes); } } } //RecolorGrid if (actions.RecolorGrid) { _behavior.Grid.RecolorBlocks(RemoteControl.SlimBlock.CubeGrid, actions.OldBlockColors, actions.NewBlockColors, actions.NewBlockSkins); if (actions.RecolorSubGrids) { foreach (var cubeGrid in MyAPIGateway.GridGroups.GetGroup(RemoteControl.SlimBlock.CubeGrid, GridLinkTypeEnum.Physical)) { _behavior.Grid.RecolorBlocks(cubeGrid, actions.OldBlockColors, actions.NewBlockColors, actions.NewBlockSkins); } } } //Enable Blocks if (actions.EnableBlocks) { _behavior.Grid.EnableBlocks(actions.EnableBlockNames, actions.EnableBlockStates); } //BuildProjectedBlocks if (actions.BuildProjectedBlocks) { _behavior.Grid.BuildProjectedBlocks(actions.MaxProjectedBlocksToBuild); } //ChangeBlockOwnership if (actions.ChangeBlockOwnership) { BlockHelper.ChangeBlockOwnership(RemoteControl.SlimBlock.CubeGrid, actions.OwnershipBlockNames, actions.OwnershipBlockFactions); } //RazeBlocks if (actions.RazeBlocksWithNames) { _behavior.Grid.RazeBlocksWithNames(actions.RazeBlocksNames); } //ChangeAutoPilotProfile if (actions.ChangeAutopilotProfile) { _behavior.AutoPilot.SetAutoPilotDataMode(actions.AutopilotProfile); } //CreateRandomLightning if (actions.CreateRandomLightning) { if (_behavior.AutoPilot.InGravity() && _behavior.AutoPilot.CurrentPlanet.HasAtmosphere) { var up = Vector3D.Normalize(RemoteControl.GetPosition() - _behavior.AutoPilot.CurrentPlanet.PositionComp.WorldAABB.Center); var randomPerpendicular = MyUtils.GetRandomPerpendicularVector(ref up); var strikeCoords = _behavior.AutoPilot.CurrentPlanet.GetClosestSurfacePointGlobal(randomPerpendicular * MathTools.RandomBetween(actions.LightningMinDistance, actions.LightningMaxDistance) + RemoteControl.GetPosition()); DamageHelper.CreateLightning(strikeCoords, actions.LightningDamage, actions.LightningExplosionRadius, actions.LightningColor); } } //CreateLightningAtAttacker if (actions.CreateLightningAtAttacker && detectedEntity != 0) { if (_behavior.AutoPilot.InGravity() && _behavior.AutoPilot.CurrentPlanet.HasAtmosphere) { IMyEntity entity = null; if (MyAPIGateway.Entities.TryGetEntityById(detectedEntity, out entity)) { DamageHelper.CreateLightning(entity.PositionComp.WorldAABB.Center, actions.LightningDamage, actions.LightningExplosionRadius, actions.LightningColor); } } } //CreateLightningAtTarget if (actions.CreateLightningAtTarget && _behavior.AutoPilot.Targeting.HasTarget()) { if (_behavior.AutoPilot.InGravity() && _behavior.AutoPilot.CurrentPlanet.HasAtmosphere) { DamageHelper.CreateLightning(_behavior.AutoPilot.Targeting.TargetLastKnownCoords, actions.LightningDamage, actions.LightningExplosionRadius, actions.LightningColor); } } //InheritLastAttackerFromCommand if (actions.InheritLastAttackerFromCommand) { _behavior.Settings.LastDamagerEntity = command != null ? command.TargetEntityId : 0; } //SetBooleansTrue foreach (var variable in actions.SetBooleansTrue) { _settings.SetCustomBool(variable, true); } //SetBooleansFalse foreach (var variable in actions.SetBooleansFalse) { _settings.SetCustomBool(variable, false); } //IncreaseCounters foreach (var variable in actions.IncreaseCounters) { _settings.SetCustomCounter(variable, 1); } //DecreaseCounters foreach (var variable in actions.DecreaseCounters) { _settings.SetCustomCounter(variable, -1); } //ResetCounters foreach (var variable in actions.ResetCounters) { _settings.SetCustomCounter(variable, 0, true); } //SetCounters if (actions.SetCounters.Count == actions.SetCountersValues.Count) { for (int i = 0; i < actions.SetCounters.Count; i++) { _settings.SetCustomCounter(actions.SetCounters[i], actions.SetCountersValues[i], false, true); } } //SetSandboxBooleansTrue foreach (var variable in actions.SetSandboxBooleansTrue) { SetSandboxBool(variable, true); } //SetSandboxBooleansFalse foreach (var variable in actions.SetSandboxBooleansFalse) { SetSandboxBool(variable, false); } //IncreaseSandboxCounters foreach (var variable in actions.IncreaseSandboxCounters) { SetSandboxCounter(variable, 1); } //DecreaseSandboxCounters foreach (var variable in actions.DecreaseSandboxCounters) { SetSandboxCounter(variable, -1); } //ResetSandboxCounters foreach (var variable in actions.ResetSandboxCounters) { SetSandboxCounter(variable, 0); } //SetSandboxCounters if (actions.SetSandboxCounters.Count != 0 && actions.SetSandboxCounters.Count == actions.SetSandboxCountersValues.Count) { for (int i = 0; i < actions.SetCounters.Count; i++) { SetSandboxCounter(actions.SetSandboxCounters[i], actions.SetSandboxCountersValues[i], true); } } //BehaviorSpecificEventA if (actions.BehaviorSpecificEventA) { _behavior.BehaviorActionA = true; } //BehaviorSpecificEventB if (actions.BehaviorSpecificEventB) { _behavior.BehaviorActionB = true; } //BehaviorSpecificEventC if (actions.BehaviorSpecificEventC) { _behavior.BehaviorActionC = true; } //BehaviorSpecificEventD if (actions.BehaviorSpecificEventD) { _behavior.BehaviorActionD = true; } //BehaviorSpecificEventE if (actions.BehaviorSpecificEventE) { _behavior.BehaviorActionE = true; } //BehaviorSpecificEventF if (actions.BehaviorSpecificEventF) { _behavior.BehaviorActionF = true; } //BehaviorSpecificEventG if (actions.BehaviorSpecificEventG) { _behavior.BehaviorActionG = true; } //BehaviorSpecificEventH if (actions.BehaviorSpecificEventH) { _behavior.BehaviorActionH = true; } }
public void ProcessTriggerWatchers() { var timeDifference = MyAPIGateway.Session.GameDateTime - LastTriggerRun; if (timeDifference.TotalMilliseconds < 500) { //Logger.MsgDebug("Triggers Not Ready (total ms elapsed: "+ timeDifference.TotalMilliseconds.ToString() + "), Handing Off to Next Action", DebugTypeEnum.Dev); //OnComplete?.Invoke(); return; } //Logger.MsgDebug("Checking Triggers", DebugTypeEnum.Dev); LastTriggerRun = MyAPIGateway.Session.GameDateTime; for (int i = 0; i < Triggers.Count; i++) { var trigger = Triggers[i]; if (!trigger.UseTrigger) { continue; } //Timer if (trigger.Type == "Timer") { //Logger.MsgDebug("Checking Timer Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger); if (trigger.UseTrigger == true) { trigger.ActivateTrigger(); } continue; } //PlayerNear if (trigger.Type == "PlayerNear") { //Logger.MsgDebug("Checking PlayerNear Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger); if (trigger.UseTrigger == true) { if (IsPlayerNearby(trigger)) { trigger.ActivateTrigger(); } } continue; } //PlayerFar if (trigger.Type == "PlayerFar") { //Logger.MsgDebug("Checking PlayerNear Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger); if (trigger.UseTrigger == true) { if (IsPlayerNearby(trigger, true)) { trigger.ActivateTrigger(); } } continue; } //TargetNear if (trigger.Type == "TargetNear") { //Logger.MsgDebug("Checking PlayerNear Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger); if (trigger.UseTrigger == true) { if (_behavior.AutoPilot.Targeting.HasTarget() && Vector3D.Distance(RemoteControl.GetPosition(), _behavior.AutoPilot.Targeting.TargetLastKnownCoords) < trigger.TargetDistance) { trigger.ActivateTrigger(); } } continue; } //TargetFar if (trigger.Type == "TargetFar") { //Logger.MsgDebug("Checking PlayerNear Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger); if (trigger.UseTrigger == true) { if (_behavior.AutoPilot.Targeting.HasTarget() && Vector3D.Distance(RemoteControl.GetPosition(), _behavior.AutoPilot.Targeting.TargetLastKnownCoords) > trigger.TargetDistance) { trigger.ActivateTrigger(); } } continue; } //DespawnNear if (trigger.Type == "DespawnNear") { //Logger.MsgDebug("Checking DespawnNear Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger); if (trigger.UseTrigger == true) { if (_behavior.Settings.DespawnCoords != Vector3D.Zero && Vector3D.Distance(RemoteControl.GetPosition(), _behavior.Settings.DespawnCoords) < trigger.TargetDistance) { trigger.ActivateTrigger(); } } continue; } //DespawnFar if (trigger.Type == "DespawnFar") { //Logger.MsgDebug("Checking DespawnFar Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger); if (trigger.UseTrigger == true) { if (_behavior.Settings.DespawnCoords != Vector3D.Zero && Vector3D.Distance(RemoteControl.GetPosition(), _behavior.Settings.DespawnCoords) > trigger.TargetDistance) { trigger.ActivateTrigger(); } } continue; } //TurretTarget if (trigger.Type == "TurretTarget") { //Logger.MsgDebug("Checking TurretTarget Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger); if (trigger.UseTrigger == true) { var turretTarget = _autopilot.Weapons.GetTurretTarget(); if (turretTarget != 0) { trigger.ActivateTrigger(); if (trigger.Triggered == true) { trigger.DetectedEntityId = turretTarget; } } } continue; } //NoWeapon if (trigger.Type == "NoWeapon") { //Logger.MsgDebug("Checking NoWeapon Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger); if (trigger.UseTrigger && !_autopilot.Weapons.HasWorkingWeapons()) { trigger.ActivateTrigger(); } continue; } //NoTarget if (trigger.Type == "NoTarget") { //Logger.MsgDebug("Checking NoTarget Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger); if (trigger.UseTrigger) { if (!_autopilot.Targeting.HasTarget()) { trigger.ActivateTrigger(); } } continue; } //HasTarget if (trigger.Type == "HasTarget") { //Logger.MsgDebug("Checking HasTarget Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger); if (trigger.UseTrigger) { if (_autopilot.Targeting.HasTarget()) { trigger.ActivateTrigger(); } } continue; } //AcquiredTarget if (trigger.Type == "AcquiredTarget") { //Logger.MsgDebug("Checking NoTarget Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger); if (trigger.UseTrigger) { if (_autopilot.Targeting.TargetAcquired) { _autopilot.Targeting.TargetAcquired = false; trigger.ActivateTrigger(); } } continue; } //LostTarget if (trigger.Type == "LostTarget") { //Logger.MsgDebug("Checking HasTarget Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger); if (trigger.UseTrigger) { if (_autopilot.Targeting.TargetLost) { _autopilot.Targeting.TargetLost = false; trigger.ActivateTrigger(); } } continue; } //TargetInSafezone if (trigger.Type == "TargetInSafezone") { //Logger.MsgDebug("Checking TargetInSafezone Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger); if (trigger.UseTrigger == true) { if (_autopilot.Targeting.HasTarget() && _autopilot.Targeting.Target.InSafeZone()) { trigger.ActivateTrigger(); } } continue; } //Grounded if (trigger.Type == "Grounded") { if (trigger.UseTrigger == true) { //Check if Grounded trigger.ActivateTrigger(); } continue; } //BehaviorTriggerA if (trigger.Type == "BehaviorTriggerA") { if (trigger.UseTrigger == true && _behavior.BehaviorTriggerA) { trigger.ActivateTrigger(); } continue; } //BehaviorTriggerB if (trigger.Type == "BehaviorTriggerB") { if (trigger.UseTrigger == true && _behavior.BehaviorTriggerB) { trigger.ActivateTrigger(); } continue; } //BehaviorTriggerC if (trigger.Type == "BehaviorTriggerC") { if (trigger.UseTrigger == true && _behavior.BehaviorTriggerC) { trigger.ActivateTrigger(); } continue; } //BehaviorTriggerD if (trigger.Type == "BehaviorTriggerD") { if (trigger.UseTrigger == true && _behavior.BehaviorTriggerD) { trigger.ActivateTrigger(); } continue; } //BehaviorTriggerE if (trigger.Type == "BehaviorTriggerE") { if (trigger.UseTrigger == true && _behavior.BehaviorTriggerE) { trigger.ActivateTrigger(); } continue; } //BehaviorTriggerF if (trigger.Type == "BehaviorTriggerF") { if (trigger.UseTrigger == true && _behavior.BehaviorTriggerF) { trigger.ActivateTrigger(); } continue; } //BehaviorTriggerG if (trigger.Type == "BehaviorTriggerG") { if (trigger.UseTrigger == true && _behavior.BehaviorTriggerG) { trigger.ActivateTrigger(); } continue; } //PaymentSuccess if (trigger.Type == "PaymentSuccess") { if (trigger.UseTrigger == true && PaymentSuccessTriggered) { trigger.ActivateTrigger(); } continue; } //PaymentFailure if (trigger.Type == "PaymentFailure") { if (trigger.UseTrigger == true && PaymentFailureTriggered) { trigger.ActivateTrigger(); } continue; } //PlayerKnownLocation if (trigger.Type == "PlayerKnownLocation") { if (MESApi.MESApiReady) { if (trigger.UseTrigger == true && MESApi.IsPositionInKnownPlayerLocation(RemoteControl.GetPosition(), true, _behavior.Owner.Faction?.Tag)) { trigger.ActivateTrigger(); } } continue; } //SensorActive if (trigger.Type == "SensorActive") { if (_behavior.Grid.SensorCheck(trigger.SensorName)) { trigger.ActivateTrigger(); } continue; } //SensorActive if (trigger.Type == "SensorIdle") { if (_behavior.Grid.SensorCheck(trigger.SensorName, false)) { trigger.ActivateTrigger(); } continue; } } _behavior.BehaviorTriggerA = false; _behavior.BehaviorTriggerB = false; _behavior.BehaviorTriggerC = false; _behavior.BehaviorTriggerD = false; _behavior.BehaviorTriggerE = false; _behavior.BehaviorTriggerF = false; _behavior.BehaviorTriggerG = false; PaymentSuccessTriggered = false; PaymentFailureTriggered = false; TimedTriggersProcessed = true; }
public bool AreConditionsMets() { if (!_gotWatchedBlocks) { SetupWatchedBlocks(); } if (this.UseConditions == false) { return(true); } int usedConditions = 0; int satisfiedConditions = 0; if (this.CheckAllLoadedModIDs == true) { usedConditions++; bool missingMod = false; foreach (var mod in this.AllModIDsToCheck) { if (Utilities.ModIDs.Contains(mod) == false) { Logger.MsgDebug(this.ProfileSubtypeId + ": Mod ID Not Present", DebugTypeEnum.Condition); missingMod = true; break; } } if (!missingMod) { satisfiedConditions++; } } if (this.CheckAnyLoadedModIDs == true) { usedConditions++; foreach (var mod in this.AllModIDsToCheck) { if (Utilities.ModIDs.Contains(mod)) { Logger.MsgDebug(this.ProfileSubtypeId + ": A Mod ID was Found: " + mod.ToString(), DebugTypeEnum.Condition); satisfiedConditions++; break; } } } if (this.CheckTrueBooleans == true) { usedConditions++; bool failedCheck = false; foreach (var boolName in this.TrueBooleans) { if (!_settings.GetCustomBoolResult(boolName)) { Logger.MsgDebug(this.ProfileSubtypeId + ": Boolean Not True: " + boolName, DebugTypeEnum.Condition); failedCheck = true; break; } } if (!failedCheck) { satisfiedConditions++; } } if (this.CheckCustomCounters == true) { usedConditions++; bool failedCheck = false; if (this.CustomCounters.Count == this.CustomCountersTargets.Count) { for (int i = 0; i < this.CustomCounters.Count; i++) { try { if (_settings.GetCustomCounterResult(this.CustomCounters[i], this.CustomCountersTargets[i]) == false) { Logger.MsgDebug(this.ProfileSubtypeId + ": Counter Amount Not High Enough: " + this.CustomCounters[i], DebugTypeEnum.Condition); failedCheck = true; break; } } catch (Exception e) { Logger.MsgDebug("Exception: ", DebugTypeEnum.Condition); Logger.MsgDebug(e.ToString(), DebugTypeEnum.Condition); } } } else { Logger.MsgDebug(this.ProfileSubtypeId + ": Counter Names and Targets List Counts Don't Match. Check Your Condition Profile", DebugTypeEnum.Condition); failedCheck = true; } if (!failedCheck) { satisfiedConditions++; } } if (this.CheckTrueSandboxBooleans == true) { usedConditions++; bool failedCheck = false; for (int i = 0; i < this.TrueSandboxBooleans.Count; i++) { try { bool output = false; var result = MyAPIGateway.Utilities.GetVariable <bool>(this.TrueSandboxBooleans[i], out output); if (!result || !output) { Logger.MsgDebug(this.ProfileSubtypeId + ": Sandbox Boolean False: " + this.TrueSandboxBooleans[i], DebugTypeEnum.Condition); failedCheck = true; break; } } catch (Exception e) { Logger.MsgDebug("Exception: ", DebugTypeEnum.Condition); Logger.MsgDebug(e.ToString(), DebugTypeEnum.Condition); } } if (!failedCheck) { satisfiedConditions++; } } if (this.CheckCustomSandboxCounters == true) { usedConditions++; bool failedCheck = false; if (this.CustomCounters.Count == this.CustomCountersTargets.Count) { for (int i = 0; i < this.CustomCounters.Count; i++) { try { int counter = 0; var result = MyAPIGateway.Utilities.GetVariable <int>(this.CustomCounters[i], out counter); if (!result || counter < this.CustomCountersTargets[i]) { Logger.MsgDebug(this.ProfileSubtypeId + ": Sandbox Counter Amount Not High Enough: " + this.CustomSandboxCounters[i], DebugTypeEnum.Condition); failedCheck = true; break; } } catch (Exception e) { Logger.MsgDebug("Exception: ", DebugTypeEnum.Condition); Logger.MsgDebug(e.ToString(), DebugTypeEnum.Condition); } } } else { Logger.MsgDebug(this.ProfileSubtypeId + ": Sandbox Counter Names and Targets List Counts Don't Match. Check Your Condition Profile", DebugTypeEnum.Condition); failedCheck = true; } if (!failedCheck) { satisfiedConditions++; } } if (this.CheckGridSpeed == true) { usedConditions++; float speed = (float)_remoteControl.GetShipSpeed(); if ((this.MinGridSpeed == -1 || speed >= this.MinGridSpeed) && (this.MaxGridSpeed == -1 || speed <= this.MaxGridSpeed)) { Logger.MsgDebug(this.ProfileSubtypeId + ": Grid Speed High Enough", DebugTypeEnum.Condition); satisfiedConditions++; } else { Logger.MsgDebug(this.ProfileSubtypeId + ": Grid Speed Not High Enough", DebugTypeEnum.Condition); } } if (MESApi.MESApiReady && this.CheckMESBlacklistedSpawnGroups) { var blackList = MESApi.GetSpawnGroupBlackList(); if (this.SpawnGroupBlacklistContainsAll.Count > 0) { usedConditions++; bool failedCheck = false; foreach (var group in this.SpawnGroupBlacklistContainsAll) { if (blackList.Contains(group) == false) { Logger.MsgDebug(this.ProfileSubtypeId + ": A Spawngroup was not on MES BlackList: " + group, DebugTypeEnum.Condition); failedCheck = true; break; } } if (!failedCheck) { satisfiedConditions++; } } if (this.SpawnGroupBlacklistContainsAny.Count > 0) { usedConditions++; foreach (var group in this.SpawnGroupBlacklistContainsAll) { if (blackList.Contains(group)) { Logger.MsgDebug(this.ProfileSubtypeId + ": A Spawngroup was on MES BlackList: " + group, DebugTypeEnum.Condition); satisfiedConditions++; break; } } } } if (UseAccumulatedDamageWatcher) { usedConditions++; bool failedCheck = false; if (this.MinAccumulatedDamage >= 0 && this.MinAccumulatedDamage < _settings.TotalDamageAccumulated) { failedCheck = true; } if (this.MaxAccumulatedDamage >= 0 && this.MaxAccumulatedDamage > _settings.TotalDamageAccumulated) { failedCheck = true; } if (!failedCheck) { satisfiedConditions++; } } if (this.MatchAnyCondition == false) { bool result = (satisfiedConditions >= usedConditions); Logger.MsgDebug(this.ProfileSubtypeId + ": All Condition Satisfied: " + result.ToString(), DebugTypeEnum.Condition); Logger.MsgDebug(string.Format("Used Conditions: {0} // Satisfied Conditions: {1}", usedConditions, satisfiedConditions), DebugTypeEnum.Condition); return(result); } else { bool result = (satisfiedConditions > 0); Logger.MsgDebug(this.ProfileSubtypeId + ": Any Condition(s) Satisfied: " + result.ToString(), DebugTypeEnum.Condition); Logger.MsgDebug(string.Format("Used Conditions: {0} // Satisfied Conditions: {1}", usedConditions, satisfiedConditions), DebugTypeEnum.Condition); return(result); } }