public bool Main()
            {
                var tmpList = new List <MyDetectedEntityInfo>();

                foreach (IMySensorBlock sensor in sensors)
                {
                    if (sensor.IsActive)
                    {
                        tmpList.Add(sensor.LastDetectedEntity);
                    }
                }

                double distance = 0;

                foreach (MyDetectedEntityInfo info in tmpList)
                {
                    double tmpDist = Vector3D.Distance(rc.GetPosition(), info.Position);

                    if (tmpDist <= distance || distance == 0)
                    {
                        closest           = info;
                        distance          = tmpDist;
                        DistanceToClosest = Math.Round(tmpDist, 2);
                    }
                }

                if (distance != 0)
                {
                    return(true);
                }

                return(false);
            }
示例#2
0
        void TargetingSystem()
        {
            MyDetectedEntityInfo?turretTarget = null;
            double turretDist = 0;

            if (turretMonitor != null && useTurretLockon && turretMonitor.Turretcount > 0)
            {
                turretTarget = turretMonitor.Scan();
                if (turretTarget.HasValue)
                {
                    turretDist = Vector3D.DistanceSquared(rc.GetPosition(), turretTarget.Value.Position);
                }
            }

            if (useTurretLockon && turretDist > 750 * 750)
            {
                if (longRangeDetection == null && turretTarget.HasValue)
                {
                    NewLongRangeDetection(turretTarget.Value.Position);
                }
            }

            if (turretTarget == null || turretDist > 750 * 750)
            {
                longRangeDetection?.DoDetect();
            }
        }
示例#3
0
            private IEnumerator <bool> TargetingRoutine()
            {
                if (control.GetNaturalGravity() == Vector3D.Zero && control.GetShipSpeed() < 2)         // Easy
                {
                    quartic = new QuarticTargeting(control.GetVelocityVector(), control.GetPosition(), maxProjectileVel);

                    Vector3D?result = quartic.CalculateTrajectory(target);
                    if (result.HasValue)
                    {
                        onRoutineFinish?.Invoke(result.Value);
                    }
                    else
                    {
                        onRoutineFail?.Invoke();
                    }

                    yield return(false);
                }
                else                                                                                  // This may take a while...
                {
                    double timescale      = 0.1;
                    var    projectileInfo = new AdvancedSimTargeting.ProjectileInfo(200, maxProjectileVel, timescale, control.GetPosition(), control.GetVelocityVector());
                    simTargeting = new AdvancedSimTargeting(projectileInfo, target, control, ingameTime, 25, true, maxProjectileVel, timescale);
                    simTargeting.onSimComplete += OnSimValid;
                    simTargeting.onSimFail     += OnSimFail;

                    yield return(true);

                    while (keepRunning)
                    {
                        simTargeting.Tick();
                        yield return(true);
                    }
                }
            }
 protected Vector3D GetVectorToTarget()
 {
     if (destination == null || destination.ToVector3D().IsZero())
     {
         return(Vector3D.Zero);
     }
     return(destination.ToVector3D() - referenceBlock.GetPosition());
 }
示例#5
0
            public void TargetPosition(Vector3D position, MyDetectedEntityInfo planet)
            {
                Vector3D startPos  = reference.GetPosition();
                Vector3D direction = Vector3D.Normalize(position - startPos);

                simTargeting                = new Simulated_Targeting(reference, position, startPos, direction, 0, planet, 9.81, launchVelocity, speedCap);
                simTargeting.tolerance      = tolerance;
                simTargeting.negationFactor = 0.001;

                fireCallbackOnce = false;
            }
示例#6
0
            public void Main()
            {
                if (started)
                {
                    ticks++;

                    speed += rc.GetShipSpeed();

                    distanceTravelled += (long)Math.Round(Vector3D.Distance(prevLoc, rc.GetPosition()));
                    prevLoc            = rc.GetPosition();
                }
            }
示例#7
0
 public static Planet GetBestGuessFromInitialData(IMyShipController remote)
 {
     if (!double.IsNaN(remote.GetNaturalGravity().Length()))
     {
         Planet   p = new Planet();
         Vector3D center;
         remote.TryGetPlanetPosition(out center);
         p.Center = center;
         double curdist = Vector3D.Distance(center, remote.GetPosition());
         double sealevelelevation;
         double curgrav = remote.GetNaturalGravity().Length();
         remote.TryGetPlanetElevation(MyPlanetElevation.Sealevel, out sealevelelevation);
         p.Radius            = curdist - sealevelelevation;
         p.GravityMathNumber = curgrav * Math.Pow(curdist, p.GravityExponent);
         if (curdist > p.Radius * (1 + p.HillParameter))
         {
             double mathvalue = curgrav * Math.Pow(curdist, p.GravityExponent);
             p.SurfaceGravity = mathvalue / Math.Pow(p.Radius * p.HillParameter + p.Radius, p.GravityExponent);
         }
         else
         {
             p.SurfaceGravity = curgrav;
         }
         return(p);
     }
     return(null);
 }
示例#8
0
        private void SpawnConvoy(IMyShipController baseToSpawnAt)
        {
            var factionId       = baseToSpawnAt.OwnerId;
            var spawnerPosition = baseToSpawnAt.GetPosition();
            var gravity         = baseToSpawnAt.GetNaturalGravity();
            var unitType        = baseToSpawnAt.CustomName.Contains("GROUND") ? UnitType.Ground : UnitType.Air;
            var cargoSize       = heatSystem.GenerateCargoShipSize();

            //TODO: Should let base define the convoy spawn points
            //TODO: gravity is not normalized and is being used to scale the spawn point...  It should be normalized and then meters used to modify.
            // NOTE: The .Forward IS normalized, so the scalar is in meters.
            if (unitType == UnitType.Air)
            {
                var positionToSpawn = spawnerPosition + gravity * -5f + baseToSpawnAt.WorldMatrix.Forward * 30;
                var transportPrefab = PrefabGrid.GetAirTransport(cargoSize);
                DuckUtils.SpawnInGravity(positionToSpawn, gravity, factionId, transportPrefab.PrefabName,
                                         transportPrefab.InitialBeaconName,
                                         Vector3D.Normalize(baseToSpawnAt.WorldMatrix.Forward));
            }
            else
            {
                var positionToSpawn = spawnerPosition + gravity * -1f + baseToSpawnAt.WorldMatrix.Forward * 35;
                var transportPrefab = PrefabGrid.GetGroundTransport(cargoSize);
                DuckUtils.SpawnInGravity(positionToSpawn, gravity, factionId, transportPrefab.PrefabName,
                                         transportPrefab.InitialBeaconName,
                                         Vector3D.Normalize(baseToSpawnAt.WorldMatrix.Forward));
            }
        }
示例#9
0
        public void SpawnConvoyTransport(IMyShipController baseToSpawnAt)
        {
            var factionId       = baseToSpawnAt.OwnerId;
            var spawnerPosition = baseToSpawnAt.GetPosition();
            var gravity         = baseToSpawnAt.GetNaturalGravity();
            var unitType        = baseToSpawnAt.CustomName.Contains("GROUND") ? UnitType.Ground : UnitType.Air;
            var cargoSize       = heatSystem.GenerateCargoShipSize();

            if (unitType == UnitType.Air)
            {
                var positionToSpawn = spawnerPosition + gravity * -5f + baseToSpawnAt.WorldMatrix.Forward * 30;
                var transportPrefab = CalPrefabFactory.GetAirTransport(cargoSize);
                DuckUtils.SpawnInGravity(positionToSpawn, gravity, factionId, transportPrefab.PrefabName,
                                         transportPrefab.InitialBeaconName,
                                         Vector3D.Normalize(baseToSpawnAt.WorldMatrix.Forward));
            }
            else
            {
                var positionToSpawn = spawnerPosition + gravity * -1f + baseToSpawnAt.WorldMatrix.Forward * 35;
                var transportPrefab = CalPrefabFactory.GetGroundTransport(cargoSize);
                DuckUtils.SpawnInGravity(positionToSpawn, gravity, factionId, transportPrefab.PrefabName,
                                         transportPrefab.InitialBeaconName,
                                         Vector3D.Normalize(baseToSpawnAt.WorldMatrix.Forward));
            }
        }
        public void Main(string argument)
        {
            TAG = (argument.Trim().Length > 0) ? argument : TAG;
            IMyShipController       OriginCockpit  = findPilotedCockpit();
            Vector3D                origin         = (OriginCockpit != null) ? OriginCockpit.GetPosition() : Me.GetPosition();
            List <IMyRemoteControl> RemoteControls = new List <IMyRemoteControl>();
            List <IMyTextPanel>     TextPanels     = new List <IMyTextPanel>();

            GridTerminalSystem.GetBlocksOfType <IMyRemoteControl>(RemoteControls, (x => x.CubeGrid.Equals(Me.CubeGrid) && x.CustomName.Contains(TAG)));
            GridTerminalSystem.GetBlocksOfType <IMyTextPanel>(TextPanels, (x => x.CubeGrid.Equals(Me.CubeGrid) && x.CustomName.Contains(TAG)));
            if (TextPanels.Count > 0 && RemoteControls.Count > 0)
            {
                StringBuilder Distances = new StringBuilder();
                foreach (IMyRemoteControl RemoteControl in RemoteControls)
                {
                    List <MyWaypointInfo> Waypoints = new List <MyWaypointInfo>();
                    RemoteControl.GetWaypointInfo(Waypoints);
                    foreach (MyWaypointInfo Waypoint in Waypoints)
                    {
                        Distances.AppendLine(formatDistance(Vector3D.Distance(origin, Waypoint.Coords)) + ": " + Waypoint.Name);
                    }
                }
                foreach (IMyTextPanel TextPanel in TextPanels)
                {
                    TextPanel.WritePublicText(((TextPanel.GetPublicTitle().Trim().Length > 0)? TextPanel.GetPublicTitle().Trim() + "\n":"") + Distances.ToString());
                    TextPanel.ShowPublicTextOnScreen();
                }
            }
        }
示例#11
0
 public void Update(long tick)
 {
     _thisDestination.From = _thisController.GetPosition() + (_thisController.WorldMatrix.Up * 1);
     _thisDestination.Set();
     _draw.DrawLine(_thisDestination);
     _draw.Update(tick);
 }
            private float GetEdgeDistance(IMyShipController reference, Vector3D direction)
            {
                Vector3D edgeDirection = GetShipEdgeVector(reference, direction);
                Vector3D edgePos       = reference.GetPosition() + edgeDirection;

                return((float)Vector3D.Distance(reference.CenterOfMass, edgePos));
            }
示例#13
0
            public void Update(Vector3D target)
            {
                MatrixD transpose = MatrixD.Transpose(rc.WorldMatrix);

                Vector3D meToTarget = rc.WorldMatrix.Translation - target;
                Vector3D localError = Vector3D.TransformNormal(meToTarget, transpose);

                localError.Y = 0;
                if (localError.X > -0.5 && localError.X < 0.5)
                {
                    localError.X = 0;
                }
                if (localError.Z > -0.5 && localError.Z < 0.5)
                {
                    localError.Z = 0;
                }

                float correction = (float)forwardPID.Control(localError.Z);
                float force      = correction * rc.CalculateShipMass().TotalMass;

                float    rightLeft     = (float)anglePID.Control(-localError.X);
                Vector3D localVelocity = Vector3D.TransformNormal(rc.GetShipVelocities().LinearVelocity, transpose);
                float    angle         = -rightLeft;

                if (localVelocity.Z < 0)
                {
                    angle *= -1;
                }

                foreach (Wheel w in wheels)
                {
                    IMyMotorSuspension wheel = w.block;
                    if (first)
                    {
                        Vector3D center = Vector3D.TransformNormal(rc.CenterOfMass - rc.GetPosition(), transpose);
                        Vector3D local  = Vector3D.TransformNormal(wheel.GetPosition() - rc.GetPosition(), transpose);
                        wheel.InvertSteer      = (local.Z > center.Z);
                        wheel.InvertPropulsion = (wheel.Orientation.Left != rc.Orientation.Forward);
                        wheel.Brake            = false;
                    }

                    if (wheel.Steering)
                    {
                        wheel.SetValueFloat("Steer override", angle);
                    }

                    if (wheel.Propulsion)
                    {
                        float maxForce = w.maxForce;
                        if (maxForce <= 0)
                        {
                            continue;
                        }
                        float percent = MathHelper.Clamp(force / maxForce, -1, 1);
                        force -= percent * maxForce;
                        wheel.SetValueFloat("Propulsion override", percent);
                    }
                }
                first = false;
            }
示例#14
0
        //public void Update(ProjectorVisualization proj)
        public void Update()
        {
            if (!Enabled)
            {
                return;
            }

            Vector3D down     = controller.GetNaturalGravity();
            Vector3D shipDown = controller.WorldMatrix.Down;

            if (Vector3D.IsZero(down))
            {
                //gravity is zero, means we're not in gravity well.
                if (DisableOnNaturalGravityExit && startedInNaturalGravity)
                {
                    Stop();
                    return;
                }
                else
                {
                    //Align to velocity vector
                    down = controller.GetShipVelocities().LinearVelocity;
                }
            }

            Vector3D locationInGrid  = Vector3D.Transform(controller.GetPosition() + Vector3.Normalize(down), MatrixD.Invert(controller.WorldMatrix)) / controller.CubeGrid.GridSize;
            Vector3D locationInGrid2 = Vector3D.Transform(controller.GetPosition() + Vector3.Normalize(shipDown), MatrixD.Invert(controller.WorldMatrix)) / controller.CubeGrid.GridSize;

            //screen.WriteText(locationInGrid.ToString("n3"));
            //screen.WriteText("\n" + locationInGrid2.ToString("n3"), true);

            Vector3D striveForZero = locationInGrid - locationInGrid2;

            striveForZero *= 5;             //Increase speed in aligning

            //screen.WriteText("\n" + striveForZero.ToString("n3"), true);
            //screen.WriteText("\n" + controller.RotationIndicator.Y.ToString("n3"), true);

            ApplyGyroOverride(-striveForZero.Z, controller.RotationIndicator.Y, -striveForZero.X, gyros, controller as IMyTerminalBlock);


            //proj.UpdatePosition(controller.GetPosition() + (Vector3.Normalize(controller.GetNaturalGravity()) * 10));
            //proj.UpdatePosition(controller.GetPosition() + (Vector3.Normalize(controller.WorldMatrix.Down) * 10));
        }
示例#15
0
            private double UpdatePosition()
            {
                this.Position         = controlReference.GetPosition();
                this.RelativeVelocity = -Vector3D.TransformNormal((controlReference.GetShipVelocities().LinearVelocity), MatrixD.Transpose(controlReference.WorldMatrix));
                this.RelativeTarget   = Vector3D.TransformNormal(this.Position - this.Objective.GetValueOrDefault(), MatrixD.Transpose(controlReference.WorldMatrix));

                double destination = Math.Sqrt(Math.Pow(RelativeTarget.X, 2) + Math.Pow(RelativeTarget.Z, 2));

                uIManager.printOnScreens("service", "DIST: " + destination + " - " + precisionFactor);
                return(destination);
            }
示例#16
0
 public Drill(IMyShipController reference, float drillVelocity = 1.5f, float asteroidDetectSize = 1.5f, float epsilon = 0.1f)
     : base(reference)
 {
     _state             = _uninitializedState;
     _lastWorldPosition = reference.GetPosition();
     _stateBehavior[_uninitializedState] = UpdateUninitialized;
     _stateBehavior[_standbyState]       = UpdateStandby;
     _stateBehavior[_searchState]        = UpdateSearch;
     _stateBehavior[_drillState]         = UpdateDrill;
     _drillVelocity     = drillVelocity;
     _astroidDetectSize = asteroidDetectSize;
     _epsilon           = epsilon;
 }
示例#17
0
        //Finds Currently Detected Enemy Location
        #region Enemy Scan #RFC#

        /*=================================================
         * Function: RFC Function bar #RFC#
         * ---------------------------------------     */
        Vector3D EnemyScan(MISSILE This_Missile)
        {
            //Targeting Module
            //-----------------------------------------------

            //Retrieves Target Position
            var This_Missile_Director = This_Missile.TURRET as IMyLargeTurretBase;
            var ENEMY_POS             = new Vector3D();

            //LOS as first call
            if (TOWCamera != null)
            {
                Vector3D Scanpos = RC.WorldMatrix.Forward * TOW_Distance;
                if (TOWCamera.CanScan(Scanpos))
                {
                    TemporaryTarget = new MyDetectedEntityInfo();
                    var ThisEntity = TOWCamera.Raycast(Scanpos);
                    if (ThisEntity.Relationship == MyRelationsBetweenPlayerAndBlock.Enemies)
                    {
                        TemporaryTarget = ThisEntity;
                        ENEMY_POS       = (Vector3D)TemporaryTarget.HitPosition;
                    }
                }
            }


            //Turret Detection As Secondary
            else if (This_Missile_Director.GetTargetedEntity().IsEmpty() == false && !(OverrideToLongTargets && TemporaryTarget.IsEmpty()))
            {
                ENEMY_POS = This_Missile_Director.GetTargetedEntity().Position;     //Also based on position for critical hits
            }

            //Finally If nothing Detected on turrets default to LOS with some basic prediction
            else
            {
                if (!TemporaryTarget.IsEmpty())
                {
                    double   TimeSinceFired = (TemporaryTarget.TimeStamp - DateTime.Now.Millisecond) / 1000.00;
                    Vector3D Velocity       = (Vector3D)TemporaryTarget.Velocity;
                    ENEMY_POS = (Vector3D)TemporaryTarget.HitPosition + Velocity * TimeSinceFired;
                }

                //OtherWise Straigh Up TOW
                else
                {
                    ENEMY_POS = RC.GetPosition() + RC.WorldMatrix.Forward * ((This_Missile.GYRO.GetPosition() - Me.GetPosition()).Length() + 300);
                }
            }

            return(ENEMY_POS);
        }
            private bool IsEnemyInRange(MyDetectedEntityInfo info)
            {
                if (info.IsEmpty())
                {
                    return(false);
                }

                if (info.Relationship != MyRelationsBetweenPlayerAndBlock.Enemies && info.Relationship != MyRelationsBetweenPlayerAndBlock.Neutral)
                {
                    return(false);
                }

                return(Vector3D.DistanceSquared(info.Position, rc.GetPosition()) < detonationDist);
            }
示例#19
0
        public void OnEntityDetected(HaE_Entity entity)
        {
            if (Vector3D.DistanceSquared(entity.entityInfo.Position, control.GetPosition()) > 1000 * 1000)
            {
                return;
            }

            if (IgnoreEventAfterOnce)
            {
                return;
            }

            if (control.GetShipSpeed() < maxActiveRotorGunVel)
            {
                gridCannonTargeting.NewTarget(entity.entityInfo);
            }
            else
            {
                foreach (var cannon in rotorTurretGroups)
                {
                    cannon.TargetDirection(ref Vector3D.Zero);
                }
            }

            statusWriter.UpdateStatus(StatusWriter.TargetingStatus.Targeting);

            missileCannonTargeting.NewTarget(entity.entityInfo);
            basicTargeting.UpdateValues(control.GetVelocityVector(), control.GetPosition(), maxGatlingBulletVel);
            var result = basicTargeting.CalculateTrajectory(entity.entityInfo);

            if (result.HasValue)
            {
                TargetSolvedGatling(result.Value);
            }

            IgnoreEventAfterOnce = true;
        }
            public bool Scan(double distance)
            {
                bool detected = false;

                foreach (var direction in localScanMap)
                {
                    Vector3D worldDirection = VectorUtils.TransformDirLocalToWorld(rc.WorldMatrix, direction);
                    Vector3D worldPos       = rc.GetPosition() + worldDirection * distance;

                    HaE_Entity entity = trackingModule.PaintTarget(worldPos);
                    if (entity != null)
                    {
                        detected = true;
                    }
                }

                return(detected);
            }
示例#21
0
            public void SetTargetDirection(Vector3D direction, double howFarOut)
            {
                //Normalize dis
                Vector3D NewTarget = direction;

                NewTarget.Normalize();

                //Set the lenght of Newtarget to howFarOut in M
                NewTarget = Vector3D.Multiply(NewTarget, howFarOut);

                //create waypoint out in the targetDirection
                NewTarget = cockpit.GetPosition() + NewTarget;

                if (!target.Equals(NewTarget))
                {
                    target = NewTarget;
                }
            }
示例#22
0
        //Begin Methods
        private bool ClearAndGather()
        {
            MainController = null;
            Remotes.Clear();

            Antennae.Clear();
            Weapons.Clear();
            Waypoints.Clear();
            Gears.Clear();

            GridTerminalSystem.GetBlocksOfType(Antennae);
            if (IsDirector)
            {
                GridTerminalSystem.GetBlocksOfType(Remotes, x => x.CubeGrid == Me.CubeGrid);
                //TODO タグ付け対応
                if (Remotes.Count == 0)
                {
                    Echo("No Remote Controller Found.");
                    return(false);
                }
                MainController = Remotes[0];

                GblPosition = Vector3D.Round(MainController.GetPosition());
                GblPosition = RefPosition + GblPosition;
            }
            else
            {
                GridTerminalSystem.GetBlocksOfType(Remotes, x => x.CubeGrid == Me.CubeGrid);
                if (Remotes.Count == 0)
                {
                    Echo("No Remote Controller Found.");
                    return(false);
                }
                GblPosition = Vector3D.Round(Remotes[0].GetPosition());
                Remotes[0].GetWaypointInfo(Waypoints);
                GridTerminalSystem.GetBlocksOfType(Weapons, x => x.CubeGrid == Me.CubeGrid);
                GridTerminalSystem.GetBlocksOfType(Gears, x => x.CubeGrid == Me.CubeGrid);
            }

            return(true);
        }
        void UpdateAlarms(TimeSpan localTime)
        {
            var  intelItems = IntelProvider.GetFleetIntelligences(localTime);
            bool hasEnemy   = false;

            foreach (var kvp in intelItems)
            {
                if (kvp.Key.Item1 == IntelItemType.Enemy && IntelProvider.GetPriority(kvp.Key.Item2) > 1 && (kvp.Value.GetPositionFromCanonicalTime(localTime + IntelProvider.CanonicalTimeDiff) - Controller.GetPosition()).Length() < alertDist)
                {
                    hasEnemy = true;
                    break;
                }
            }

            Alarm = hasEnemy;

            if (hasEnemy && AutoScramble)
            {
                Attack(localTime);
            }
        }
示例#24
0
            private Vector3D CalculateTargetVector(MyDetectedEntityInfo info)
            {
                ///prediction = position + velocity * time + 0.5 * acceleration * time * time
                ///time ~ 1.5(s)*distance(m)/1000
                ///

                float    distance     = (float)Vector3D.Distance(cockpit.GetPosition(), info.Position);
                float    time         = 1.5f * distance / 1000;
                Vector3D displacement = ToVector3D(info.Velocity) * time;
                Vector3D targetVector = info.Position + displacement;
                //Vector3D targetVector = info.Position;

                /// Own velocity correction TESTED ON 300
                var      velocities = cockpit.GetShipVelocities();
                Vector3D mySpeed    = velocities.LinearVelocity;

                targetVector = targetVector + mySpeed * -1 * distance / 2500;

                //_program.Echo($"T:{time}");
                return(targetVector);
            }
示例#25
0
 public void NotReady()
 {
     StartElev = Elev;
     SeaLevel  = MinR;
     RControllers.SetAutoPilotEnabled(false);
     RControllers.FlightMode = FlightMode.OneWay;
     RControllers.Direction  = Base6Directions.Direction.Forward;
     RControllers.SpeedLimit = 200;
     StartLocation           = RController.GetPosition();
     RControllers.ClearWaypoints();
     GyroStartLocation = RGyro.GetPosition();
     RConStartLocation = RCon.GetPosition();
     RefDist           = Math.Round(Vector3D.Distance(GyroStartLocation, StartLocation), 2);               //Distance between RC and Gyro
     Distance          = ((GyroStartLocation - StartLocation) * ((TargetAltitude - StartElev) / RefDist)); //Calculates Distance to Target
     TargetLocation    = (StartLocation + Distance);                                                       ////Calculates Co-ords for Target
     RefDist           = Math.Round(Vector3D.Distance(RConStartLocation, StartLocation), 2);               //Distance between RC and Gyro
     Distance          = ((RConStartLocation - StartLocation) * ((AppTarget + StartElev) / RefDist));      //Calculates Distance to Approach (1000m)
     AppLocation       = (StartLocation + Distance);                                                       ////Calculates Co-ords for Target
     RControllers.AddWaypoint(TargetLocation, (Ship + "Target Location"));
     Init = true;
     Main("Ready");
     return;
 }
示例#26
0
            public Point(IMyShipController rc, bool vel, bool rot)
            {
                if (vel)
                {
                    position = rc.GetPosition();
                    velocity = rc.GetShipVelocities().LinearVelocity;
                }
                else
                {
                    position = null;
                    velocity = null;
                }

                if (rot)
                {
                    forward = rc.WorldMatrix.Forward;
                    up      = rc.WorldMatrix.Up;
                }
                else
                {
                    forward = null;
                    up      = null;
                }
            }
示例#27
0
        bool GetBlocks()
        {
            UpdateConfig(Me);

            bool setupFailed = false;

            gyros.Clear();
            allThrusters.Clear();
            brakingThrusters.Clear();
            otherThrusters.Clear();
            shipControllers.Clear();
            statusScreens.Clear();
            merges.Clear();
            landingTimers.Clear();

            GridTerminalSystem.GetBlocksOfType(shipControllers, block => block.CustomName.ToLower().Contains(referenceName.ToLower()));
            GridTerminalSystem.GetBlocksOfType(gyros);
            GridTerminalSystem.GetBlocksOfType(allThrusters);
            GridTerminalSystem.GetBlocksOfType(landingTimers, block => block.CustomName.ToLower().Contains(landingTimerName.ToLower()));

            if (shipControllers.Count == 0)
            {
                setupFailed = true;
                Echo($"CRITICAL: No ship controllers with the name '{referenceName}' were found");
            }
            else
            {
                //---Assign our remote control
                referenceBlock = shipControllers[0] as IMyShipController;
                GetThrusterOrientation(referenceBlock);
            }

            if (brakingThrusters.Count == 0)
            {
                setupFailed = true;
                Echo("CRITICAL: No downwards thrusters were found");
            }

            if (gyros.Count == 0)
            {
                setupFailed = true;
                Echo($"CRITICAL: No gyroscopes were found");
            }

            if (landingTimers.Count == 0)
            {
                Echo($"Optional: No landing timers found");
            }

            if (setupFailed)
            {
                Echo("Setup Failed!");
                return(false);
            }
            else
            {
                Echo("Setup Successful!");
                var edgeDirection = GetShipEdgeVector(referenceBlock, referenceBlock.WorldMatrix.Down);
                var edgePos       = referenceBlock.GetPosition() + edgeDirection;
                shipHeight = Vector3D.Distance(referenceBlock.CenterOfMass, edgePos);
                return(true);
            }
        }
示例#28
0
        void Main()
        {
            // initialize
            var blocks = new List <IMyTerminalBlock>();

            if (counter == 0)
            {
                GridTerminalSystem.GetBlocksOfType <IMyShipController>(blocks, FilterShipController);

                if (blocks.Count == 0)
                {
                    throw new Exception("Did not find any cockpit.");
                }

                controller = blocks[0] as IMyShipController;
                debug.Append("use ").Append(controller.CustomName).Append(':').AppendLine();

                perpBlocks = Utils.FindPerpendicularTo(controller);

                ship       = new ShipController(controller);
                worldCoord = controller.GetPosition();
                debug.Append("POSITION = ").Append(worldCoord).AppendLine();

                Debug(debug.ToString());
                debug.Clear();
                counter++;
                return;
            }

            worldCoord = new VRageMath.Vector3D(0, 0, 0);

            bool orthogonal = perpBlocks.Count == 3;

            VRageMath.Matrix toWorld = orthogonal ? Utils.toWorld(GridTerminalSystem.Blocks) : Utils.toWorld(perpBlocks);

            blocks = new List <IMyTerminalBlock>();
            GridTerminalSystem.GetBlocksOfType <IMyThrust>(blocks);
            GridTerminalSystem.GetBlocksOfType <IMyGyro>(blocks);

            debug.Append("worldCoord = ").Append(VRageMath.Vector3I.Round(worldCoord)).AppendLine();
            debug.Append("controller.GetPosition() = ").Append(VRageMath.Vector3I.Round(controller.GetPosition())).AppendLine();
            debug.Append("controller.Position = ").Append(controller.Position).AppendLine();

            debug.Append("transfrom controller.Position = ").Append(VRageMath.Vector3I.Round(VRageMath.Vector3.Transform(controller.Position, toWorld))).AppendLine();
            debug.Append("transfrom controller.Position = ").Append(VRageMath.Vector3I.Round(VRageMath.Vector3.Transform(controller.GetPosition(), VRageMath.Matrix.Invert(toWorld)))).AppendLine();

            VRageMath.Vector3 worldDir = worldCoord - controller.GetPosition();
            float             distance = worldDir.LengthSquared() > 0 ? worldDir.Normalize() : 0;

            debug.Append("distance = ").Append(distance).AppendLine();
            debug.Append("direction = ").Append(worldDir).AppendLine();

            VRageMath.Matrix worldController = new VRageMath.Matrix();
            controller.Orientation.GetMatrix(out worldController);
            worldController = worldController * toWorld;
            debug.Append("worldController = ").AppendLine();
            debug.Append(worldController.Right).AppendLine();
            debug.Append(worldController.Up).AppendLine();
            debug.Append(worldController.Backward).AppendLine();
            debug.Append(worldController.Translation).AppendLine();
            debug.Append("origin worldController = ").Append(VRageMath.Vector3I.Round(VRageMath.Vector3.Transform(new VRageMath.Vector3(), worldController))).AppendLine();
            //VRageMath.Vector3 n = orthogonal ? worldController.Right : worldController.Up.Cross(worldController.Backward);
            //VRageMath.Vector3 projDir = worldDir - worldDir.Dot(n) / n.Dot(n) * n;
            //if (projDir.LengthSquared() > 0)
            //    projDir.Normalize();

            //VRageMath.Vector3 eY = worldController.Up;
            //eY.Normalize();
            //VRageMath.Vector3 eZ = worldController.Backward;
            //eZ.Normalize();

            //float cosinePhiY = eY.Dot(projDir);
            //float cosinePhiZ = eZ.Dot(projDir);

            //float pitch = (float)(cosinePhiY > 0 ? -Math.Acos(cosinePhiZ) : Math.Acos(cosinePhiZ));
            ////VRageMath.Matrix.AlignRotationToAxes();
            //debug.Append("pitch = ").Append(pitch).AppendLine();

            debug.Append("worldController.IsRotation() = ").Append(worldController.IsRotation());
            VRageMath.Matrix  toAlign = VRageMath.Matrix.CreateFromDir(worldDir, worldController.Up);
            VRageMath.Matrix  align   = VRageMath.Matrix.AlignRotationToAxes(ref toAlign, ref worldController);
            VRageMath.Vector3 xyz     = new VRageMath.Vector3();
            VRageMath.Matrix.GetEulerAnglesXYZ(ref align, out xyz);
            xyz = 0.1f * xyz;

            debug.Append(xyz).AppendLine();
            ship.UpdateBlocks(blocks);
            ship.Stop();
            ship.Rotate(Identity.Left, xyz.GetDim(0));
            ship.Rotate(Identity.Down, xyz.GetDim(1));
            ship.Rotate(Identity.Forward, xyz.GetDim(2));

            Debug(debug.ToString());
            debug.Clear();
        }
示例#29
0
        void Main()
        {
            // initialize
            var blocks = new List <IMyTerminalBlock>();

            GridTerminalSystem.GetBlocksOfType <IMyShipController>(blocks, FilterShipController);

            if (blocks.Count == 0)
            {
                throw new Exception("Did not find any cockpit.");
            }

            controller = blocks[0] as IMyShipController;
            debug.Append("use ").Append(controller.CustomName).Append(':').AppendLine();

            perpBlocks = Utils.FindPerpendicularTo(controller);

            for (int i = 0; i < perpBlocks.Count; ++i)
            {
                var block = perpBlocks[i];
                debug.Append(block.Position).AppendLine();
            }

            VRageMath.Vector3 cur  = perpBlocks[1].Position - perpBlocks[0].Position;
            VRageMath.Vector3 next = perpBlocks[2].Position - perpBlocks[0].Position;
            debug.Append(VRageMath.Vector3.ArePerpendicular(ref cur, ref next)).AppendLine();

            worldCoord = new VRageMath.Vector3D(0, 0, 0);

            bool orthogonal = perpBlocks.Count == 3;

            VRageMath.Matrix  toWorld = orthogonal ? Utils.toWorld(perpBlocks) : Utils.toWorld(GridTerminalSystem.Blocks);
            VRageMath.Vector3 r       = toWorld.Right;
            VRageMath.Vector3 u       = toWorld.Up;
            VRageMath.Vector3 b       = toWorld.Backward;

            debug.Append(r.Dot(u)).AppendLine();
            debug.Append(u.Dot(b)).AppendLine();
            debug.Append(b.Dot(r)).AppendLine();

            debug.Append(VRageMath.Vector3.ArePerpendicular(ref r, ref u)).AppendLine();
            debug.Append(VRageMath.Vector3.ArePerpendicular(ref u, ref b)).AppendLine();
            debug.Append(VRageMath.Vector3.ArePerpendicular(ref b, ref r)).AppendLine();

            blocks = new List <IMyTerminalBlock>();
            GridTerminalSystem.GetBlocksOfType <IMyThrust>(blocks);
            GridTerminalSystem.GetBlocksOfType <IMyGyro>(blocks);

            debug.Append("worldCoord = ").Append(VRageMath.Vector3I.Round(worldCoord)).AppendLine();
            debug.Append("controller.GetPosition() = ").Append(VRageMath.Vector3I.Round(controller.GetPosition())).AppendLine();
            debug.Append("controller.Position = ").Append(controller.Position).AppendLine();

            debug.Append("transfrom controller.Position = ").Append(VRageMath.Vector3I.Round(VRageMath.Vector3.Transform(controller.Position, toWorld))).AppendLine();
            debug.Append("transfrom controller.GetPosition() = ").Append(VRageMath.Vector3I.Round(VRageMath.Vector3.Transform(controller.GetPosition(), VRageMath.Matrix.Invert(toWorld)))).AppendLine();
            debug.Append("transfrom zero = ").Append(VRageMath.Vector3I.Round(VRageMath.Vector3.Transform(worldCoord, VRageMath.Matrix.Invert(toWorld)))).AppendLine();

            VRageMath.Vector3 worldDir = worldCoord - controller.GetPosition();
            float             distance = worldDir.LengthSquared() > 0 ? worldDir.Normalize() : 0;

            debug.Append("distance = ").Append(distance).AppendLine();
            debug.Append("direction = ").Append(worldDir).AppendLine();

            VRageMath.Matrix worldController = new VRageMath.Matrix();
            controller.Orientation.GetMatrix(out worldController);
            worldController = worldController * VRageMath.Matrix.CreateTranslation(controller.Position) * toWorld;

            debug.Append("worldController = ").AppendLine();
            debug.Append(worldController.Right).AppendLine();
            debug.Append(worldController.Up).AppendLine();
            debug.Append(worldController.Backward).AppendLine();
            debug.Append(worldController.Translation).AppendLine();

            VRageMath.Vector3 a        = worldController.Forward;
            VRageMath.Matrix  rotation = Utils.CalculateRotation(ref worldDir, ref a);

            debug.Append((double)Math.Abs(rotation.Right.Dot(rotation.Up))).AppendLine();
            debug.Append((double)Math.Abs(rotation.Right.Dot(rotation.Backward))).AppendLine();
            debug.Append((double)Math.Abs(rotation.Up.Dot(rotation.Backward))).AppendLine();

            debug.Append("rotation transl+persp = ").Append(rotation.HasNoTranslationOrPerspective()).AppendLine();
            debug.Append("rotation rotation = ").Append(rotation.IsRotation()).AppendLine();
            debug.Append(rotation.Right).AppendLine();
            debug.Append(rotation.Up).AppendLine();
            debug.Append(rotation.Backward).AppendLine();
            debug.Append(rotation.Translation).AppendLine();

            VRageMath.Vector3 xyz = new VRageMath.Vector3();
            VRageMath.Matrix.GetEulerAnglesXYZ(ref rotation, out xyz);

            debug.Append("X = ").Append(xyz.GetDim(0)).AppendLine();
            debug.Append("Y = ").Append(xyz.GetDim(1)).AppendLine();
            debug.Append("Z = ").Append(xyz.GetDim(2)).AppendLine();

            Debug(debug.ToString());
            debug.Clear();
        }
示例#30
0
            public void Capture()
            {
                int  phase         = phasetemp;
                bool freedirection = true;

                var worldToAnchorLocalMatrix = Matrix.Transpose(Reference.WorldMatrix.GetOrientation());

                MyDetectedEntityInfo fighter;

                if (HangarSensor.IsActive || true)
                {
                    fighter = HangarSensor.LastDetectedEntity;
                }
                else
                {
                    fighter   = BottomSensor.LastDetectedEntity;
                    phasetemp = 0;
                }

                Vector3D worldPositon = (fighter.Position - Reference.GetPosition());
                Vector3D position     = Vector3D.Transform(worldPositon, worldToAnchorLocalMatrix) + new Vector3D(0, 10.2, 1.25);

                Vector3D worldVelocities = (fighter.Velocity - Reference.GetShipVelocities().LinearVelocity);
                Vector3D velocities      = Vector3D.Transform(worldVelocities, worldToAnchorLocalMatrix);

                parent.Echo(Convert.ToString(velocities.X));
                parent.Echo(Convert.ToString(velocities.Y));
                parent.Echo(Convert.ToString(velocities.Z));
                parent.Echo(Convert.ToString(position.X));
                parent.Echo(Convert.ToString(position.Y));
                parent.Echo(Convert.ToString(position.Z));

                float front = Convert.ToSingle(fighter.Orientation.Forward.Dot(Reference.WorldMatrix.Forward));
                float right = Convert.ToSingle(fighter.Orientation.Forward.Dot(Reference.WorldMatrix.Right));
                float down  = Convert.ToSingle(fighter.Orientation.Forward.Dot(Reference.WorldMatrix.Down));

                switch (phase)
                {
                case 0:


                    GGFr.SetGravity(-5 * Convert.ToSingle(position.Z + velocities.Z));
                    GGBa.SetGravity(5 * Convert.ToSingle(position.Z + velocities.Z));
                    GGR.SetGravity(5 * Convert.ToSingle(position.X + velocities.X));
                    GGL.SetGravity(-5 * Convert.ToSingle(position.X + velocities.X));

                    GGDis.SetGravity(-9.81f - 5 * Convert.ToSingle(velocities.Y));
                    GGUpDo.SetGravity(Convert.ToSingle(9.81f - 5 * velocities.Y));

                    if (Math.Abs(position.X) < 8 && Math.Abs(position.Z) < 10)
                    {
                        bool direction = freedirection ^ fighter.Orientation.Down.Dot(Reference.WorldMatrix.Down) < 0;

                        if ((direction && front < -0.99) || (!direction && front > 0.99))
                        {
                            phasetemp = 1;
                            GGRot.OnOff(false);
                            GGDis.OnOff(false);
                        }
                        else

                        {
                            if (direction ^ right > 0)
                            {
                                Rota[0, 0].GravityAcceleration = -10;
                                Rota[0, 1].GravityAcceleration = -10;
                                Rota[1, 0].GravityAcceleration = 10;
                                Rota[1, 1].GravityAcceleration = 10;
                            }
                            else
                            {
                                Rota[0, 0].GravityAcceleration = 10;
                                Rota[0, 1].GravityAcceleration = 10;
                                Rota[1, 0].GravityAcceleration = -10;
                                Rota[1, 1].GravityAcceleration = -10;
                            }

                            counter++;
                            if (counter >= 20)
                            {
                                counter = 0;
                                Vector3 field = new Vector3(17.5 + 2 * position.Z, 35, 14);
                                Rota[0, 0].FieldSize = field;
                                field.X = 17.5f - 2 * Convert.ToSingle(position.Z);
                                Rota[0, 1].FieldSize = field;
                                field.X = 10 + 2 * Convert.ToSingle(position.X);
                                Rota[1, 0].FieldSize = field;
                                field.X = 10 - 2 * Convert.ToSingle(position.X);
                                Rota[1, 1].FieldSize = field;
                            }
                        }
                    }
                    else
                    {
                        GGRot.SetGravity(0);
                    }

                    break;

                case 1:

                    GGR.SetGravity(9.81f + 5 * Convert.ToSingle(velocities.X));
                    GGL.SetGravity(9.81f - 5 * Convert.ToSingle(velocities.X));

                    float height;
                    if (down > 0.92)
                    {
                        height = 0;
                    }
                    else
                    {
                        height = 18f;
                    }

                    float upDoBase = Convert.ToSingle(-5 * (position.Y + height) - 7 * velocities.Y);


                    if (position.Y > -3)
                    {
                        float offset;
                        if (freedirection)
                        {
                            offset = -5.5f;
                        }
                        else
                        {
                            offset = 5.5f;
                        }

                        GGFr.SetGravity(-5 * Convert.ToSingle(position.Z - offset + velocities.Z));
                        GGBa.SetGravity(5 * Convert.ToSingle(position.Z - offset + velocities.Z));

                        GGUpDo.SetGravity(upDoBase + 9.81f / 4);
                    }
                    else
                    {
                        GGFr.SetGravity(9.81f - 5 * Convert.ToSingle(velocities.Z));
                        GGBa.SetGravity(9.81f + 5 * Convert.ToSingle(velocities.Z));

                        UpDown[0, 0].GravityAcceleration = upDoBase - 10 * (front + right);
                        UpDown[0, 1].GravityAcceleration = upDoBase - 10 * (front - right);
                        UpDown[1, 0].GravityAcceleration = upDoBase + 10 * (front - right);
                        UpDown[1, 1].GravityAcceleration = upDoBase + 10 * (front + right);
                    }


                    if (!HangarSensor.IsActive)
                    {
                        phasetemp = 0;
                        GGRot.OnOff(true);
                        GGDis.OnOff(true);
                        GGFr.ResetDimensions();
                        GGBa.ResetDimensions();
                    }
                    break;

                default:
                    break;
                }
            }