void UpdateHitPosition(IMyRemoteControl control, int tick) { if (ticks != 1) { //RayCast not long enough, no new information acquired return; } double relativeVelocity = lastDistance - predictedPositionAngles.X; double timeFactor = 60D / (double)tick; relativeVelocity = relativeVelocity * timeFactor; if (TotalMass == -1) { TotalMass = (int)control.CalculateShipMass().TotalMass; } if (MaxThrust == -1) { MaxThrust = 0; List <IMyThrust> thruster = new List <IMyThrust>(); parent.GridTerminalSystem.GetBlocksOfType(thruster); foreach (IMyThrust thrust in thruster) { if (thrust.WorldMatrix.Forward == control.WorldMatrix.Backward) { MaxThrust += thrust.MaxThrust; } } } if (MaxAcceleration == -1) { MaxAcceleration = MaxThrust / TotalMass; } double ownSpeed = control.GetShipSpeed(); double timeToMax; double distanceAtMaxSpeed; if (ownSpeed <= 99) { timeToMax = (100 - ownSpeed) / MaxAcceleration; distanceAtMaxSpeed = predictedPositionAngles.X - (relativeVelocity + (MaxAcceleration * timeToMax) / 2) * timeToMax; } else { timeToMax = 0; distanceAtMaxSpeed = predictedPositionAngles.X; } timeToTarget = (float)(distanceAtMaxSpeed / (relativeVelocity + (100 - ownSpeed)) + timeToMax); predictedHitPoint = TargetInfo.Position + timeToTarget * TargetInfo.Velocity; lastDistance = predictedPositionAngles.X; }
public void Tick() { if (!engaged) { return; } var goingTooFast = mainControl.GetShipSpeed() > mainControl.SpeedLimit; mainControl.HandBrake = goingTooFast || LastCommand.forwardSpeed == 0; }
public void GetPredictedTargetPosition(Vector3D homebase, Vector3D homebasevelocity) { Vector3D homeship = homebase; //Get the current position of home Vector3D shippos = brain.GetPosition(); //Get the position of the drone, so we can calculate distance to home Vector3D toTarget = homeship - shippos; //Substract positions so we're left with a vector of the lenght and direction between ship and home Vector3D diffVelocity = homebasevelocity; //Get the targets velocity vector, needs to be redone if the turret isn't static double projectileSpeed = brain.GetShipSpeed(); //Define projectile speed of our guns double a = diffVelocity.LengthSquared() - projectileSpeed * projectileSpeed; //Target velocity squared minus projectile velocity squared -- Why? double b = 2 * Vector3D.Dot(diffVelocity, toTarget); // 2 * dot product of target velocity and target vector -- Why? double c = toTarget.LengthSquared(); // distance to target squared -- why? // x = (-b +/- sqrt(b^2 - 4 * a * c )) / (2 * a) - Solving 2. degree equiation double p = -b / (2 * a); double q = Math.Sqrt((b * b) - 4 * a * c) / (2 * a); // x = (-b +/- sqrt(b^2 - 4 * a * c )) / (2 * a) - Solving 2. degree equiation double t1 = p - q; //1. solution double t2 = p + q; //2. solution double t; if (t1 > t2 && t2 > 0)//Use the smallest of the two solutions, but only if it is above 0 { t = t2; } else { t = t1; } //t is the time it takes for the projectile to reach the target targetPos = homeship + diffVelocity * t; if (targetPos.X.ToString() == "NaN") { Echo("current target is stopped"); } else { Echo(targetPos.ToString()); } Echo(homebasevelocity.ToString()); }
void Main() { carspeed = Convert.ToSingle(RemoteDriver.GetShipSpeed()); if (RemoteDriver.IsUnderControl) { RotateRull(); float whangle; if (carspeed >= 18) { if (carspeed >= 40) { whangle = 15; } else { whangle = 20; } } else { whangle = NormWhAng; } if (Tangle != whangle) { Tangle = whangle; foreach (IMyMotorSuspension ThisWheel in Wheels) { ThisWheel.MaxSteerAngle = Tangle; } } } if (switchingsusp) { switchingsusp = false; foreach (IMyMotorSuspension Motor in Wheels) { Motor.Strength = Smoothing(Motor, "Strength", strengthSuspModifer, 0.15f); Motor.Height = Smoothing(Motor, "Height", heightSuspModifer, 0.0042f); if (Motor.GetValueFloat("Strength") != strengthSuspModifer || Motor.GetValueFloat("Height") != heightSuspModifer) { switchingsusp = true; } } } }
public void Main(string argument, UpdateType updateSource) { double levelElevation = 10000.00; double slowElevation = 8000; double stopVelocity = 1000; IMyRemoteControl remoteControl = GridTerminalSystem.GetBlockWithName("Remote Control") as IMyRemoteControl; IMyGyro gyroscope = GridTerminalSystem.GetBlockWithName("Gyroscope") as IMyGyro; IMyCockpit cockpit = GridTerminalSystem.GetBlockWithName("Control Seat") as IMyCockpit; IMyProgrammableBlock autoLevel = (IMyProgrammableBlock)GridTerminalSystem.GetBlockWithName("Prog Block Auto Level"); Echo(remoteControl.CustomName); Echo(gyroscope.CustomName); StringBuilder sb = new StringBuilder(); double basicVel = remoteControl.GetShipSpeed(); double elevation; remoteControl.TryGetPlanetElevation(MyPlanetElevation.Surface, out elevation); sb.AppendLine($"Vel: {basicVel}\n Elev: {elevation.ToString("0.00")}"); if (stopVelocity <= elevation) { sb.AppendLine($"Level Limit Reached"); } else if (slowElevation <= elevation) { sb.AppendLine($"Level Limit Reached"); } else if (levelElevation <= elevation) { sb.AppendLine($"Level Limit Reached"); } Write(sb.ToString(), cockpit); }
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); } }
public void Main(string argument, UpdateType updateSource) { string[] argInfo = argument.Split(new string[] { "," }, StringSplitOptions.None); if (argument == "RUN") { //Check if can scan, and scan if can. if (cam.CanScan(rayCastDistance)) { detectedInfo = cam.Raycast(rayCastDistance); } else { Echo("Can't scan yet!"); } Echo("INITIATING"); coordinate = Vector3D.Zero; //initating to zero value. Boolean found = false; if (detectedInfo.HitPosition != null) { coordinate = detectedInfo.HitPosition.Value; found = true; } if (found) { Vector3D currentCoords = rc.GetPosition(); //creating unit vector double denominator = Math.Sqrt(Math.Pow(coordinate.X - currentCoords.X, 2) + Math.Pow(coordinate.Y - currentCoords.Y, 2) + Math.Pow(coordinate.Z - currentCoords.Z, 2)); double xMultiplier = (coordinate.X - currentCoords.X) / denominator; double yMultiplier = (coordinate.Y - currentCoords.Y) / denominator; double zMultiplier = (coordinate.Z - currentCoords.Z) / denominator; //manipulating target coordinate with unit vector coordinate.X -= finalDistFromTarget * xMultiplier; coordinate.Y -= finalDistFromTarget * yMultiplier; coordinate.Z -= finalDistFromTarget * zMultiplier; //Setting up backward thrusters list backwardThrusters = new List <IMyThrust>(); //Obtaining each thruster pointing backward foreach (IMyThrust thruster in thrusters) { if (Base6Directions.GetFlippedDirection(rc.Orientation.Forward) == Base6Directions.GetFlippedDirection(thruster.Orientation.Forward)) { backwardThrusters.Add(thruster); } } //Obtaining max backward acceleration MyShipMass myShipMass = rc.CalculateShipMass(); backwardsAcceleration = CalculateAcceleration(myShipMass.TotalMass, backwardThrusters); //autopilot settings rc.ClearWaypoints(); rc.AddWaypoint(coordinate, "AUTO DYNAMIC BRAKING SCRIPT COORDINATE"); rc.SetAutoPilotEnabled(true); rc.SetCollisionAvoidance(false); rc.SetDockingMode(false); //CHANGE??? or dont? rc.FlightMode = FlightMode.OneWay; rc.Direction = Base6Directions.Direction.Forward; blindMode = false; } } else if (argInfo[0] == "blind".ToLower()) { int dist = 0; Boolean passed = Int32.TryParse(argInfo[1], out dist); if (passed) { Vector3D dir = rc.WorldMatrix.Forward; coordinate = rc.GetPosition(); coordinate.X += dir.X * dist; coordinate.Y += dir.Y * dist; coordinate.Z += dir.Z * dist; Vector3D currentCoords = rc.GetPosition(); //Setting up backward thrusters list backwardThrusters = new List <IMyThrust>(); //Obtaining each thruster pointing backward foreach (IMyThrust thruster in thrusters) { if (Base6Directions.GetFlippedDirection(rc.Orientation.Forward) == Base6Directions.GetFlippedDirection(thruster.Orientation.Forward)) { backwardThrusters.Add(thruster); } } //Obtaining max backward acceleration MyShipMass myShipMass = rc.CalculateShipMass(); backwardsAcceleration = CalculateAcceleration(myShipMass.TotalMass, backwardThrusters); //autopilot settings rc.ClearWaypoints(); rc.AddWaypoint(coordinate, "CAPTXAN'S SCRIPT COORDINATE"); rc.SetAutoPilotEnabled(true); rc.SetCollisionAvoidance(false); rc.SetDockingMode(false); //CHANGE??? or dont? rc.FlightMode = FlightMode.OneWay; rc.Direction = Base6Directions.Direction.Forward; blindMode = true; blindCounter = 0; } else { Echo("2nd parameter is not a number!"); } } else { //User Feedback if (!cam.CanScan(rayCastDistance)) { float percentage = ((cam.TimeUntilScan(rayCastDistance) / 1000) / (rayCastDistance / 2000)); percentage = (1 - percentage) * 100; Echo("Raycast is recharging " + percentage + "%"); if (!cam.EnableRaycast) { cam.EnableRaycast = true; } } else { Echo("Ready to Scan"); cam.EnableRaycast = false; } //Travelling CHANGE HERE FOR ENABLE / DISABLE AUTOPILOT if (rc.IsAutoPilotEnabled) { travelling = true; double currentDistanceFromTarget = Vector3D.Distance(coordinate, rc.GetPosition()); Echo("Travelling, ETA: " + (int)(currentDistanceFromTarget / rc.GetShipSpeed()) + "s"); //Calculating stopping distance to determine if thrusters need to be enabled. Echo("Current Speed: " + (int)rc.GetShipSpeed() + "m/s"); Echo("Ship Speed Limit: " + rc.SpeedLimit + "m/s"); if (rc.GetShipSpeed() > rc.SpeedLimit - 1) //If ship at max speed { Vector3D currentTrajectory = Vector3D.Normalize(rc.GetPosition() - prevPosition); prevPosition = rc.GetPosition(); Vector3D calculatedTrajectory = Vector3D.Normalize(rc.GetPosition() - coordinate); double accuracyAmount; if (currentDistanceFromTarget > 15000) { accuracyAmount = .99999; } else if (currentDistanceFromTarget > 5000) { accuracyAmount = .9999; } else { accuracyAmount = .999; } if (currentDistanceFromTarget * .90 > (Math.Pow(rc.GetShipSpeed(), 2) / (2 * backwardsAcceleration)) && Math.Abs(currentTrajectory.Dot(calculatedTrajectory)) > accuracyAmount) { foreach (IMyThrust thruster in thrusters) { thruster.ApplyAction("OnOff_Off"); } } else //Curr < stopp { foreach (IMyThrust thruster in thrusters) { thruster.ApplyAction("OnOff_On"); } } } Echo("Blind Mode: " + blindMode); if (blindMode) { Echo("Blind Counter: " + blindCounter); Echo("Coll Avoid: " + rc.); if (cam.CanScan(((Math.Pow(rc.GetShipSpeed(), 2) / (2 * backwardsAcceleration)) * 2))) { detectedInfo = cam.Raycast((Math.Pow(maxSpeed, 2) / (2 * backwardsAcceleration)) * 2); if (detectedInfo.HitPosition != null) { rc.SpeedLimit = 3; rc.SetCollisionAvoidance(true); blindCounter = 0; } else { if (blindCounter > 500) { rc.SpeedLimit = maxSpeed; rc.SetCollisionAvoidance(false); blindCounter = 0; } else { blindCounter++; } } } } } else if (travelling) { foreach (IMyThrust thruster in thrusters) { thruster.ApplyAction("OnOff_On"); } travelling = false; blindMode = false; } } //Additional Arugment Commands if (argument == "ABORT") { rc.SetAutoPilotEnabled(false); rc.DampenersOverride = true; } }
double CAF_DIST_TO_TARGET; //Outputs distance to target void CollectAndFire2(Vector3D INPUT_POINT, double INPUT_VELOCITY, double INPUT_MAX_VELOCITY, Vector3D REFPOS, IMyRemoteControl RC) { //Function Initialisation //-------------------------------------------------------------------- if (C_A_F_HASRUN == false) { //Initialise Classes And Basic System CAF2_FORWARD = new Thrust_info(RC.WorldMatrix.Forward, myGridTerminal, RC.CubeGrid); CAF2_UP = new Thrust_info(RC.WorldMatrix.Up, myGridTerminal, RC.CubeGrid); CAF2_RIGHT = new Thrust_info(RC.WorldMatrix.Right, myGridTerminal, RC.CubeGrid); CAFTHI = new List <Thrust_info>() { CAF2_FORWARD, CAF2_UP, CAF2_RIGHT }; myGridTerminal.GetBlocksOfType <IMyThrust>(CAF2_THRUST, block => block.CubeGrid == RC.CubeGrid); C_A_F_HASRUN = true; //Initialises Braking Component foreach (var item in CAFTHI) { CAF2_BRAKING_COUNT = (item.PositiveMaxForce < CAF2_BRAKING_COUNT) ? item.PositiveMaxForce : CAF2_BRAKING_COUNT; CAF2_BRAKING_COUNT = (item.NegativeMaxForce < CAF2_BRAKING_COUNT) ? item.PositiveMaxForce : CAF2_BRAKING_COUNT; } } //Generating Maths To Point and decelleration information etc. //-------------------------------------------------------------------- double SHIPMASS = Convert.ToDouble(RC.CalculateShipMass().PhysicalMass); Vector3D INPUT_VECTOR = Vector3D.Normalize(INPUT_POINT - REFPOS); double VELOCITY = RC.GetShipSpeed(); CAF_DIST_TO_TARGET = (REFPOS - INPUT_POINT).Length(); CAF_SHIP_DECELLERATION = 0.75 * (CAF2_BRAKING_COUNT / SHIPMASS); CAF_STOPPING_DIST = (((VELOCITY * VELOCITY) - (INPUT_VELOCITY * INPUT_VELOCITY))) / (2 * CAF_SHIP_DECELLERATION); //If Within Stopping Distance Halts Programme //-------------------------------------------- if (!(CAF_DIST_TO_TARGET > (CAF_STOPPING_DIST + 0.25)) || CAF_DIST_TO_TARGET < 0.25 || VELOCITY > INPUT_MAX_VELOCITY) { foreach (var thruster in CAF2_THRUST) { (thruster as IMyThrust).ThrustOverride = 0; } return; } //dev notes, this is the most major source of discontinuity between theorised system response //Reflects Vector To Cancel Orbiting //------------------------------------ Vector3D DRIFT_VECTOR = Vector3D.Normalize(RC.GetShipVelocities().LinearVelocity + RC.WorldMatrix.Forward * 0.00001); Vector3D R_DRIFT_VECTOR = -1 * Vector3D.Normalize(Vector3D.Reflect(DRIFT_VECTOR, INPUT_VECTOR)); R_DRIFT_VECTOR = ((Vector3D.Dot(R_DRIFT_VECTOR, INPUT_VECTOR) < -0.3)) ? 0 * R_DRIFT_VECTOR : R_DRIFT_VECTOR; INPUT_VECTOR = Vector3D.Normalize((4 * R_DRIFT_VECTOR) + INPUT_VECTOR); //Components Of Input Vector In FUR Axis //---------------------------------------- double F_COMP_IN = Vector_Projection(INPUT_VECTOR, RC.WorldMatrix.Forward); double U_COMP_IN = Vector_Projection(INPUT_VECTOR, RC.WorldMatrix.Up); double R_COMP_IN = Vector_Projection(INPUT_VECTOR, RC.WorldMatrix.Right); //Calculate MAX Allowable in Each Axis & Length //----------------------------------------------- double F_COMP_MAX = (F_COMP_IN > 0) ? CAF2_FORWARD.PositiveMaxForce : -1 * CAF2_FORWARD.NegativeMaxForce; double U_COMP_MAX = (U_COMP_IN > 0) ? CAF2_UP.PositiveMaxForce : -1 * CAF2_UP.NegativeMaxForce; double R_COMP_MAX = (R_COMP_IN > 0) ? CAF2_RIGHT.PositiveMaxForce : -1 * CAF2_RIGHT.NegativeMaxForce; double MAX_FORCE = Math.Sqrt(F_COMP_MAX * F_COMP_MAX + U_COMP_MAX * U_COMP_MAX + R_COMP_MAX * R_COMP_MAX); //Apply Length to Input Components and Calculates Smallest Multiplier //-------------------------------------------------------------------- double F_COMP_PROJ = F_COMP_IN * MAX_FORCE; double U_COMP_PROJ = U_COMP_IN * MAX_FORCE; double R_COMP_PROJ = R_COMP_IN * MAX_FORCE; double MULTIPLIER = 1; MULTIPLIER = (F_COMP_MAX / F_COMP_PROJ < MULTIPLIER) ? F_COMP_MAX / F_COMP_PROJ : MULTIPLIER; MULTIPLIER = (U_COMP_MAX / U_COMP_PROJ < MULTIPLIER) ? U_COMP_MAX / U_COMP_PROJ : MULTIPLIER; MULTIPLIER = (R_COMP_MAX / R_COMP_PROJ < MULTIPLIER) ? R_COMP_MAX / R_COMP_PROJ : MULTIPLIER; //Calculate Multiplied Components //--------------------------------- CAF2_FORWARD.VCF = ((F_COMP_PROJ * MULTIPLIER) / F_COMP_MAX) * Math.Sign(F_COMP_MAX); CAF2_UP.VCF = ((U_COMP_PROJ * MULTIPLIER) / U_COMP_MAX) * Math.Sign(U_COMP_MAX); CAF2_RIGHT.VCF = ((R_COMP_PROJ * MULTIPLIER) / R_COMP_MAX) * Math.Sign(R_COMP_MAX); //Runs System Thrust Application //---------------------------------- Dictionary <IMyThrust, float> THRUSTVALUES = new Dictionary <IMyThrust, float>(); foreach (var thruster in CAF2_THRUST) { THRUSTVALUES.Add((thruster as IMyThrust), 0f); } foreach (var THRUSTSYSTM in CAFTHI) { List <IMyThrust> POSTHRUST = THRUSTSYSTM.PositiveThrusters; List <IMyThrust> NEGTHRUST = THRUSTSYSTM.NegativeThrusters; if (THRUSTSYSTM.VCF < 0) { POSTHRUST = THRUSTSYSTM.NegativeThrusters; NEGTHRUST = THRUSTSYSTM.PositiveThrusters; } foreach (var thruster in POSTHRUST) { THRUSTVALUES[thruster as IMyThrust] = (float)(Math.Abs(THRUSTSYSTM.VCF)) * (thruster as IMyThrust).MaxThrust; } foreach (var thruster in NEGTHRUST) { THRUSTVALUES[thruster as IMyThrust] = 1; } //(float)0.01001;} foreach (var thruster in THRUSTVALUES) { thruster.Key.ThrustOverride = thruster.Value; } //thruster.Key.ThrustOverride = thruster.Value; } }
Boolean Dock3() { mode = 3; foreach (IMyThrust thruster in allThrusters) { thruster.ThrustOverridePercentage = 0; } rc.SetAutoPilotEnabled(false); foreach (IMyGyro gyro in gyros) { gyro.ApplyAction("OnOff_On"); } double yaw; double pitch; Boolean yawLock = false; Boolean pitchLock = false; GetRotationAngles(Vector3D.Negate(dockingDir), connector, out yaw, out pitch); ApplyGyroOverride(pitch, yaw, 0, gyros, connector); if (yaw < 0.01) { yawLock = true; } if (pitch < 0.01) { pitchLock = true; } Echo("yawLock:" + yawLock); Echo("pitchLock" + pitchLock); if (pitchLock && yawLock) { Vector3D closestPoint; double distanceFromDockingVector = DistanceFromVector(dockingConnectorPos, dockingDir, connector.GetPosition(), out closestPoint); Echo("Distance from docking vector:" + distanceFromDockingVector); if (distanceFromDockingVector > 0.35) { NewAdjustTest(closestPoint, connector, distanceFromDockingVector); } else if (distanceFromDockingVector == -1) { Echo("Error in docking vector distance calculation"); } else { float shipmass = rc.CalculateShipMass().TotalMass; if (rc.GetShipSpeed() < 1.5) { foreach (IMyThrust thruster in backThrusterGroup) { thruster.ThrustOverride = shipmass; } } else { foreach (IMyThrust thruster in backThrusterGroup) { thruster.ThrustOverridePercentage = 0; } } if (Vector3D.Distance(dockingConnectorPos, rc.GetPosition()) > errorDistance) { Storage = ""; dockingConnectorPos = new Vector3D(); dockingDir = new Vector3D(); mode = 0; globalPath.Clear(); rc.ClearWaypoints(); foreach (IMyThrust thrust in allThrusters) { thrust.ThrustOverridePercentage = 0; } foreach (IMyGyro gyro in gyros) { gyro.GyroOverride = false; gyro.Pitch = 0; gyro.Yaw = 0; gyro.Roll = 0; } Boolean sent = antenna.TransmitMessage("canceldock," + password); if (!sent) { messageQue.Add("canceldock," + password); } antenna.CustomName += " ERROR"; } } } if (connector.Status == MyShipConnectorStatus.Connectable) { connector.Connect(); mode = 5; globalPath.Clear(); foreach (IMyThrust thruster in allThrusters) { thruster.ThrustOverridePercentage = 0; } foreach (IMyGyro gyro in gyros) { gyro.Pitch = 0; gyro.Yaw = 0; gyro.Roll = 0; } return(true); } return(false); }
void GuideMissile() { missilePos = shipReference.GetPosition(); //---Get orientation vectors of our missile Vector3D missileFrontVec = shipReference.WorldMatrix.Forward; Vector3D missileLeftVec = shipReference.WorldMatrix.Left; Vector3D missileUpVec = shipReference.WorldMatrix.Up; //---Check if we have gravity double rollAngle = 0; double rollSpeed = 0; var remote = remotes[0] as IMyRemoteControl; gravVec = shipReference.GetNaturalGravity(); double gravMagSquared = gravVec.LengthSquared(); if (gravMagSquared != 0) { if (gravVec.Dot(missileUpVec) < 0) { // rollAngle = Math.PI / 2 - Math.Acos(MathHelper.Clamp(gravVec.Dot(missileLeftVec) / gravVec.Length(), -1, 1)); } else { // rollAngle = Math.PI + Math.Acos(MathHelper.Clamp(gravVec.Dot(missileLeftVec) / gravVec.Length(), -1, 1)); } } else { rollSpeed = 0; } //---Get travel vector var missileVelocityVec = shipReference.GetShipVelocities().LinearVelocity; double speed = shipReference.GetShipSpeed(); //---Find vector from missile to destinationVec Vector3D missileToTargetVec; if (speed > 10 ||) { missileToTargetVec = Vector3D.Negate(missileVelocityVec); } else { shipReference.TryGetPlanetPosition(out targetPos); missileToTargetVec = Vector3D.Negate(targetPos - missilePos); // targetPos - missilePos; } //---Calc our new heading based upon our travel vector var headingVec = CalculateHeadingVector(missileToTargetVec, missileVelocityVec, driftCompensation); //---Get pitch and yaw angles double yawAngle; double pitchAngle; GetRotationAngles(headingVec, missileFrontVec, missileLeftVec, missileUpVec, out yawAngle, out pitchAngle); logger.Info("mttv: " + missileToTargetVec); logger.Info("mvv: " + missileVelocityVec); logger.Info("hv: " + headingVec); if (firstGuidance) { lastPitchAngle = pitchAngle; lastYawAngle = yawAngle; firstGuidance = false; } //---Angle controller logger.Debug(yawAngle + "|" + lastYawAngle); double yawSpeed = Math.Round(proportionalConstant * yawAngle + derivativeConstant * (yawAngle - lastYawAngle) * 60, 3); double pitchSpeed = Math.Round(proportionalConstant * pitchAngle + derivativeConstant * (pitchAngle - lastPitchAngle) * 60, 3); //---Set appropriate gyro override if (speed <= 1E-2) { logger.Info("Fin"); ApplyGyroOverride(0, 0, 0, gyros, shipReference); Runtime.UpdateFrequency = UpdateFrequency.None; } else { logger.Info("V=" + missileVelocityVec.Length()); ApplyGyroOverride(pitchSpeed, yawSpeed, rollSpeed, gyros, shipReference); } //---Store previous values lastYawAngle = yawAngle; lastPitchAngle = pitchAngle; lastRollAngle = rollAngle; }
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); } }
private bool EvaluateCondition() { switch (currentCondition) { case Conditions.NONE: return(true); case Conditions.PGRA: double currentPGravity = control.GetNaturalGravity().Length(); switch (currentOperator) { case Operators.EQUAL: return(currentPGravity == value); case Operators.LESS: return(currentPGravity < value); case Operators.MORE: return(currentPGravity > value); } break; case Conditions.AGRA: double currentAGravity = control.GetArtificialGravity().Length(); switch (currentOperator) { case Operators.EQUAL: return(currentAGravity == value); case Operators.LESS: return(currentAGravity < value); case Operators.MORE: return(currentAGravity > value); } break; case Conditions.SPEED: double currentSpeed = control.GetShipSpeed(); switch (currentOperator) { case Operators.EQUAL: return(currentSpeed == value); case Operators.LESS: return(currentSpeed < value); case Operators.MORE: return(currentSpeed > value); } break; case Conditions.TIME: if (time == -1) { time = DateTime.Now.Millisecond; } if (DateTime.Now.Millisecond - time > value * 1000) { time = -1; return(true); } return(false); case Conditions.LOCATION: BoundingSphereD boundaries = control.CubeGrid.WorldVolume; return(boundaries.Contains(conditionGPS) != ContainmentType.Disjoint); } return(false); }