public void Main()
            {
                if (accelerateTarget == null || accelerateTarget == Vector3D.Zero || accelerateTarget == Vector3D.PositiveInfinity || PID_Controller == null || !accelerateTarget.IsValid())
                {
                    return;
                }

                Vector3D accelerateTargetNormalized = accelerateTarget;
                double   accelerateTargetLength     = accelerateTargetNormalized.Normalize();
                double   error      = Vector3D.Dot(control.WorldMatrix.Forward, accelerateTarget) + accelerateTargetLength;
                double   multiplier = Math.Abs(PID_Controller.NextValue(error, 0.016));

                if (accelerateTargetLength < negligible)
                {
                    accelerateTargetNormalized = Vector3D.Normalize(control.GetShipVelocities().LinearVelocity);
                }

                GyroUtils.PointInDirection(gyros, control, accelerateTargetNormalized, multiplier);
                //ThrustUtils.SetThrustBasedDot(thrusters, accelerateTargetNormalized, multiplier);
                autopilotModule.ThrustToVelocity(control.GetShipVelocities().LinearVelocity + accelerateTarget);


                if (accelerateInDirection && control.GetShipSpeed() >= (speedLimit - 0.01))
                {
                    accelerateTarget = Vector3D.Zero;
                    BoostForward(0);
                    accelerateInDirection = false;
                }
            }
            private double GetSpeedOnNaturalGravityVect()
            {
                Vector3D acceleration    = referenceBlock.GetNaturalGravity();
                Vector3D shipVelocityVec = referenceBlock.GetShipVelocities().LinearVelocity;

                return(VectorUtils.Projection(shipVelocityVec, acceleration).Length() * Math.Sign(shipVelocityVec.Dot(acceleration)));
            }
Exemple #3
0
            public void AimCannons(Vector3D TargetLocation, Vector3D TargetVelocity)
            {
                Vector3D MyTargetDir  = AimPoint - turrets[0].GetPosition();
                double   MyTargetDist = MyTargetDir.Length();

                MyTargetDir = Vector3D.Normalize(MyTargetDir);
                double   MyOrthVelocity = shipcontroller.GetShipVelocities().LinearVelocity.Dot(MyTargetDir);
                Vector3D MyTangVelocity = Vector3D.Reject(shipcontroller.GetShipVelocities().LinearVelocity, MyTargetDir);

                Vector2D corrections = GetCorrection2(MyTargetDist, MyOrthVelocity, MyTangVelocity.Length());

                (gts.GetBlockWithName("Cockpit") as IMyCockpit).GetSurface(0).WriteText("v: " + corrections[0] + "  x: " + corrections[1] + "\n", false);

                Vector3D AimDir = FindInterceptVector(
                    turrets[0].GetPosition(),
                    corrections[0],
                    TargetLocation,
                    TargetVelocity);

                //(gts.GetBlockWithName(LCD) as IMyTextPanel).WriteText(""+AimDir.Length(),true);
                if ((corrections[1] > 0) && (MyTangVelocity.LengthSquared() > 1))
                {
                    AimDir -= (Vector3D.Normalize(MyTangVelocity) * corrections[1]);
                }
                AimPoint = turrets[0].GetPosition() + AimDir;
                foreach (IMyLargeMissileTurret turret in turrets)
                {
                    turret.SetTarget(AimPoint);

                    /* if (radar.CurrentTarget.Velocity.Length() > 80)
                     * turret.ApplyAction("ShootOnce");*/
                }
            }
Exemple #4
0
        public float GetBrakingDistance()
        {
            var   speed     = (float)Controller.GetShipVelocities().LinearVelocity.Length();
            float aMax      = MinThrustRatio * MaxAccel;
            float decelTime = speed / aMax;

            return(speed * decelTime - 0.5f * aMax * decelTime * decelTime);
        }
Exemple #5
0
            bool AdjustGyros_v2()
            {
                if (!ignoreGravity)
                {
                    alignVec = sc.GetNaturalGravity();
                }
                if (ignoreGravity || Vector3D.IsZero(alignVec))
                {
                    // When in zero-gravity, then use direction of ship-velocity instead
                    alignVec = sc.GetShipVelocities().LinearVelocity;
                    if (Vector3D.IsZero(alignVec))
                    {
                        // No usable velocity, reset all gyros
                        foreach (var g in gyros)
                        {
                            SetGyro(g);
                        }
                        return(false);
                    }
                }
                if (!isInverted)
                {
                    alignVec = Vector3D.Negate(alignVec);
                }
                alignVec.Normalize();

                sc.Orientation.GetMatrix(out or);                 //Get orientation from reference-block
                //down = (isRocket ? or.Backward : or.Down);
                localDown = Vector3D.Transform((isRocket ? or.Backward : or.Down), MatrixD.Transpose(or));
                localGrav = Vector3D.TransformNormal(alignVec, MatrixD.Transpose(sc.WorldMatrix));

                rot = Vector3D.Cross(localDown, localGrav);
                ang = rot.Length() + forceRotation;                               // Naive fix for "Gimbal lock"
                ang = Math.Atan2(ang, Math.Sqrt(Math.Max(0.0, 1.0 - ang * ang))); //More numerically stable than: ang=Math.Asin(ang)
                if (0.01 > ang)
                {
                    foreach (var g in gyros)
                    {
                        SetGyro(g);
                    }
                    return(false);
                }

                //Control speed to be proportional to distance (angle) we have left
                ctrl_vel = Math.Max(0.01, Math.Min(maxYaw, (maxYaw * (ang / Math.PI) * ctrl_Coeff)));
                rot.Normalize();
                rot *= -ctrl_vel;

                foreach (var g in gyros)
                {
                    var gyroRot = Vector3D.TransformNormal(rot, MatrixD.Transpose(g.WorldMatrix));
                    SetGyroRad(g, 1, true, (float)gyroRot.X, (float)gyroRot.Y, (float)gyroRot.Z);
                }
                return(true);
            }
            public Vector3 GetVelocityAtPoint(IMyShipController anchor)
            {
                Vector3 value = Vector3D.Zero;

                if (Obj.IsAttached)
                {
                    Vector3 v = Obj.Top.GetPosition() - anchor.CenterOfMass;
                    value = anchor.GetShipVelocities().LinearVelocity + anchor.GetShipVelocities().AngularVelocity.Cross(v);
                }
                return(value);
            }
            private Vector3D CalculateTargetVector(MyDetectedEntityInfo info, IMyLargeTurretBase turret, double ammoSpeed = 1000d)            //projectile speed 1000m/s (300 auto canon)
            {
                ///prediction = position + velocity * time + 0.5 * acceleration * time * time
                ///time ~ distance(m)/1000 (1000m/s 300 AC ammmo speed
                ///

                Vector3D shotOrigin = turret.GetPosition();

                Vector3D directionToTarget = Vector3D.Normalize(info.Position - shotOrigin);

                //double targetSpeedInLineOfFire = Vector3D.Dot(directionToTarget, info.Velocity);
                double relativeSpeed = ammoSpeed;                // - targetSpeedInLineOfFire;

                double   distance     = Vector3D.Distance(turret.GetPosition(), info.Position);
                double   time         = distance / relativeSpeed;
                Vector3D displacement = ToVector3D(info.Velocity) * time;
                Vector3D targetVector = info.Position + displacement;
                //Vector3D targetVector = info.Position;

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

                //targetVector = targetVector + mySpeed * -1 * distance / 2500;
                targetVector = targetVector + (mySpeed * -1) * time / 1.5d;

                //_program.Echo($"T:{time}");
                return(targetVector);
            }
            public void StabelizeUpwards(Vector3D groundUpVector)
            {
                Vector3D velocity = rc.GetShipVelocities().LinearVelocity;

                velocity.Normalize();

                Vector3D upVector      = groundUpVector;
                Vector3D forwardVector = VectorUtils.ProjectOnPlanePerpendiculair(rc.WorldMatrix.Left, rc.WorldMatrix.Forward, velocity);

                if (groundUpVector == Vector3D.Zero)
                {
                    upVector = Vector3D.Normalize(-rc.GetNaturalGravity());
                }

                upVector += pitchUpBias * rc.WorldMatrix.Backward;

                var refLeft    = rc.WorldMatrix.Left;
                var refUp      = rc.WorldMatrix.Backward;
                var refForward = rc.WorldMatrix.Up;

                double dotUp      = 1 - Vector3D.Dot(upVector, refForward);
                double multiplier = MyMath.Clamp((float)(dotUp * 2 * dotUp), 1, 10);

                MatrixD rotationMatrix = MatrixD.CreateFromDir(refForward, refUp);

                Vector3D moveindicatorUP = VectorUtils.Project(VectorUtils.TransformDirLocalToWorld(rc.WorldMatrix, rc.MoveIndicator), rc.WorldMatrix.Right);

                forwardVector += moveindicatorUP * userInputMultiplier;

                GyroUtils.PointInDirection(gyros, rotationMatrix, upVector, -forwardVector, multiplier * upwardStabelizationMultiplier);
            }
        DockIntel GetHangarIntel(Hangar hangar, TimeSpan timestamp)
        {
            var builder = Context.SharedStringBuilder;

            builder.Clear();
            hangar.Intel.WorldMatrix          = hangar.Connector.WorldMatrix;
            hangar.Intel.CurrentVelocity      = controller.GetShipVelocities().LinearVelocity;
            hangar.Intel.Status               = hangar.hangarStatus;
            hangar.Intel.OwnerID              = hangar.OwnerID;
            hangar.Intel.CurrentCanonicalTime = timestamp + IntelProvider.CanonicalTimeDiff;

            hangar.Intel.ID = hangar.Connector.EntityId;
            if (string.IsNullOrEmpty(hangar.Intel.DisplayName))
            {
                hangar.Intel.DisplayName = builder.Append(hangar.Connector.CustomName).Append(" - ").Append(Context.Reference.CubeGrid.CustomName).ToString();
            }

            hangar.Intel.UndockNear = hangar.Connector.CubeGrid.GridSizeEnum == MyCubeSize.Large ? 1.3f : 0.55f;
            hangar.Intel.UndockFar  = hangar.ClearanceDist;

            hangar.Intel.IndicatorDir     = hangar.DirectionIndicator == null ? (DirectionIndicator == null ? Vector3D.Zero : DirectionIndicator.WorldMatrix.Forward) : hangar.DirectionIndicator.WorldMatrix.Forward;
            hangar.Intel.HangarChannelTag = HangarChannelTag;
            hangar.Intel.Tags             = hangar.HangarTags;

            return(hangar.Intel);
        }
Exemple #10
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;
            }
Exemple #11
0
        public Vector3D GetShipAngularVelocity(IMyShipController dataBlock)
        {
            var worldLocalVelocities     = dataBlock.GetShipVelocities().AngularVelocity;
            var worldToAnchorLocalMatrix = Matrix.Transpose(dataBlock.WorldMatrix.GetOrientation());

            return(Vector3D.Transform(worldLocalVelocities, worldToAnchorLocalMatrix));
        }
Exemple #12
0
            public void Update()
            {
                // Calculate the needed thrust to get to velocity
                Vector3D myVel  = rc.GetShipVelocities().LinearVelocity;
                Vector3D deltaV = myVel - Velocity;

                if (Vector3D.IsZero(deltaV))
                {
                    return;
                }

                Vector3D gravity = rc.GetNaturalGravity();
                Vector3D thrust  = GetShipMass() * (2 * deltaV + gravity);

                // Apply the thrust
                for (int i = 0; i < thrusters.Count; i++)
                {
                    IMyThrust t = thrusters [i];
                    if (t == null)
                    {
                        thrusters.RemoveAtFast(i);
                        continue;
                    }


                    if (!t.IsFunctional)
                    {
                        continue;
                    }

                    if (Vector3D.Dot(t.WorldMatrix.Forward, thrust) > 0)
                    {
                        t.Enabled = true;
                        double outputThrust     = Vector3D.Dot(thrust, t.WorldMatrix.Forward);
                        double outputProportion = MathHelper.Clamp(outputThrust / t.MaxEffectiveThrust, 0, 1);
                        t.ThrustOverridePercentage = (float)outputProportion;
                        thrust -= t.WorldMatrix.Forward * outputProportion * t.MaxEffectiveThrust;
                    }
                    else
                    {
                        t.ThrustOverride = 0;
                        t.Enabled        = false;
                    }
                }
            }
            public void NextPosition(ref Vector3D nextDirection, Vector3D headingDir, double safetyMargin = 1.25)
            {
                CreateSphereFromEntities(headingDir);

                Vector3D position    = rc.CubeGrid.WorldVolume.Center;
                Vector3D movementDir = rc.GetShipVelocities().LinearVelocity;

                movementDir.Normalize();

                RayD movementRay = new RayD(position, movementDir);
                RayD headingRay  = new RayD(rc.CubeGrid.WorldVolume.Center, headingDir);

                BoundingSphereD sphere = boundingSphere;

                sphere.Radius += rc.CubeGrid.WorldVolume.Radius;

                if (sphere.Contains(position) != ContainmentType.Disjoint)
                {
                    Vector3D dodgeDirection = Vector3D.Normalize(position - sphere.Center);

                    nextDirection = sphere.Center + dodgeDirection * sphere.Radius * safetyMargin;
                    return;
                }

                double?movementDist = sphere.Intersects(movementRay);
                double?headingDist  = sphere.Intersects(headingRay);

                if (movementDist.HasValue || headingDist.HasValue)
                {
                    Vector3D pointOnSphere;
                    Vector3D dodgeDirection;
                    if (movementDist.HasValue)
                    {
                        pointOnSphere  = position + movementDir * movementDist.Value;
                        dodgeDirection = GetAvoidanceVector(pointOnSphere, sphere, movementDir);
                    }
                    else
                    {
                        pointOnSphere  = position + headingDir * headingDist.Value;
                        dodgeDirection = GetAvoidanceVector(pointOnSphere, sphere, headingDir);
                    }

                    nextDirection = dodgeDirection;
                }
            }
Exemple #14
0
            private void CalcWorldSpeed()
            {
                Vector3D linearVelocity = Vector3D.Normalize(cockpit.GetShipVelocities().LinearVelocity);
                Vector3D gravity        = -Vector3D.Normalize(cockpit.GetNaturalGravity());

                worldSpeedForward = Helpers.NotNan(Vector3D.Dot(linearVelocity, Vector3D.Cross(gravity, cockpit.WorldMatrix.Right)) * cockpit.GetShipSpeed());
                worldSpeedRight   = Helpers.NotNan(Vector3D.Dot(linearVelocity, Vector3D.Cross(gravity, cockpit.WorldMatrix.Forward)) * cockpit.GetShipSpeed());
                worldSpeedUp      = Helpers.NotNan(Vector3D.Dot(linearVelocity, gravity) * cockpit.GetShipSpeed());
            }
            public void Main(float currentAlt, MyDetectedEntityInfo surfaceType)
            {
                if (rc.GetShipVelocities().LinearVelocity.Length() > minSpeed)
                {
                    SetDownForceBasedVel();
                    SetDownForceBasedCorner();
                    SetDownForceBasedAlt(currentAlt);
                    SetDownForceBasedJump();
                }
                else
                {
                    SetDownForce(0);
                }

                SetDownForceBasedBreaks();

                ApplyDownForce();
            }
Exemple #16
0
            public void DebugSpeed()
            {
                Vector3D speed_Bship = m_shipControl.GetShipVelocities().LinearVelocity;

                var      rotBase = Babs_2_Bcockpit;
                Vector3D speed_Bcock;

                Vector3D.Rotate(ref speed_Bship, ref rotBase, out speed_Bcock);
                DebugV3(speed_Bcock, "Speed Cockpit:", "m/s");
            }
Exemple #17
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);
            }
Exemple #18
0
            private void UpdateThrusterGroups()
            {
                if (_controller == null)
                {
                    return;
                }
                if (_config.LiftThrustersGroupName != "")
                {
                    _liftThrusters.FindBlocks(true, null, _config.LiftThrustersGroupName);
                }
                else
                {
                    _liftThrusters.FindBlocks(true, thruster => {
                        Vector3D thrusterDirection = -thruster.WorldMatrix.Forward;
                        //double forwardDot = Vector3D.Dot(thrusterDirection, _controller.WorldMatrix.Forward);
                        double upDot = Vector3D.Dot(thrusterDirection, -Vector3.Normalize(_controller.GetTotalGravity()));
                        //double leftDot = Vector3D.Dot(thrusterDirection, _controller.WorldMatrix.Left);

                        if (upDot >= 0.2)
                        {
                            return(true);
                        }
                        return(false);
                    });
                }
                if (_config.StopThrustersGroupName != "")
                {
                    _stopThrusters.FindBlocks(true, null, _config.StopThrustersGroupName);
                }
                else
                {
                    _stopThrusters.FindBlocks(true, thruster => {
                        Vector3D thrusterDirection = -thruster.WorldMatrix.Forward;
                        double forwardDot          = Vector3D.Dot(thrusterDirection, _controller.GetShipVelocities().LinearVelocity);
                        //double upDot = Vector3D.Dot(thrusterDirection, _controller.WorldMatrix.Up);
                        //double leftDot = Vector3D.Dot(thrusterDirection, _controller.WorldMatrix.Left);

                        if (forwardDot <= -0.7)
                        {
                            return(true);
                        }
                        return(false);
                    });
                }
                _cruiseThrusters.FindBlocks(true, thruster => {
                    var facing = thruster.Orientation.TransformDirection(Base6Directions.Direction.Forward);
                    return(facing == Base6Directions.Direction.Backward);
                });
                _cruiseReverseThrusters.FindBlocks(true, thruster => {
                    var facing = thruster.Orientation.TransformDirection(Base6Directions.Direction.Forward);
                    return(facing == Base6Directions.Direction.Forward);
                });
            }
Exemple #19
0
            public void LogPoint(TimeSpan deltaTime)
            {
                DataPoint point = new DataPoint
                {
                    position = controller.CenterOfMass,
                    forward  = controller.WorldMatrix.Forward,
                    velocity = controller.GetShipVelocities().LinearVelocity,
                    time     = deltaTime
                };

                datapoints.Add(point);
            }
Exemple #20
0
        void UpdateOrientationParameters()
        {
            Vector3D linearVelocity = Vector3D.Normalize(cockpit_.GetShipVelocities().LinearVelocity);
            Vector3D gravity        = -Vector3D.Normalize(cockpit_.GetNaturalGravity());

            pitch_ = Math.Acos(Vector3D.Dot(cockpit_.WorldMatrix.Forward, gravity)) * RadToDeg;
            roll_  = Math.Acos(Vector3D.Dot(cockpit_.WorldMatrix.Right, gravity)) * RadToDeg;

            worldSpeedForward_ = Vector3D.Dot(linearVelocity, Vector3D.Cross(gravity, cockpit_.WorldMatrix.Right)) * cockpit_.GetShipSpeed();
            worldSpeedRight_   = Vector3D.Dot(linearVelocity, Vector3D.Cross(gravity, cockpit_.WorldMatrix.Forward)) * cockpit_.GetShipSpeed();
            worldSpeedUp_      = Vector3D.Dot(linearVelocity, gravity) * cockpit_.GetShipSpeed();
        }
        public void Main(string argument, UpdateType updateType)
        {
            string tag1        = "pack";
            string tag2        = "pack2";
            string messageOut1 = antenna.GetPosition().ToString();
            string messageOut2 = controller.GetShipVelocities().LinearVelocity.ToString();

            Echo(messageOut2);
            IGC.SendBroadcastMessage(tag1, messageOut1, TransmissionDistance.TransmissionDistanceMax);
            IGC.RegisterBroadcastListener(tag1);
            IGC.SendBroadcastMessage(tag2, messageOut2, TransmissionDistance.TransmissionDistanceMax);
            IGC.RegisterBroadcastListener(tag2);
        }
Exemple #22
0
            private void SpaceBrake()
            {
                TargetOrientation(Vector3D.Normalize(cockpit.GetShipVelocities().LinearVelocity));

                if (Helpers.EqualWithMargin(gyroController.angle, 0, angleThreshold))
                {
                    cockpit.DampenersOverride = true;
                }

                if (cockpit.GetShipSpeed() < speedThreshold)
                {
                    SetAction("disabled");
                }
            }
        void Attack(TimeSpan localTime)
        {
            FriendlyShipScratchpad.Clear();

            var intelItems = IntelProvider.GetFleetIntelligences(localTime);

            foreach (var kvp in intelItems)
            {
                if (kvp.Key.Item1 == IntelItemType.Friendly)
                {
                    var friendly = (FriendlyShipIntel)kvp.Value;
                    if (friendly.AgentClass == AgentClass.Fighter && (friendly.AgentStatus & AgentStatus.Docked) != 0 && (friendly.GetPositionFromCanonicalTime(localTime + IntelProvider.CanonicalTimeDiff) - Controller.GetPosition()).Length() < 100)
                    {
                        FriendlyShipScratchpad.Add(friendly);
                    }
                }
            }

            if (FriendlyShipScratchpad.Count == 0)
            {
                return;
            }

            for (int i = 0; i < FriendlyShipScratchpad.Count; i++)
            {
                var targetWaypoint = new Waypoint();

                var gravDir = Controller.GetNaturalGravity();
                targetWaypoint.Position = Controller.GetPosition();
                var angle = 2 * i * Math.PI / FriendlyShipScratchpad.Count;

                if (gravDir != Vector3D.Zero)
                {
                    gravDir.Normalize();
                    var flatForward = Controller.WorldMatrix.Forward - VectorHelpers.VectorProjection(Controller.WorldMatrix.Forward, gravDir);
                    flatForward.Normalize();
                    var flatLeftDir = Vector3D.Cross(flatForward, gravDir);
                    targetWaypoint.Position += (flatForward * TrigHelpers.FastCos(angle) + flatLeftDir * TrigHelpers.FastSin(angle)) * 500;
                    targetWaypoint.Position -= gravDir * 200;
                }
                else
                {
                    targetWaypoint.Position += (Controller.WorldMatrix.Forward * TrigHelpers.FastCos(angle) + Controller.WorldMatrix.Left * TrigHelpers.FastSin(angle)) * 500;
                }

                targetWaypoint.Position += Controller.GetShipVelocities().LinearVelocity * 3;
                IntelProvider.ReportFleetIntelligence(targetWaypoint, localTime);
                IntelProvider.ReportCommand(FriendlyShipScratchpad[i], TaskType.Attack, MyTuple.Create(IntelItemType.Waypoint, targetWaypoint.ID), localTime);
            }
        }
Exemple #24
0
        public void GetTargetInterception(MyDetectedEntityInfo target)
        {
            trajectoryCalculation = new Trajectory(cockpit.GetShipVelocities().LinearVelocity, cockpitpos, cockpit.WorldMatrix.Forward, 400);

            if (projector != null)
            {
                projector.UpdatePosition(cockpitpos + Vector3D.Normalize(target.Position - cockpitpos) * projectionDistanceFromCockpit);
            }

            if (Vector3D.DistanceSquared(target.Position, cockpit.GetPosition()) < detectionRange * detectionRange)
            {
                var intersection = trajectoryCalculation.SimulateTrajectory(target);
                if (intersection.HasValue)
                {
                    if (leadProjector != null)
                    {
                        leadProjector.UpdatePosition(cockpitpos + Vector3D.Normalize(intersection.Value - cockpitpos) * (projectionDistanceFromCockpit - 1));
                        leadProjector.Enable();
                    }



                    if (autoAim != null)
                    {
                        var dist      = intersection.Value - cockpitpos;
                        var direction = SpreadVectors(Vector3D.Normalize(dist), 0.0174532925);

                        autoAim.SetTarget(direction);
                        autoAim.mainRotate();
                    }
                }
                else
                {
                    if (leadProjector != null)
                    {
                        leadProjector.Disable();
                    }
                    DisposeAuto();
                }
            }
            else
            {
                if (leadProjector != null)
                {
                    leadProjector.Disable();
                }
                DisposeAuto();
            }
        }
 public bool Update()
 {
     //Speed towards the center of nearest gravity well.
     if (Controller != null)
     {
         newValue = -Vector3.Dot(Controller.GetShipVelocities().LinearVelocity,
                                 Vector3D.Normalize(Controller.GetNaturalGravity()));
         if (newValue != Value)
         {
             Value = newValue;
             return(true);
         }
     }
     return(false);
 }
Exemple #26
0
            public Vector3D ControlVelocity(Vector3D targetVelocity)
            {
                // Calculate the needed thrust to get to velocity
                Vector3D myVel  = rc.GetShipVelocities().LinearVelocity;
                Vector3D deltaV = myVel - targetVelocity;

                if (Vector3D.IsZero(deltaV))
                {
                    return(Vector3D.Zero);
                }

                Vector3D gravity = rc.GetNaturalGravity();

                return(2 * deltaV + gravity);
            }
            public Vector2 CalculatePitchRollToAchiveVelocity(Vector3 targetVelocity)
            {
                Vector3 diffrence            = Vector3.Normalize(controller.GetShipVelocities().LinearVelocity - targetVelocity);
                Vector3 gravity              = -Vector3.Normalize(controller.GetNaturalGravity());
                float   velocity             = (float)controller.GetShipSpeed();
                float   proportionalModifier = (float)Math.Pow(Math.Abs(diffrence.Length()), 2);

                float pitch = NotNaN(Vector3.Dot(diffrence, Vector3.Cross(gravity, controller.WorldMatrix.Right)) * velocity) * proportionalModifier / dampeningFactor;
                float roll  = NotNaN(Vector3.Dot(diffrence, Vector3.Cross(gravity, controller.WorldMatrix.Forward)) * velocity) * proportionalModifier / dampeningFactor;

                pitch = MinAbs(pitch, 90.0f * degToRad);
                roll  = MinAbs(roll, 90.0f * degToRad);

                return(new Vector2(roll, pitch));
            }
        public bool Update()
        {
            grav          = controller.GetNaturalGravity();
            vel           = controller.GetShipVelocities().LinearVelocity;
            gravInHeading = Vector3D.Dot(grav, Vector3D.Normalize(vel));
            force         = ForceInDirection(Vector3D.Normalize(vel), thrusters);

            val = StoppingDistance(shipData[Data.Mass].Value, force, vel.Length(), gravInHeading);

            if (val != Value)
            {
                Value = val;
                return(true);
            }
            return(false);
        }
Exemple #29
0
        void UpdateMyIntel(TimeSpan timestamp)
        {
            if (timestamp == TimeSpan.Zero)
            {
                return;
            }
            if (controller == null)
            {
                return;
            }

            FriendlyShipIntel myIntel;
            IMyCubeGrid       cubeGrid = Context.Reference.CubeGrid;
            var key = MyTuple.Create(IntelItemType.Friendly, cubeGrid.EntityId);

            if (IntelItems.ContainsKey(key))
            {
                myIntel = (FriendlyShipIntel)IntelItems[key];
            }
            else
            {
                myIntel = new FriendlyShipIntel();
            }

            myIntel.DisplayName          = cubeGrid.DisplayName;
            myIntel.CurrentVelocity      = controller.GetShipVelocities().LinearVelocity;
            myIntel.CurrentPosition      = cubeGrid.WorldAABB.Center;
            myIntel.Radius               = (float)(cubeGrid.WorldAABB.Max - cubeGrid.WorldAABB.Center).Length() * RadiusMulti + 20;
            myIntel.CurrentCanonicalTime = timestamp + CanonicalTimeDiff;
            myIntel.ID          = cubeGrid.EntityId;
            myIntel.AgentStatus = AgentStatus.None;

            foreach (var processor in intelProcessors)
            {
                processor.ProcessIntel(myIntel);
            }

            if (Host != null)
            {
                Host.ReportFleetIntelligence(myIntel, timestamp);
            }
            else
            {
                ReportFleetIntelligence(myIntel, timestamp);
            }
        }
Exemple #30
0
            void Control()
            {
                var brakes   = Controller.MoveIndicator.Y > 0 || Controller.HandBrake;
                var velocity = Vector3D.TransformNormal(Controller.GetShipVelocities().LinearVelocity, MatrixD.Transpose(Controller.WorldMatrix)) * brakingConstant;

                avgWheelPosition = Vector3D.Zero;
                foreach (var w in Wheels)
                {
                    avgWheelPosition += w.GetPosition();
                }
                avgWheelPosition /= Wheels.Count;

                foreach (var w in SubgridWheels)
                {
                    w.SetValue("Propulsion override", -Math.Sign(Math.Round(Vector3D.Dot(w.WorldMatrix.Up, Controller.WorldMatrix.Right), 2)) * (Convert.ToSingle(brakes && Controller.GetShipSpeed() > 1) * (float)velocity.Z + Convert.ToSingle(!brakes) * w.Power * 0.01f * -Controller.MoveIndicator.Z));
                    w.SetValue("Steer override", Math.Sign(Math.Round(Vector3D.Dot(w.WorldMatrix.Forward, Controller.WorldMatrix.Up), 2)) * Math.Sign(Vector3D.Dot(w.GetPosition() - avgWheelPosition, Controller.WorldMatrix.Forward)) * Controller.MoveIndicator.X + Controller.RollIndicator);
                }
            }