예제 #1
0
 void DrawOutput()
 {
     if (outputSurface == null)
     {
         return;
     }
     outputSurface.WriteText(string.Join("\n",
                                         "Waypath Recorder",
                                         "Recording: " + pathName,
                                         "Points: " + pathPoints.Count,
                                         "Position: " + mainControl.GetPosition(),
                                         "Direction: " + mainControl.WorldMatrix.GetOrientation().Forward
                                         ));
 }
예제 #2
0
        public bool RequestVelocityCheckCollisions()
        {
            if (RAI_SessionCore.IsServer == false || this.UseCollisionDetection == false)
            {
                this.VelocityResult = new CollisionCheckResult(false);
                return(false);
            }

            if (this.CubeGrid.Physics == null || this.CubeGrid.IsStatic == true)
            {
                this.VelocityResult = new CollisionCheckResult(false);
                return(false);
            }

            if (this.CubeGrid.Physics.LinearVelocity.Length() < 0.1f)
            {
                this.VelocityResult = new CollisionCheckResult(false);
                return(false);
            }

            this.RemoteControlPosition = RemoteControl.GetPosition();
            this.GridVelocity          = this.CubeGrid.Physics.LinearVelocity;
            return(true);
            //MyAPIGateway.Parallel.Start(CheckVelocityCollisionsThreaded, VelocityCollisionCheckFinish);
        }
예제 #3
0
        void HandleMessage()
        {
            while (directiveListener.HasPendingMessage)
            {
                var directive = GreedleDirective.FromJSON(JSON.Parse(directiveListener.AcceptMessage().As <string>()));
                switch (directive.type)
                {
                case GreedleDirective.DirectiveType.Respond:
                    IGC.SendBroadcastMessage(
                        "greedle_response",
                        JSON.Stringify(GreedleResponse.ToJSON(new GreedleResponse()
                    {
                        name     = name,
                        position = mainControl.GetPosition()
                    }))
                        ); break;

                case GreedleDirective.DirectiveType.Target:
                {
                    if (directive.targetDirective.addressedTo == name)
                    {
                        Target(directive.targetDirective.target);
                    }
                    break;
                }
                }
            }
        }
예제 #4
0
                public void LookAt(Vector3D target, IMyGyro gyro, IMyRemoteControl control)
                {
                    Vector3D offet = (target - control.GetPosition());

                    if (offet.Length() < 100.0f)
                    {
                        ApplyGyro(Vector3.Zero);
                        return;
                    }

                    Vector3 direction = Vector3D.Normalize(offet);

                    if (spaceship.gravity.LengthSquared() > 1e-1f)
                    {
                        Allign(direction, spaceship.gravity, gyro, control);
                    }
                    else
                    {
                        Quaternion quat = Quaternion.CreateFromForwardUp(control.WorldMatrix.Forward, control.WorldMatrix.Up);
                        quat.Conjugate();
                        direction = quat * direction;
                        Vector3.GetAzimuthAndElevation(direction, out azimuth, out elevation);
                        Vector3 final = Vector3.Transform(new Vector3(elevation, azimuth, 0.0f),
                                                          control.WorldMatrix.GetOrientation() * Matrix.Transpose(gyro.WorldMatrix.GetOrientation()));

                        ApplyGyro(-final);
                    }
                }
예제 #5
0
        public static void ChangeReputationWithPlayersInRadius(IMyRemoteControl remoteControl, double radius, List <int> amounts, List <string> factions, bool applyReputationChangeToFactionMembers)
        {
            if (amounts.Count != factions.Count)
            {
                Logger.MsgDebug("Could Not Do Reputation Change. Faction Tag and Rep Amount Counts Do Not Match");
                return;
            }

            var playerList = new List <IMyPlayer>();
            var playerIds  = new List <long>();

            MyAPIGateway.Players.GetPlayers(playerList);

            foreach (var player in playerList)
            {
                if (player.IsBot == true)
                {
                    continue;
                }

                if (Vector3D.Distance(player.GetPosition(), remoteControl.GetPosition()) > radius)
                {
                    continue;
                }

                if (player.IdentityId != 0 && !playerIds.Contains(player.IdentityId))
                {
                    playerIds.Add(player.IdentityId);
                }
            }

            ChangePlayerReputationWithFactions(amounts, playerIds, factions, applyReputationChangeToFactionMembers);
        }
예제 #6
0
        public void Main(string argument, UpdateType updateSource)
        {
            GridTerminalSystem.GetBlocksOfType <IMyGyro>(gyros);
            GridTerminalSystem.GetBlocksOfType <IMyRemoteControl>(controllers);
            GridTerminalSystem.GetBlocksOfType <IMySensorBlock>(sensors);

            if (controllers.Count < 1 || gyros.Count < 1)
            {
                Echo("ERROR: either no controller or gyro");
                return;
            }
            IMyRemoteControl controller = controllers[0];//

            //Vector2 yawAndRoll = controller.RotationIndicator;
            //Vector3 inputRotationVector = new Vector3(-yawAndRoll.X, yawAndRoll.Y, controller.RollIndicator);//pitch, yaw, roll. What?? ok.

            IMySensorBlock sensor = sensors[0];
            //Echo($"{sensor.LastDetectedEntity.Position}\n{sensor.LastDetectedEntity.Orientation}\n{sensor.LastDetectedEntity.Velocity}");
            //direction to the target
            Vector3D p1 = controller.GetPosition();
            Vector3D p2 = sensor.LastDetectedEntity.Position;
            Vector3D p3 = p2 - p1;

            //rotation to the target
            p3.Normalize();
            Vector3D heading = controller.WorldMatrix.Forward;

            heading.Normalize();
            double angle = Math.Acos(heading.Dot(p3));//this doesn't account for up vector for now

            Echo($"ANGLE:{angle}");
            Echo($"p3:{p3}");
            antenna.HudText = angle.ToString();
            //axis of rotation
            Vector3D cross = heading.Cross(p3);
            //var relativeRotation = Vector3D.Transform(cross, controller.WorldMatrix);

            double yaw; double pitch;

            GetRotationAngles(p3, controller.WorldMatrix.Forward, controller.WorldMatrix.Left, controller.WorldMatrix.Up, out yaw, out pitch);



            applyRotation(VECTOR@, gyros, controller);
            //turn axis into ship coordinates

            //calc the new matrix after that rotation

            //IF there is a gravity
            //calc angle to rotate by and axis of rotation, add that rotation to the rotation already underway
            //align the grav and up vector into the same plane...?
            //calc what my desired forward vector is(p3?), then

            //need to rotate and project up vector in line with art/nat gravity
            //Vector3D projection = a.Dot(b) / b.LengthSquared() * b;
            //applyRotation(inputRotationVector, gyros, controller);

            //keep this at the end
            previousShipVelicities = controllers[0].GetShipVelocities();
        }
예제 #7
0
            //Use For Precise Turning (docking, mining, attacking)
            //----------==--------=------------=-----------=---------------=------------=-----=-----*/
            void GyroTurn6(Vector3D TARGET, double GAIN, IMyGyro GYRO, IMyRemoteControl REF_RC, double ROLLANGLE, double MAXANGULARVELOCITY)
            {
                //确保自动驾驶仪没有功能
                REF_RC.SetAutoPilotEnabled(false);
                //检测前、上 & Pos
                Vector3D ShipForward = REF_RC.WorldMatrix.Forward;
                Vector3D ShipUp      = REF_RC.WorldMatrix.Up;
                Vector3D ShipPos     = REF_RC.GetPosition();

                //创建和使用逆Quatinion
                Quaternion Quat_Two               = Quaternion.CreateFromForwardUp(ShipForward, ShipUp);
                var        InvQuat                = Quaternion.Inverse(Quat_Two);
                Vector3D   DirectionVector        = Vector3D.Normalize(TARGET - ShipPos);         //RealWorld Target Vector
                Vector3D   RCReferenceFrameVector = Vector3D.Transform(DirectionVector, InvQuat); //Target Vector In Terms Of RC Block

                //转换为局部方位和高度
                double ShipForwardAzimuth = 0; double ShipForwardElevation = 0;

                Vector3D.GetAzimuthAndElevation(RCReferenceFrameVector, out ShipForwardAzimuth, out ShipForwardElevation);

                //Does Some Rotations To Provide For any Gyro-Orientation做一些旋转来提供任何旋转方向
                var RC_Matrix = REF_RC.WorldMatrix.GetOrientation();
                var Vector     = Vector3.Transform((new Vector3D(ShipForwardElevation, ShipForwardAzimuth, ROLLANGLE)), RC_Matrix); //Converts To World转换为世界
                var TRANS_VECT = Vector3.Transform(Vector, Matrix.Transpose(GYRO.WorldMatrix.GetOrientation()));                    //Converts To Gyro Local转换为陀螺仪方位

                //Applies To Scenario适用于场景
                GYRO.Pitch        = (float)MathHelper.Clamp((-TRANS_VECT.X * GAIN), -MAXANGULARVELOCITY, MAXANGULARVELOCITY);
                GYRO.Yaw          = (float)MathHelper.Clamp(((-TRANS_VECT.Y) * GAIN), -MAXANGULARVELOCITY, MAXANGULARVELOCITY);
                GYRO.Roll         = (float)MathHelper.Clamp(((-TRANS_VECT.Z) * GAIN), -MAXANGULARVELOCITY, MAXANGULARVELOCITY);
                GYRO.GyroOverride = true;

                //GYRO.SetValueFloat("Pitch", (float)((TRANS_VECT.X) * GAIN));
                //GYRO.SetValueFloat("Yaw", (float)((-TRANS_VECT.Y) * GAIN));
                //GYRO.SetValueFloat("Roll", (float)((-TRANS_VECT.Z) * GAIN));
            }
예제 #8
0
        public Vector3D GetBurnVector(Vector3D targetPosition, Vector3D targetVelocity, IMyRemoteControl core, Vector3 offset)
        {
            Vector3D targetVector = targetPosition - core.GetPosition();
            double   timeToTarget = targetVector.Length() / 100;

            return(targetVector + timeToTarget * (targetVelocity - 0.9 * core.GetShipVelocities().LinearVelocity));
        }
예제 #9
0
 Vector3D GetBurnVector(IMyRemoteControl core, bool oldSystem)
 {
     if (oldSystem)
     {
         Vector3D targetVector = predictedHitPoint - core.GetPosition();
         targetVector.Normalize();
         targetVector = targetVector * 120;
         Vector3D velocity      = core.GetShipVelocities().LinearVelocity;
         Vector3D correctVector = targetVector - velocity;
         return(correctVector + core.GetPosition());
     }
     else
     {
         Vector3D targetVector = predictedPosition - core.GetPosition();
         return(targetVector + timeToTarget * (TargetInfo.Velocity - 0.9 * core.GetShipVelocities().LinearVelocity));
     }
 }
예제 #10
0
        public Crawler(RoboticArm leftBack, RoboticArm leftFront, RoboticArm rightBack, RoboticArm rightFront, IMyRemoteControl rc)
        {
            LeftBack   = leftBack;
            LeftFront  = leftFront;
            RightBack  = rightBack;
            RightFront = rightFront;
            Rc         = rc;

            StepIndent = new []
            {
                GetAverageArmSegmentLength(LeftBack),
                GetAverageArmSegmentLength(LeftFront),
                GetAverageArmSegmentLength(RightBack),
                GetAverageArmSegmentLength(RightFront),
            }.Average() *StepIndentMultiplier;

            // getting local positions of leg base rotation rotors
            var lb = VectorUtility.GetLocalVector(Rc.WorldMatrix, Rc.GetPosition(), LeftBack.RotorRotation.Rotor.GetPosition());
            var lf = VectorUtility.GetLocalVector(Rc.WorldMatrix, Rc.GetPosition(), LeftFront.RotorRotation.Rotor.GetPosition());
            var rb = VectorUtility.GetLocalVector(Rc.WorldMatrix, Rc.GetPosition(), RightBack.RotorRotation.Rotor.GetPosition());
            var rf = VectorUtility.GetLocalVector(Rc.WorldMatrix, Rc.GetPosition(), RightFront.RotorRotation.Rotor.GetPosition());

            Center = VectorUtility.GetAverageVector(
                VectorUtility.GetAverageVector(lb, lf),
                VectorUtility.GetAverageVector(rb, rf));

            lb -= Center;
            lf -= Center;
            rb -= Center;
            rf -= Center;

            LbMarchPoint = VectorUtility.Normalize(lb) * (StepIndent + lb.Length());
            LfMarchPoint = VectorUtility.Normalize(lf) * (StepIndent + lf.Length());
            RbMarchPoint = VectorUtility.Normalize(rb) * (StepIndent + rb.Length());
            RfMarchPoint = VectorUtility.Normalize(rf) * (StepIndent + rf.Length());

            Lbh = new Vector3D(LbMarchPoint.X, LbMarchPoint.Y - 0.5, LbMarchPoint.Z);
            Lfh = new Vector3D(LfMarchPoint.X, LfMarchPoint.Y - 0.5, LfMarchPoint.Z);
            Rbh = new Vector3D(RbMarchPoint.X, RbMarchPoint.Y - 0.5, RbMarchPoint.Z);
            Rfh = new Vector3D(RfMarchPoint.X, RfMarchPoint.Y - 0.5, RfMarchPoint.Z);

            Lbs = new Vector3D(LbMarchPoint.X, LbMarchPoint.Y - 1.5, LbMarchPoint.Z + 3);
            Lfs = new Vector3D(LfMarchPoint.X, LfMarchPoint.Y - 1.5, LfMarchPoint.Z - 3);
            Rbs = new Vector3D(RbMarchPoint.X, RbMarchPoint.Y - 1.5, RbMarchPoint.Z + 3);
            Rfs = new Vector3D(RfMarchPoint.X, RfMarchPoint.Y - 1.5, RfMarchPoint.Z - 3);
        }
예제 #11
0
        //IsTargetBroadcasting
        public static bool IsTargetBroadcasting(IMyCubeGrid cubeGrid, IMyRemoteControl sourceBlock, bool checkAntennas, bool checkBeacons)
        {
            var gts = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(cubeGrid);

            if (checkAntennas == true)
            {
                List <IMyRadioAntenna> antennaList = new List <IMyRadioAntenna>();
                gts.GetBlocksOfType <IMyRadioAntenna>(antennaList);

                foreach (var antenna in antennaList)
                {
                    if (antenna.IsWorking == true && antenna.IsFunctional == true && antenna.IsBroadcasting == true)
                    {
                        var distToNPC = (float)Vector3D.Distance(sourceBlock.GetPosition(), antenna.GetPosition());

                        if (antenna.Radius >= distToNPC)
                        {
                            return(true);
                        }
                    }
                }
            }

            if (checkBeacons == true)
            {
                List <IMyBeacon> beaconList = new List <IMyBeacon>();
                gts.GetBlocksOfType <IMyBeacon>(beaconList);

                foreach (var beacon in beaconList)
                {
                    if (beacon.IsWorking == true && beacon.IsFunctional == true)
                    {
                        var distToNPC = (float)Vector3D.Distance(sourceBlock.GetPosition(), beacon.GetPosition());

                        if (beacon.Radius >= distToNPC)
                        {
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
예제 #12
0
 public bool getGravityVector(out Vector3D gravity)
 {
     gravity = Vector3D.Zero;
     if (_init())
     {
         return(true);
     }
     rc.TryGetPlanetPosition(out gravity);
     gravity -= rc.GetPosition();
     gravity.Normalize();
     return(false);
 }
예제 #13
0
        public List <ITarget> AcquireBlockTarget()
        {
            var result = new List <ITarget>();

            foreach (var grid in GridManager.Grids)
            {
                if (!grid.ActiveEntity())
                {
                    continue;
                }

                if (grid.IsSameGrid(RemoteControl.SlimBlock.CubeGrid))
                {
                    continue;
                }

                if (grid.Distance(RemoteControl.GetPosition()) > Data.MaxDistance)
                {
                    continue;
                }

                grid.GetBlocks(result, Data.BlockTargets);
            }

            return(result);
        }
예제 #14
0
        public void KeepMoving()
        {
            var lbd = State == 1 ? Lbs : Lbh;
            var lfd = State == 1 ? Lfh : Lfs;
            var rbd = State == 1 ? Rbh : Rbs;
            var rfd = State == 1 ? Rfs : Rfh;

            lbd = VectorUtility.GetWorldPoint(Rc.WorldMatrix, Rc.GetPosition(), lbd + Center);
            lfd = VectorUtility.GetWorldPoint(Rc.WorldMatrix, Rc.GetPosition(), lfd + Center);
            rbd = VectorUtility.GetWorldPoint(Rc.WorldMatrix, Rc.GetPosition(), rbd + Center);
            rfd = VectorUtility.GetWorldPoint(Rc.WorldMatrix, Rc.GetPosition(), rfd + Center);

            if (NearDest(LeftBack, lbd) && NearDest(LeftFront, lfd) && NearDest(RightBack, rbd) && NearDest(RightFront, rfd))
            {
                FlipState();
            }

            LeftBack.KeepMoving(lbd, 2);
            LeftFront.KeepMoving(lfd, 2);
            RightBack.KeepMoving(rbd, 2);
            RightFront.KeepMoving(rfd, 2);

            var pts = new[]
            {
                lbd, lfd, rbd, rfd, LeftBack.Tip.GetPosition(), LeftFront.Tip.GetPosition(),
                RightBack.Tip.GetPosition(), RightFront.Tip.GetPosition()
            };

            var str = "";
            int i   = 1;

            foreach (var p in pts)
            {
                str += VectorUtility.ToLabel(p, i.ToString()) + "\n";
                i++;
            }

            Rc.CustomData = str;
        }
예제 #15
0
    protected IMyEntity GetClosestEnemy(float maxSearchRadius) {
      if (!Active) {
        return null;
      }
      IMyFaction selfFaction = m_remote.CubeGrid.GetOwningFaction();

      BoundingSphereD bounds = new BoundingSphereD(m_remote.GetPosition(), maxSearchRadius);
      List<IMyEntity> possibleEnemies = MyAPIGateway.Entities.GetEntitiesInSphere(ref bounds);
      double minDist = double.MaxValue;
      IMyEntity closest = null;
      foreach (IMyEntity entity in possibleEnemies) {
        if(entity == m_remote.CubeGrid) {
          continue;
        }
        Vector3D position = entity.GetPosition();
        IMyFaction objectFaction = null;
        if (entity is IMyCubeGrid) {
          IMyCubeGrid grid = entity as IMyCubeGrid;
          objectFaction = grid.GetOwningFaction();
        } else if (entity is IMyPlayer) {
          IMyPlayer player = entity as IMyPlayer;
          objectFaction = MyAPIGateway.Session.Factions.TryGetPlayerFaction(player.IdentityId);
        }

        if (objectFaction == null) {
          continue;
        }
        MyRelationsBetweenFactions relation = MyAPIGateway.Session.Factions.GetRelationBetweenFactions(selfFaction.FactionId, objectFaction.FactionId);
        if (relation.Equals(MyRelationsBetweenFactions.Enemies)) {
          double dist = m_remote.GetPosition().DistanceTo(position);
          if(dist < minDist) {
            minDist = dist;
            closest = entity;
          }
        }
      }
      return closest;
    }
예제 #16
0
        void Move(Path path)
        {
            Vector3D targetVelocity = path.Velocity;
            Vector3D myPos          = rc.GetPosition();

            Vector3D difference = path.Position - myPos;
            double   diffLen    = difference.Length();

            thrust.Velocity = difference + targetVelocity;
            thrust.Update();

            gyros.FaceVectors(path.Forward, path.Up);
            path.Update();
        }
        /// <summary>
        /// Возвращает углы наводки на цель
        /// </summary>
        /// <param name="Target">координаты точки, нак оторую требуется доводка</param>
        /// <returns></returns>
        private Vector3D GetNavAngles(Vector3D Target)
        {
            Vector3D V3DCenter = remCon.GetPosition();
            Vector3D V3Dfow    = remCon.WorldMatrix.Forward;
            Vector3D V3Dup     = remCon.WorldMatrix.Up;
            Vector3D V3Dleft   = remCon.WorldMatrix.Left;

            Vector3D TargetNorm = Vector3D.Normalize(Target - V3DCenter);

            double TargetPitch = Math.Acos(Vector3D.Dot(V3Dup, TargetNorm)) - (Math.PI / 2);
            double TargetYaw   = Math.Acos(Vector3D.Dot(V3Dleft, TargetNorm)) - (Math.PI / 2);
            double TargetRoll  = 0.0f;

            return(new Vector3D(TargetYaw, -TargetPitch, TargetRoll));
        }
예제 #18
0
    Vector3D GetNavAngles(Vector3D target)
    {
        Vector3D center = remCon.GetPosition();
        Vector3D fwd    = remCon.WorldMatrix.Forward;
        Vector3D up     = remCon.WorldMatrix.Up;
        Vector3D left   = remCon.WorldMatrix.Left;

        Vector3D targetNorm  = Vector3D.Normalize(target - center);
        double   targetPitch = Math.Acos(Vector3D.Dot(up, targetNorm)) - (Math.PI / 2);
        double   targetYaw   = Math.Acos(Vector3D.Dot(left, targetNorm)) - (Math.PI / 2);
        double   targetRoll  = 0;

        textPanel.WritePublicText("Yaw: " + Math.Round(targetYaw, 4) +
                                  "\n Pitch: " + Math.Round(targetPitch, 4) + "\n Roll: " + Math.Round(targetRoll, 4));

        return(new Vector3D(targetYaw, -targetPitch, targetRoll));///////////////////////////////////////
    }
            public void Tick()
            {
                p.Echo(new Vector3D(0, 0, 0).ToString());
                Controller.GetWaypointInfo(Waypoints);
                var pos = Controller.GetPosition();

                //var target = Vector3D.TransformNormal(new Vector3D(10, 0, 0), MatrixD.Transpose(Controller.WorldMatrix));
                p.Echo("Pos: " + pos.ToString());
                if (Waypoints.Any())
                {
                    var point = Waypoints.First();

                    p.Echo("Distance to waypoint: " + Vector3D.Distance(pos, point.Coords).ToString());
                }

                //p.Echo("test: " + Vector3D.Add(pos, target));
            }
예제 #20
0
        public void Main(string args)
        {
            if (args.StartsWith("AntennaPosition"))
            {
                Echo("Recived message");
                Vector3 coords;
                if (StringToVector3(args, out coords))
                {
                    var currentPos = remoteControl.GetPosition();

                    if ((currentPos - coords).Length() < NotDisturbDistance)
                    {
                        remoteControl.SetAutoPilotEnabled(false);
                    }
                    remoteControl.ClearWaypoints();
                    remoteControl.AddWaypoint(coords, "Destination");
                    Echo($"Move to {coords.ToString()}");
                    remoteControl.SetAutoPilotEnabled(true);
                }
            }
        }
예제 #21
0
            Vector3 ToLocalSpherical(Vector3D target, IMyRemoteControl core)
            {
                Vector3D targetVector = target - core.GetPosition();
                double   front        = targetVector.Dot(core.WorldMatrix.Forward) + offset.X;
                double   right        = targetVector.Dot(core.WorldMatrix.Right) + offset.Y;
                double   up           = targetVector.Dot(core.WorldMatrix.Up) + offset.Z;
                double   deltaAzimuth = Math.Atan(right / front);
                double   planelength  = front / Math.Cos(deltaAzimuth);
                double   elevation    = Math.Atan(up / planelength);
                double   length       = planelength / Math.Cos(elevation);

                if (front < 0)
                {
                    deltaAzimuth += Math.PI;
                    elevation     = -elevation;
                }
                if (deltaAzimuth > Math.PI)
                {
                    deltaAzimuth -= 2 * Math.PI;
                }
                return(new Vector3(length, deltaAzimuth, elevation));
            }
예제 #22
0
        public void ProcessCommandReceiveTriggerWatcher(string commandCode, IMyRemoteControl senderRemote, double radius, long entityId)
        {
            if (!_behavior.IsAIReady())
            {
                return;
            }

            if (senderRemote?.SlimBlock?.CubeGrid == null || this.RemoteControl?.SlimBlock?.CubeGrid == null)
            {
                return;
            }

            var antenna = BlockHelper.GetActiveAntenna(this.AntennaList);

            if (antenna == null)
            {
                return;
            }

            if (Vector3D.Distance(this.RemoteControl.GetPosition(), senderRemote.GetPosition()) > radius)
            {
                return;
            }

            for (int i = 0; i < this.CommandTriggers.Count; i++)
            {
                var trigger = this.CommandTriggers[i];

                if (trigger.UseTrigger == true && commandCode == trigger.CommandReceiveCode)
                {
                    trigger.ActivateTrigger();

                    if (trigger.Triggered == true)
                    {
                        ProcessTrigger(trigger, entityId, true);
                    }
                }
            }
        }
예제 #23
0
        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;
            }
        }
예제 #25
0
            //Primary Generic Functions
            //==========================

            //Use For General Drone Flying:
            void RC_Manager(Vector3D TARGET, IMyRemoteControl RC, bool TURN_ONLY)
            {
                //Uses Rotation Control To Handle Max Rotational Velocity
                //---------------------------------------------------------
                if (RC.GetShipVelocities().AngularVelocity.AbsMax() > PrecisionMaxAngularVel)
                {
                    print("转动速度放缓"); RC.SetAutoPilotEnabled(false); return;
                }
                //Setup Of Common Variables
                //--------------------------------------------
                Vector3D DronePosition   = RC.GetPosition();
                Vector3D Drone_To_Target = Vector3D.Normalize(TARGET - DronePosition);
                //Override Direction Detection
                //-------------------------------
                double To_Target_Angle = Vector3D.Dot(Vector3D.Normalize(RC.GetShipVelocities().LinearVelocity), Drone_To_Target);
                double Ship_Velocity   = RC.GetShipVelocities().LinearVelocity.Length();

                //Turn Only: (Will drift ship automatically)
                //--------------------------------------------

                /*List<MyWaypointInfo> way = new List<MyWaypointInfo>();
                 *      RC.GetWaypointInfo(way);
                 *      if (way.Count>0)
                 *      {
                 *          if (way[0].Coords!= TARGET)
                 *          {
                 *              //RC.ApplyAction("AutoPilot_Off");
                 *              //RC.ClearWaypoints();
                 *          }
                 *      }*/

                if (TURN_ONLY)
                {
                    //if (way.Count <1)
                    {
                        RC.ClearWaypoints();
                        GYRO.GyroOverride = false;
                        RC.AddWaypoint(TARGET, "母船起点");
                        RC.FlightMode = FlightMode.OneWay;
                        RC.Direction  = Base6Directions.Direction.Forward;
                        RC.ApplyAction("AutoPilot_On");
                        RC.ApplyAction("CollisionAvoidance_Off");
                        RC.ControlThrusters = false;
                    }
                    return;
                }
                //Drift Cancellation Enabled:
                //-----------------------------
                if (To_Target_Angle < 0.4 && Ship_Velocity > 3)
                {
                    //Aim Gyro To Reflected Vector
                    Vector3D DRIFT_VECTOR           = Vector3D.Normalize(RC.GetShipVelocities().LinearVelocity);
                    Vector3D REFLECTED_DRIFT_VECTOR = -1 * (Vector3D.Normalize(Vector3D.Reflect(DRIFT_VECTOR, Drone_To_Target)));
                    Vector3D AIMPINGPOS             = (-1 * DRIFT_VECTOR * 500) + DronePosition;

                    //if (way.Count < 1 )
                    {
                        RC.ClearWaypoints();
                        GYRO.GyroOverride = false;
                        RC.AddWaypoint(AIMPINGPOS, "AIMPINGPOS");
                        RC.SpeedLimit = 100;
                        RC.FlightMode = FlightMode.OneWay;
                        RC.Direction  = Base6Directions.Direction.Forward;
                        RC.ApplyAction("AutoPilot_On");
                        RC.ApplyAction("CollisionAvoidance_Off");
                    }
                }

                //System Standard Operation:
                //---------------------------
                else
                {
                    //Assign To RC, Clear And Refresh Command
                    List <ITerminalAction> action = new List <ITerminalAction>();
                    RC.GetActions(action);
                    RC.ControlThrusters = true;
                    RC.ClearWaypoints();
                    GYRO.GyroOverride = false;
                    RC.AddWaypoint(TARGET, "目标");
                    RC.SpeedLimit = 100;
                    RC.FlightMode = FlightMode.OneWay;
                    RC.Direction  = Base6Directions.Direction.Forward;
                    RC.ApplyAction("AutoPilot_On");
                    RC.ApplyAction("DockingMode_Off");
                    RC.ApplyAction("CollisionAvoidance_On");
                }
            }
예제 #26
0
            private void FirstTimeSetup(IMyRemoteControl rc)
            {
                try
                {
                    RC1 = rc;
                    myGridTerminal.GetBlocksOfType <IMyOreDetector>(oreDetectors, b => b.CubeGrid == RC1.CubeGrid);
                    myGridTerminal.GetBlocksOfType <IMyCameraBlock>(cameraBlocks, b => b.CubeGrid == RC1.CubeGrid);
                    myGridTerminal.GetBlocksOfType <IMyBatteryBlock>(batteryBlocks, b => b.CubeGrid == RC1.CubeGrid);
                    myGridTerminal.GetBlocksOfType <IMyRadioAntenna>(RadioAntennas, b => b.CubeGrid == RC1.CubeGrid);
                    if (cameraBlocks.Count > 0)
                    {
                        cameraBlock = cameraBlocks[0];
                    }
                    myGridTerminal.GetBlocksOfType(mySmallMissiles, b => b.CubeGrid == RC1.CubeGrid);
                    myGridTerminal.GetBlocksOfType(mySmallGatlings, b => b.CubeGrid == RC1.CubeGrid);
                    myGridTerminal.GetBlocksOfType(myLargeTurrets, b => b.CubeGrid == RC1.CubeGrid);
                }
                catch (Exception e)
                {
                    print(e.Message);
                }
                try
                {
                    List <IMyTerminalBlock> TEMP_CON = new List <IMyTerminalBlock>();
                    myGridTerminal.GetBlocksOfType <IMyShipConnector>(TEMP_CON, b => b.CubeGrid == RC1.CubeGrid && b.CustomName.Contains("Ejector") == false);
                    CONNECTOR1 = TEMP_CON[0] as IMyShipConnector;
                }
                catch { }
                try
                {
                    List <IMyTerminalBlock> TEMP_GYRO = new List <IMyTerminalBlock>();
                    myGridTerminal.GetBlocksOfType <IMyGyro>(TEMP_GYRO, b => b.CubeGrid == RC1.CubeGrid);
                    GYRO = TEMP_GYRO[0] as IMyGyro;
                }
                catch { }

                //Initialising Dedicated Cargo
                try
                {
                    myGridTerminal.GetBlocksOfType <IMyCargoContainer>(Cargo, b => b.CubeGrid == RC1.CubeGrid);
                }
                catch
                { }

                //Gathers Antennae
                try
                {
                    List <IMyTerminalBlock> TEMP = new List <IMyTerminalBlock>();
                    myGridTerminal.GetBlocksOfType <IMyRadioAntenna>(TEMP, b => b.CubeGrid == RC1.CubeGrid);
                    RADIO = TEMP[0] as IMyRadioAntenna;
                    RADIO.SetValue <long>("PBList", RC1.EntityId);
                    RADIO.EnableBroadcasting = true;
                    RADIO.Enabled            = true;
                }
                catch { }

                //GathersControllers
                try
                {
                    myGridTerminal.GetBlocksOfType <IMyShipController>(CONTROLLERS, b => b.CubeGrid == RC1.CubeGrid);
                }
                catch { }

                //Gathers Director Turret
                try
                {
                    myGridTerminal.GetBlocksOfType <IMyLargeTurretBase>(DIRECTORS, b => b.CubeGrid == RC1.CubeGrid);
                }
                catch { }

                //Gathers Drills
                try
                {
                    myGridTerminal.GetBlocksOfType <IMyShipDrill>(SHIP_DRILLS, b => b.CubeGrid == RC1.CubeGrid);
                }
                catch { }

                //Gathers Directional Weaponry
                try
                {
                    myGridTerminal.GetBlocksOfType <IMyUserControllableGun>(DIRECTIONAL_FIRE,
                                                                            (block =>
                                                                             (
                                                                                 block.GetType().Name == "MySmallMissileLauncher" ||
                                                                                 block.GetType().Name == "MySmallGatlingGun" ||
                                                                                 block.GetType().Name == "MySmallMissileLauncherReload"
                                                                             ) &&
                                                                             block.CubeGrid == RC1.CubeGrid)
                                                                            ); //Collects the directional weaponry (in a group)
                }
                catch { }
                //Runs Thruster Setup
                try
                {
                    CollectAndFire2(new Vector3D(), 0, 0, RC1.GetPosition(), RC1);
                    for (int j = 0; j < CAF2_THRUST.Count; j++)
                    {
                        CAF2_THRUST[j].SetValue <float>("Override", 0.0f); CAF2_THRUST[j].ApplyAction("OnOff_On");
                    }
                }
                catch { }
            }
예제 #27
0
            Vector3D dockPos3 = new Vector3D(); //Straight Up And Forward Location
            private void DockingIterator(bool Docking, List <Vector3D> COORDINATES, IMyGyro GYRO, IMyShipConnector CONNECTOR, IMyRemoteControl RC)
            {
                if (COORDINATES.Count < 3)
                {
                    return;
                }

                int TargetID  = 0;
                int CurrentID = 0;
                int iter_er   = 0;

                if (Docking == true)
                {
                    TargetID = 1; CurrentID = 0; iter_er = +1;
                }
                if (Docking == false)
                {
                    TargetID = 0; CurrentID = 1; iter_er = -1;
                }

                if (Docking == true)
                {
                    CONNECTOR.Connect();
                }
                if (Docking == true && CONNECTOR.IsWorking == false)
                {
                    CONNECTOR.Enabled = true;
                }
                if (Docking == false && CONNECTOR.IsWorking == true)
                {
                    CONNECTOR.Disconnect(); CONNECTOR.Enabled = true;
                }
                if (CONNECTOR.Status == MyShipConnectorStatus.Connected && Docking == true)
                {
                    for (int j = 0; j < CAF2_THRUST.Count; j++)
                    {
                        (CAF2_THRUST[j] as IMyThrust).Enabled = false;
                    }
                    GYRO.GyroOverride = false;
                    return;
                }
                Vector3D RollOrienter        = Vector3D.Normalize(COORDINATES[COORDINATES.Count - 1] - COORDINATES[COORDINATES.Count - 2]);
                Vector3D Connector_Direction = -1 * ReturnConnectorDirection(CONNECTOR, RC);
                double   RollReqt            = (float)(0.6 * (Vector3D.Dot(RollOrienter, Connector_Direction)));

                //垂直运动在码头
                if (COORD_ID == COORDINATES.Count - 1)
                {
                    Vector3D DockingHeading = Vector3D.Normalize(COORDINATES[COORDINATES.Count - 3] - COORDINATES[COORDINATES.Count - 2]) * 9000000; //Heading
                    GyroTurn6(DockingHeading, RotationalSensitvity, GYRO, RC, RollReqt, PrecisionMaxAngularVel);                                     //Turn to heading
                    if (Vector3D.Dot(RC.WorldMatrix.Forward, Vector3D.Normalize(DockingHeading)) > 0.98)                                             //Error check for small rotational velocity
                    {
                        Vector_Thrust_Manager(COORDINATES[COORD_ID - TargetID], COORDINATES[COORD_ID - CurrentID], CONNECTOR.GetPosition(), 5, 0.7, RC);
                    }                                                                                                                                     //Thrusts to point
                }

                //在码头上的最后/第一个外部Coord
                else if (COORD_ID == 0)
                {
                    print($"启动自动驾驶\n距离目标:{Vector3D.Distance(COORDINATES[0], RC.GetPosition())}");
                    RC_Manager(COORDINATES[0], RC, false);
                }

                //水平和迭代语句
                else
                {
                    var HEADING = Vector3D.Normalize(COORDINATES[COORD_ID - CurrentID] - COORDINATES[COORD_ID - TargetID]) * 9000000;
                    Vector_Thrust_Manager(COORDINATES[COORD_ID - TargetID], COORDINATES[COORD_ID - CurrentID], CONNECTOR.GetPosition(), 8, 1, RC); //Runs docking sequence
                    GyroTurn6(HEADING, RotationalSensitvity, GYRO, RC, RollReqt, PrecisionMaxAngularVel);
                }

                //逻辑检查和迭代
                if (Docking == false && COORD_ID == 0)
                {
                }
                else if ((CONNECTOR.GetPosition() - COORDINATES[COORD_ID - CurrentID]).Length() < 1 || ((RC.GetPosition() - COORDINATES[COORD_ID - CurrentID]).Length() < 10 && COORD_ID == 0))
                {
                    COORD_ID = COORD_ID + iter_er;
                    if (COORD_ID == COORDINATES.Count)
                    {
                        COORD_ID = COORDINATES.Count - 1;
                    }
                    if (COORD_ID < 0)
                    {
                        COORD_ID = 0;
                    }
                }
            }
예제 #28
0
        public void Main(string argument, UpdateType updateType)
        {
            Vector3D homebase         = new Vector3D(coord[0], coord[1], coord[2]);
            Vector3D homebasevelocity = new Vector3D(velocityout[0], velocityout[1], velocityout[2]);
            MatrixD  m = brain.WorldMatrix;
            Matrix   test;



            switch (argument.ToLower())
            {
            case "auto":
                brain.SetAutoPilotEnabled(true);
                brain.SetCollisionAvoidance(true);
                brain.DampenersOverride = true;
                Echo("Auto Pilot Enabled.");
                break;

            case "stop":
                brain.SetAutoPilotEnabled(false);
                brain.SetCollisionAvoidance(false);
                brain.DampenersOverride = false;
                Echo("Auto Pilot Disabled.");
                break;
            }



            info.WritePublicText("");
            info.WritePublicText(brain.CalculateShipMass().TotalMass.ToString() + " : Mass \n", true);

            //calculate manhattan distance
            int dist = (int)Math.Ceiling(Math.Abs(homebase.X - brain.GetPosition().X) + Math.Abs(homebase.Y - brain.GetPosition().Y) + Math.Abs(homebase.Z - brain.GetPosition().Z));

            info.WritePublicText(dist.ToString() + " :Distance \n", true);
            //debugging to an lcd screen - used as a visual aid
            info.WritePublicText(m.Forward.X.ToString(), true);

            //found out how to use and turn gyro
            //if (dist < 20 && m.Forward.X < 0.1)
            //{
            //    gyro.SetValueFloat("Yaw", 2);
            //    gyro.GetActionWithName("Override").Apply(gyro);
            //}

            //check for new homebase coords
            if (listeners[0].HasPendingMessage)
            {
                packet = listeners[0].AcceptMessage();
                string messagetext = packet.Data.ToString();
                sentcord = messagetext;
            }

            //check for new homebase velocity
            if (listeners[1].HasPendingMessage)
            {
                packet = listeners[1].AcceptMessage();
                string messagetext1 = packet.Data.ToString();
                sentvelocity = messagetext1;
            }
            string[] coords = sentcord.Split(' ');
            if (coords[0] != "")
            {
                coord[0] = double.Parse(coords[0].Remove(0, 2));
                coord[1] = double.Parse(coords[1].Remove(0, 2));
                coord[2] = double.Parse(coords[2].Remove(0, 2));
            }

            string[] velocity = sentvelocity.Split(' ');
            if (velocity[0] != "")
            {
                velocityout[0] = double.Parse(velocity[0].Remove(0, 2));
                velocityout[1] = double.Parse(velocity[1].Remove(0, 2));
                velocityout[2] = double.Parse(velocity[2].Remove(0, 2));
            }
            GetPredictedTargetPosition(homebase, homebasevelocity);

            //add new thrusters to list
            for (int i = 0; i < term.Count; i++)
            {
                onGridThrust.Add((IMyThrust)term[i]);
            }
        }
예제 #29
0
 internal Vector3D GetPosition()
 {
     return(remoteControl.GetPosition());
 }
예제 #30
0
        void Main()
        {
            //check if current RC is damaged, look for a replacement
            if (_currentControl == null || !_currentControl.IsFunctional)
            {
                _currentControl = _controllers.FirstOrDefault(c => c.IsFunctional);
            }

            if (_currentControl == null)
            {
                return; //no controls left :(
            }
            //Check Player Distance From Origin
            _currentControl.ClearWaypoints();
            Vector3D currentPos = _currentControl.GetPosition();
            Vector3D closestPlayer;

            _currentControl.GetNearestPlayer(out closestPlayer);

            double playerDistanceOrigin = Vector3D.DistanceSquared(closestPlayer, _origin);
            double playerDistanceDrone  = Vector3D.DistanceSquared(currentPos, closestPlayer);

            if (playerDistanceDrone < BREAKAWAY_DISTANCE * BREAKAWAY_DISTANCE || playerDistanceOrigin < PATROL_RADIUS * PATROL_RADIUS)
            {
                //Chase Player
                _currentControl.AddWaypoint(closestPlayer, "Player");

                //update guns
                if (USE_STATIC_GUNS)
                {
                    if (playerDistanceDrone <= WEAPON_ENGAGE_DIST * WEAPON_ENGAGE_DIST)
                    {
                        Vector3D playerDir = closestPlayer - currentPos;
                        playerDir.Normalize();
                        double dot = Vector3D.Dot(_currentControl.WorldMatrix.Forward, playerDir);
                        //check if player is inside our target cone
                        if (dot > _weaponAngle)
                        {
                            StartShooting();
                            _shooting = true;
                        }
                        else
                        {
                            StopShooting();
                            _shooting = false;
                        }
                    }
                    else if (playerDistanceDrone > WEAPON_DISENGAGE_DIST * WEAPON_DISENGAGE_DIST && _shooting)
                    {
                        StopShooting();
                        _shooting = false;
                    }
                }
            }
            else
            {
                //Go To Origin
                _currentControl.AddWaypoint(_origin, "Origin");
                if (_shooting && USE_STATIC_GUNS)
                {
                    _shooting = false;
                    StopShooting();
                }
            }

            _currentControl.SetAutoPilotEnabled(true);
        }