Beispiel #1
0
        public TargetSignatureData(Vessel v, float _signalStrength)
        {
            velocity       = v.srf_velocity;
            geoPos         = VectorUtils.WorldPositionToGeoCoords(v.CoM, v.mainBody);
            acceleration   = v.acceleration;
            exists         = true;
            timeAcquired   = Time.time;
            signalStrength = _signalStrength;

            targetInfo = v.gameObject.GetComponent <TargetInfo> ();

            team = BDArmorySettings.BDATeams.None;
            if (targetInfo)
            {
                team = targetInfo.team;
            }
            else
            {
                foreach (var mf in v.FindPartModulesImplementing <MissileFire>())
                {
                    team = BDATargetManager.BoolToTeam(mf.team);
                    break;
                }
            }

            vesselJammer = v.gameObject.GetComponent <VesselECMJInfo>();

            pingPosition = Vector2.zero;
        }
 void SendGPS()
 {
     if (groundStabilized && weaponManager)
     {
         BDATargetManager.GPSTargets[BDATargetManager.BoolToTeam(weaponManager.team)].Add(new GPSTargetInfo(bodyRelativeGTP, "Target"));
     }
 }
        public void EnableCamera()
        {
            if (!TargetingCamera.Instance)
            {
                Debug.Log("Tried to enable targeting camera, but camera instance is null.");
                return;
            }
            if (vessel.isActiveVessel)
            {
                activeCam    = this;
                windowIsOpen = true;
                TargetingCamera.Instance.EnableCamera(cameraParentTransform);
                TargetingCamera.Instance.nvMode = nvMode;
                TargetingCamera.Instance.SetFOV(fov);
                RefreshWindowSize();
            }

            cameraEnabled = true;

            if (weaponManager)
            {
                weaponManager.mainTGP = this;
            }

            BDATargetManager.RegisterLaserPoint(this);
        }
Beispiel #4
0
        protected void  AddTargetInfoToVessel()
        {
            TargetInfo info = vessel.gameObject.AddComponent <TargetInfo>();

            info.team              = BDATargetManager.BoolToTeam(Team);
            info.isMissile         = true;
            info.MissileBaseModule = this;
        }
Beispiel #5
0
		void Awake()
		{
			GameEvents.onGameStateLoad.Add(LoadGPSTargets);
			GameEvents.onGameStateSave.Add(SaveGPSTargets);
			LoadedBuildings = new List<DestructibleBuilding>();
			DestructibleBuilding.OnLoaded.Add(AddBuilding);
			LoadedVessels = new List<Vessel>();
			GameEvents.onVesselLoaded.Add(AddVessel);
			GameEvents.onVesselGoOnRails.Add(RemoveVessel);
			GameEvents.onVesselGoOffRails.Add(AddVessel);
			GameEvents.onVesselCreate.Add(AddVessel);
			GameEvents.onVesselDestroy.Add(CleanVesselList);

			Instance = this;
		}
Beispiel #6
0
        void Awake()
        {
            GameEvents.onGameStateLoad.Add(LoadGPSTargets);
            GameEvents.onGameStateSave.Add(SaveGPSTargets);
            LoadedBuildings = new List <DestructibleBuilding>();
            DestructibleBuilding.OnLoaded.Add(AddBuilding);
            LoadedVessels = new List <Vessel>();
            GameEvents.onVesselLoaded.Add(AddVessel);
            GameEvents.onVesselGoOnRails.Add(RemoveVessel);
            GameEvents.onVesselGoOffRails.Add(AddVessel);
            GameEvents.onVesselCreate.Add(AddVessel);
            GameEvents.onVesselDestroy.Add(CleanVesselList);

            Instance = this;
        }
Beispiel #7
0
        protected void UpdateLaserTarget()
        {
            if (TargetAcquired)
            {
                if (lockedCamera && lockedCamera.groundStabilized && !lockedCamera.gimbalLimitReached && lockedCamera.surfaceDetected) //active laser target
                {
                    TargetPosition     = lockedCamera.groundTargetPosition;
                    TargetVelocity     = (TargetPosition - lastLaserPoint) / Time.fixedDeltaTime;
                    TargetAcceleration = Vector3.zero;
                    lastLaserPoint     = TargetPosition;

                    if (GuidanceMode == GuidanceModes.BeamRiding && TimeIndex > 0.25f && Vector3.Dot(GetForwardTransform(), part.transform.position - lockedCamera.transform.position) < 0)
                    {
                        TargetAcquired = false;
                        lockedCamera   = null;
                    }
                }
                else //lost active laser target, home on last known position
                {
                    if (CMSmoke.RaycastSmoke(new Ray(transform.position, lastLaserPoint - transform.position)))
                    {
                        //Debug.Log("Laser missileBase affected by smoke countermeasure");
                        float angle = VectorUtils.FullRangePerlinNoise(0.75f * Time.time, 10) * BDArmorySettings.SMOKE_DEFLECTION_FACTOR;
                        TargetPosition     = VectorUtils.RotatePointAround(lastLaserPoint, transform.position, VectorUtils.GetUpDirection(transform.position), angle);
                        TargetVelocity     = Vector3.zero;
                        TargetAcceleration = Vector3.zero;
                        lastLaserPoint     = TargetPosition;
                    }
                    else
                    {
                        TargetPosition = lastLaserPoint;
                    }
                }
            }
            else
            {
                ModuleTargetingCamera foundCam = null;
                bool parentOnly = (GuidanceMode == GuidanceModes.BeamRiding);
                foundCam = BDATargetManager.GetLaserTarget(this, parentOnly);
                if (foundCam != null && foundCam.cameraEnabled && foundCam.groundStabilized && BDATargetManager.CanSeePosition(foundCam.groundTargetPosition, vessel.transform.position, MissileReferenceTransform.position))
                {
                    Debug.Log("[BDArmory]: Laser guided missileBase actively found laser point. Enabling guidance.");
                    lockedCamera   = foundCam;
                    TargetAcquired = true;
                }
            }
        }
        public TargetSignatureData(Vessel v, float _signalStrength)
        {
            /*
             * if(v.situation == Vessel.Situations.SUB_ORBITAL || v.situation == Vessel.Situations.ESCAPING || v.situation == Vessel.Situations.SUB_ORBITAL)
             * {
             *      velocity = v.obt_velocity;
             *      orbit = v.orbit;
             *      orbital = true;
             * }
             * else
             * {
             */
            orbital  = false;
            orbit    = null;
            velocity = v.srf_velocity;
            //}
            vessel         = v;
            geoPos         = VectorUtils.WorldPositionToGeoCoords(v.CoM, v.mainBody);
            acceleration   = v.acceleration;
            exists         = true;
            timeAcquired   = Time.time;
            signalStrength = _signalStrength;

            targetInfo = v.gameObject.GetComponent <TargetInfo> ();

            team = BDArmorySettings.BDATeams.None;
            if (targetInfo)
            {
                team = targetInfo.team;
            }
            else
            {
                foreach (var mf in v.FindPartModulesImplementing <MissileFire>())
                {
                    team = BDATargetManager.BoolToTeam(mf.team);
                    break;
                }
            }

            vesselJammer = v.gameObject.GetComponent <VesselECMJInfo>();

            pingPosition = Vector2.zero;

            lockedByRadar = null;
        }
Beispiel #9
0
        protected void UpdateHeatTarget()
        {
            if (lockFailTimer > 1)
            {
                legacyTargetVessel = null;
                TargetAcquired     = false;
                return;
            }

            if (heatTarget.exists && lockFailTimer < 0)
            {
                lockFailTimer = 0;
            }
            if (lockFailTimer >= 0)
            {
                Ray lookRay = new Ray(transform.position, heatTarget.position + (heatTarget.velocity * Time.fixedDeltaTime) - transform.position);
                heatTarget = BDATargetManager.GetHeatTarget(lookRay, lockedSensorFOV / 2, heatThreshold, allAspect);

                if (heatTarget.exists)
                {
                    TargetAcquired     = true;
                    TargetPosition     = heatTarget.position + (2 * heatTarget.velocity * Time.fixedDeltaTime);
                    TargetVelocity     = heatTarget.velocity;
                    TargetAcceleration = heatTarget.acceleration;
                    lockFailTimer      = 0;
                }
                else
                {
                    TargetAcquired = false;
                    if (FlightGlobals.ready)
                    {
                        lockFailTimer += Time.fixedDeltaTime;
                    }
                }
            }
        }
Beispiel #10
0
        void AutoPilot(FlightCtrlState s)
        {
            if (!vessel || !vessel.transform || vessel.packed || !vessel.mainBody)
            {
                return;
            }
            vesselTransform = vessel.ReferenceTransform;

            //default brakes off full throttle
            //s.mainThrottle = 1;

            //vessel.ActionGroups.SetGroup(KSPActionGroup.Brakes, false);
            AdjustThrottle(maxSpeed, true);
            useAB     = true;
            useBrakes = true;
            vessel.ActionGroups.SetGroup(KSPActionGroup.SAS, true);

            steerMode = SteerModes.NormalFlight;


            GetGuardTarget();
            if (vessel.Landed && standbyMode && weaponManager && BDATargetManager.TargetDatabase[BDATargetManager.BoolToTeam(weaponManager.team)].Count == 0)
            {
                //s.mainThrottle = 0;
                //vessel.ActionGroups.SetGroup(KSPActionGroup.Brakes, true);
                AdjustThrottle(0, true);
                return;
            }
            //upDirection = -FlightGlobals.getGeeForceAtPosition(transform.position).normalized;
            upDirection = VectorUtils.GetUpDirection(vessel.transform.position);
            debugString = string.Empty;
            if (MissileGuidance.GetRadarAltitude(vessel) < minAltitude)
            {
                startedLanded = true;
            }



            if (startedLanded)
            {
                TakeOff(s);
                turningTimer = 0;
            }
            else
            {
                if (FlyAvoidCollision(s))
                {
                    turningTimer = 0;
                }
                else if (command != PilotCommands.Free)
                {
                    UpdateCommand(s);
                }
                else
                {
                    UpdateAI(s);
                }
            }

            //brake and cut throttle if exceeding max speed

            /*
             * if(vessel.srfSpeed > maxSpeed)
             * {
             *      vessel.ActionGroups.SetGroup(KSPActionGroup.Brakes, true);
             *      s.mainThrottle = 0;
             * }
             */

            debugString += "\nthreatLevel: " + threatLevel;
        }
Beispiel #11
0
        public static void ScanInDirection(MissileFire myWpnManager, float directionAngle, Transform referenceTransform, float fov, Vector3 position, float minSignature, ref TargetSignatureData[] dataArray, float dataPersistTime, bool pingRWR, RadarWarningReceiver.RWRThreatTypes rwrType, bool radarSnapshot)
        {
            Vector3d geoPos        = VectorUtils.WorldPositionToGeoCoords(position, FlightGlobals.currentMainBody);
            Vector3  forwardVector = referenceTransform.forward;
            Vector3  upVector      = referenceTransform.up;      //VectorUtils.GetUpDirection(position);
            Vector3  lookDirection = Quaternion.AngleAxis(directionAngle, upVector) * forwardVector;

            int dataIndex = 0;

            foreach (var vessel in BDATargetManager.LoadedVessels)
            {
                if (vessel == null)
                {
                    continue;
                }
                if (!vessel.loaded)
                {
                    continue;
                }

                if (myWpnManager)
                {
                    if (vessel == myWpnManager.vessel)
                    {
                        continue;                                                   //ignore self
                    }
                }
                else if ((vessel.transform.position - position).sqrMagnitude < 3600)
                {
                    continue;
                }

                Vector3 vesselDirection = Vector3.ProjectOnPlane(vessel.CoM - position, upVector);

                if (Vector3.Angle(vesselDirection, lookDirection) < fov / 2)
                {
                    if (TerrainCheck(referenceTransform.position, vessel.transform.position))
                    {
                        continue;                                                                                          //blocked by terrain
                    }
                    float sig = float.MaxValue;
                    if (radarSnapshot && minSignature > 0)
                    {
                        sig = GetModifiedSignature(vessel, position);
                    }

                    RadarWarningReceiver.PingRWR(vessel, position, rwrType, dataPersistTime);

                    float detectSig = sig;

                    VesselECMJInfo vesselJammer = vessel.GetComponent <VesselECMJInfo>();
                    if (vesselJammer)
                    {
                        sig       *= vesselJammer.rcsReductionFactor;
                        detectSig += vesselJammer.jammerStrength;
                    }

                    if (detectSig > minSignature)
                    {
                        if (vessel.vesselType == VesselType.Debris)
                        {
                            vessel.gameObject.AddComponent <TargetInfo>();
                        }
                        else if (myWpnManager != null)
                        {
                            BDATargetManager.ReportVessel(vessel, myWpnManager);
                        }

                        while (dataIndex < dataArray.Length - 1)
                        {
                            if ((dataArray[dataIndex].exists && Time.time - dataArray[dataIndex].timeAcquired > dataPersistTime) || !dataArray[dataIndex].exists)
                            {
                                break;
                            }
                            dataIndex++;
                        }
                        if (dataIndex >= dataArray.Length)
                        {
                            break;
                        }
                        dataArray[dataIndex] = new TargetSignatureData(vessel, sig);
                        dataIndex++;
                        if (dataIndex >= dataArray.Length)
                        {
                            break;
                        }
                    }
                }
            }
        }
Beispiel #12
0
        /// <summary>
        /// Scans for targets in direction with field of view.
        /// Returns the direction scanned for debug
        /// </summary>
        /// <returns>The scan direction.</returns>
        /// <param name="myWpnManager">My wpn manager.</param>
        /// <param name="directionAngle">Direction angle.</param>
        /// <param name="referenceTransform">Reference transform.</param>
        /// <param name="fov">Fov.</param>
        /// <param name="results">Results.</param>
        /// <param name="maxDistance">Max distance.</param>
        public static Vector3 GuardScanInDirection(MissileFire myWpnManager, float directionAngle, Transform referenceTransform, float fov, out ViewScanResults results, float maxDistance)
        {
            results = new ViewScanResults();
            results.foundMissile     = false;
            results.foundHeatMissile = false;
            results.foundAGM         = false;
            results.firingAtMe       = false;

            if (!myWpnManager || !referenceTransform)
            {
                return(Vector3.zero);
            }

            Vector3  position      = referenceTransform.position;
            Vector3d geoPos        = VectorUtils.WorldPositionToGeoCoords(position, FlightGlobals.currentMainBody);
            Vector3  forwardVector = referenceTransform.forward;
            Vector3  upVector      = referenceTransform.up;
            Vector3  lookDirection = Quaternion.AngleAxis(directionAngle, upVector) * forwardVector;



            foreach (var vessel in BDATargetManager.LoadedVessels)
            {
                if (vessel == null)
                {
                    continue;
                }

                if (vessel.loaded)
                {
                    if (vessel == myWpnManager.vessel)
                    {
                        continue;                                                   //ignore self
                    }
                    Vector3 vesselProjectedDirection = Vector3.ProjectOnPlane(vessel.transform.position - position, upVector);
                    Vector3 vesselDirection          = vessel.transform.position - position;


                    if (Vector3.Dot(vesselDirection, lookDirection) < 0)
                    {
                        continue;
                    }

                    float vesselDistance = (vessel.transform.position - position).magnitude;

                    if (vesselDistance < maxDistance && Vector3.Angle(vesselProjectedDirection, lookDirection) < fov / 2 && Vector3.Angle(vessel.transform.position - position, -myWpnManager.transform.forward) < myWpnManager.guardAngle / 2)
                    {
                        //Debug.Log("Found vessel: " + vessel.vesselName);
                        if (TerrainCheck(referenceTransform.position, vessel.transform.position))
                        {
                            continue;                                                                                              //blocked by terrain
                        }
                        BDATargetManager.ReportVessel(vessel, myWpnManager);

                        TargetInfo tInfo;
                        if ((tInfo = vessel.GetComponent <TargetInfo>()))
                        {
                            if (tInfo.isMissile)
                            {
                                MissileLauncher missile;
                                if (missile = tInfo.missileModule)
                                {
                                    results.foundMissile = true;
                                    if (missile.hasFired && (missile.targetPosition - (myWpnManager.vessel.CoM + (myWpnManager.vessel.rb_velocity * Time.fixedDeltaTime))).sqrMagnitude < 3600)
                                    {
                                        //Debug.Log("found missile targeting me");
                                        if (missile.targetingMode == MissileLauncher.TargetingModes.Heat)
                                        {
                                            results.foundHeatMissile = true;
                                            break;
                                        }
                                        else if (missile.targetingMode == MissileLauncher.TargetingModes.Laser)
                                        {
                                            results.foundAGM = true;
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                //check if its shooting guns at me
                                if (!results.firingAtMe)
                                {
                                    foreach (var weapon in vessel.FindPartModulesImplementing <ModuleWeapon>())
                                    {
                                        if (!weapon.isFiring)
                                        {
                                            continue;
                                        }
                                        if (Vector3.Dot(weapon.fireTransforms[0].forward, vesselDirection) > 0)
                                        {
                                            continue;
                                        }

                                        if (Vector3.Angle(weapon.fireTransforms[0].forward, -vesselDirection) < 6500 / vesselDistance)
                                        {
                                            results.firingAtMe = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(lookDirection);
        }
Beispiel #13
0
        IEnumerator DogfightCompetitionModeRoutine(float distance)
        {
            competitionStarting = true;
            competitionStatus   = "Competition: Pilots are taking off.";
            Dictionary <BDArmorySettings.BDATeams, List <BDModulePilotAI> > pilots = new Dictionary <BDArmorySettings.BDATeams, List <BDModulePilotAI> >();

            pilots.Add(BDArmorySettings.BDATeams.A, new List <BDModulePilotAI>());
            pilots.Add(BDArmorySettings.BDATeams.B, new List <BDModulePilotAI>());
            foreach (var v in BDATargetManager.LoadedVessels)
            {
                if (!v || !v.loaded)
                {
                    continue;
                }
                BDModulePilotAI pilot = null;
                foreach (var p in v.FindPartModulesImplementing <BDModulePilotAI>())
                {
                    pilot = p;
                    break;
                }

                if (!pilot || !pilot.weaponManager)
                {
                    continue;
                }

                pilots[BDATargetManager.BoolToTeam(pilot.weaponManager.team)].Add(pilot);
                pilot.ActivatePilot();
                pilot.standbyMode = false;
                if (pilot.weaponManager.guardMode)
                {
                    pilot.weaponManager.ToggleGuardMode();
                }
            }

            //clear target database so pilots don't attack yet
            BDATargetManager.ClearDatabase();

            if (pilots[BDArmorySettings.BDATeams.A].Count == 0 || pilots[BDArmorySettings.BDATeams.B].Count == 0)
            {
                Debug.Log("Unable to start competition mode - one or more teams is empty");
                competitionStatus = "Competition: Failed!  One or more teams is empty.";
                yield return(new WaitForSeconds(2));

                competitionStarting = false;
                yield break;
            }

            BDModulePilotAI aLeader = pilots[BDArmorySettings.BDATeams.A][0];
            BDModulePilotAI bLeader = pilots[BDArmorySettings.BDATeams.B][0];

            aLeader.weaponManager.wingCommander.CommandAllFollow();
            bLeader.weaponManager.wingCommander.CommandAllFollow();


            //wait till the leaders are airborne
            while (aLeader && bLeader && (aLeader.vessel.LandedOrSplashed || bLeader.vessel.LandedOrSplashed))
            {
                yield return(null);
            }

            if (!aLeader || !bLeader)
            {
                StopCompetition();
            }

            competitionStatus = "Competition: Sending pilots to start position.";
            Vector3 aDirection = Vector3.ProjectOnPlane(aLeader.vessel.CoM - bLeader.vessel.CoM, aLeader.vessel.upAxis).normalized;
            Vector3 bDirection = Vector3.ProjectOnPlane(bLeader.vessel.CoM - aLeader.vessel.CoM, bLeader.vessel.upAxis).normalized;

            Vector3 center       = (aLeader.vessel.CoM + bLeader.vessel.CoM) / 2f;
            Vector3 aDestination = center + (aDirection * (distance + 1250f));
            Vector3 bDestination = center + (bDirection * (distance + 1250f));

            aDestination = VectorUtils.WorldPositionToGeoCoords(aDestination, FlightGlobals.currentMainBody);
            bDestination = VectorUtils.WorldPositionToGeoCoords(bDestination, FlightGlobals.currentMainBody);

            aLeader.CommandFlyTo(aDestination);
            bLeader.CommandFlyTo(bDestination);

            Vector3 centerGPS = VectorUtils.WorldPositionToGeoCoords(center, FlightGlobals.currentMainBody);

            //wait till everyone is in position
            bool waiting = true;

            while (waiting)
            {
                waiting = false;

                if (!aLeader || !bLeader)
                {
                    StopCompetition();
                }

                if (Vector3.Distance(aLeader.transform.position, bLeader.transform.position) < distance * 1.95f)
                {
                    waiting = true;
                }
                else
                {
                    foreach (var t in pilots.Keys)
                    {
                        foreach (var p in pilots[t])
                        {
                            if (p.currentCommand == BDModulePilotAI.PilotCommands.Follow && Vector3.Distance(p.vessel.CoM, p.commandLeader.vessel.CoM) > 1000f)
                            {
                                competitionStatus = "Competition: Waiting for teams to get in position.";
                                waiting           = true;
                            }
                        }
                    }
                }

                yield return(null);
            }

            //start the match
            foreach (var t in pilots.Keys)
            {
                foreach (var p in pilots[t])
                {
                    if (!p)
                    {
                        continue;
                    }

                    //enable guard mode
                    if (!p.weaponManager.guardMode)
                    {
                        p.weaponManager.ToggleGuardMode();
                    }

                    //report all vessels
                    if (BDATargetManager.BoolToTeam(p.weaponManager.team) == BDArmorySettings.BDATeams.B)
                    {
                        BDATargetManager.ReportVessel(p.vessel, aLeader.weaponManager);
                    }
                    else
                    {
                        BDATargetManager.ReportVessel(p.vessel, bLeader.weaponManager);
                    }

                    //release command
                    p.ReleaseCommand();
                    p.defaultOrbitCoords = centerGPS;
                }
            }
            competitionStatus = "Competition starting!  Good luck!";
            yield return(new WaitForSeconds(2));

            competitionStarting = false;
        }
Beispiel #14
0
        public static TargetSignatureData GetHeatTarget(Ray ray, float scanRadius, float highpassThreshold, bool allAspect, MissileFire mf = null)
        {
            float minScore = highpassThreshold;
            float minMass  = 0.5f;
            TargetSignatureData finalData = TargetSignatureData.noTarget;
            float finalScore = 0;

            foreach (var vessel in BDATargetManager.LoadedVessels)
            {
                if (!vessel || !vessel.loaded)
                {
                    continue;
                }

                TargetInfo tInfo = vessel.gameObject.GetComponent <TargetInfo>();
                if (mf == null ||
                    !tInfo ||
                    !(mf && tInfo.isMissile && tInfo.team != BDATargetManager.BoolToTeam(mf.team) && (tInfo.missileModule.MissileState == MissileLauncher.MissileStates.Boost || tInfo.missileModule.MissileState == MissileLauncher.MissileStates.Cruise)))
                {
                    if (vessel.GetTotalMass() < minMass)
                    {
                        continue;
                    }
                }

                if (RadarUtils.TerrainCheck(ray.origin, vessel.transform.position))
                {
                    continue;
                }

                float angle = Vector3.Angle(vessel.CoM - ray.origin, ray.direction);
                if (angle < scanRadius)
                {
                    float score = 0;
                    foreach (var part in vessel.Parts)
                    {
                        if (!part)
                        {
                            continue;
                        }
                        if (!allAspect)
                        {
                            if (!Misc.CheckSightLineExactDistance(ray.origin, part.transform.position + vessel.rb_velocity, Vector3.Distance(part.transform.position, ray.origin), 5, 5))
                            {
                                continue;
                            }
                        }

                        float thisScore = (float)(part.thermalInternalFluxPrevious + part.skinTemperature) * (15 / Mathf.Max(15, angle));
                        thisScore *= Mathf.Pow(1400, 2) / Mathf.Clamp((vessel.CoM - ray.origin).sqrMagnitude, 90000, 36000000);
                        score      = Mathf.Max(score, thisScore);
                    }

                    if (vessel.LandedOrSplashed)
                    {
                        score /= 4;
                    }

                    score *= Mathf.Clamp(Vector3.Angle(vessel.transform.position - ray.origin, -VectorUtils.GetUpDirection(ray.origin)) / 90, 0.5f, 1.5f);

                    if (score > finalScore)
                    {
                        finalScore = score;
                        finalData  = new TargetSignatureData(vessel, score);
                    }
                }
            }

            heatScore  = finalScore;    //DEBUG
            flareScore = 0;             //DEBUG
            foreach (var flare in BDArmorySettings.Flares)
            {
                if (!flare)
                {
                    continue;
                }

                float angle = Vector3.Angle(flare.transform.position - ray.origin, ray.direction);
                if (angle < scanRadius)
                {
                    float score = flare.thermal * Mathf.Clamp01(15 / angle);
                    score *= Mathf.Pow(1400, 2) / Mathf.Clamp((flare.transform.position - ray.origin).sqrMagnitude, 90000, 36000000);

                    score *= Mathf.Clamp(Vector3.Angle(flare.transform.position - ray.origin, -VectorUtils.GetUpDirection(ray.origin)) / 90, 0.5f, 1.5f);

                    if (score > finalScore)
                    {
                        flareScore = score;                        //DEBUG
                        finalScore = score;
                        finalData  = new TargetSignatureData(flare, score);
                    }
                }
            }



            if (finalScore < minScore)
            {
                finalData = TargetSignatureData.noTarget;
            }

            return(finalData);
        }
Beispiel #15
0
        void UpdateAI(FlightCtrlState s)
        {
            if (weaponManager && weaponManager.guardMode && !targetVessel)
            {
                TargetInfo potentialTarget = BDATargetManager.GetLeastEngagedTarget(weaponManager);
                if (potentialTarget && potentialTarget.Vessel)
                {
                    targetVessel = potentialTarget.Vessel;
                }
            }

            if (evasiveTimer > 0 || (weaponManager && (weaponManager.missileIsIncoming || weaponManager.isChaffing || weaponManager.isFlaring || weaponManager.underFire)))
            {
                Evasive(s);
                evasiveTimer += Time.fixedDeltaTime;
                turningTimer  = 0;

                if (evasiveTimer > 5)
                {
                    evasiveTimer = 0;
                }
            }
            else if (!extending && weaponManager && targetVessel != null && targetVessel.transform != null)
            {
                if (!targetVessel.Landed)
                {
                    if (vessel.altitude < defaultAltitude && Vector3.Angle(targetVessel.transform.position - vessel.transform.position, -upDirection) < 35)
                    {
                        //dangerous if low altitude and target is far below you - don't dive into ground!
                        extending          = true;
                        lastTargetPosition = targetVessel.transform.position;
                    }

                    if (Vector3.Angle(targetVessel.transform.position - vesselTransform.position, vesselTransform.up) > 35)
                    {
                        turningTimer += Time.deltaTime;
                    }
                    else
                    {
                        turningTimer = 0;
                    }

                    debugString += "turningTimer: " + turningTimer;

                    if (turningTimer > 15)
                    {
                        //extend if turning circles for too long
                        extending          = true;
                        turningTimer       = 0;
                        lastTargetPosition = targetVessel.transform.position;
                    }
                }
                else                 //extend if too close for agm attack
                {
                    float extendDistance = Mathf.Clamp(weaponManager.guardRange - 1800, 2500, 4000);
                    float srfDist        = Vector3.Distance(GetSurfacePosition(targetVessel.transform.position), GetSurfacePosition(vessel.transform.position));

                    if (srfDist < extendDistance && Vector3.Angle(vesselTransform.up, targetVessel.transform.position - vessel.transform.position) > 45)
                    {
                        extending          = true;
                        lastTargetPosition = targetVessel.transform.position;
                    }
                }

                if (!extending)
                {
                    debugString += "\nFlying to target";
                    threatLevel  = 1;
                    FlyToTargetVessel(s, targetVessel);
                }
            }
            else
            {
                if (!extending)
                {
                    //FlyCircular(s);
                    FlyOrbit(s, defaultOrbitCoords, 2000, minSpeed, true);
                }
            }

            if (extending)
            {
                threatLevel  = 1;
                debugString += "\nExtending";
                FlyExtend(s, lastTargetPosition);
            }
        }
Beispiel #16
0
        void Awake()
        {
            if (!vessel)
            {
                vessel = GetComponent <Vessel>();
            }
            if (!vessel)
            {
                Debug.Log("TargetInfo was added to a non-vessel");
                Destroy(this);
                return;
            }

            //destroy this if a target info is already attached to the vessel
            foreach (var otherInfo in vessel.gameObject.GetComponents <TargetInfo>())
            {
                if (otherInfo != this)
                {
                    Destroy(this);
                    return;
                }
            }

            team = BDArmorySettings.BDATeams.None;

            bool foundMf = false;

            foreach (var mf in vessel.FindPartModulesImplementing <MissileFire>())
            {
                foundMf       = true;
                team          = BDATargetManager.BoolToTeam(mf.team);
                weaponManager = mf;
                break;
            }
            if (!foundMf)
            {
                foreach (var ml in vessel.FindPartModulesImplementing <MissileLauncher>())
                {
                    isMissile     = true;
                    missileModule = ml;
                    team          = BDATargetManager.BoolToTeam(ml.team);
                    break;
                }
            }

            if (team != BDArmorySettings.BDATeams.None)
            {
                if (!BDATargetManager.TargetDatabase[BDATargetManager.OtherTeam(team)].Contains(this))
                {
                    BDATargetManager.TargetDatabase[BDATargetManager.OtherTeam(team)].Add(this);
                }
            }

            friendliesEngaging = new List <MissileFire>();

            vessel.OnJustAboutToBeDestroyed += AboutToBeDestroyed;
            lifeRoutine = StartCoroutine(LifetimeRoutine());
            //add delegate to peace enable event
            BDArmorySettings.OnPeaceEnabled += OnPeaceEnabled;

            if (!isMissile && team != BDArmorySettings.BDATeams.None)
            {
                massRoutine = StartCoroutine(MassRoutine());
            }
        }
Beispiel #17
0
        /// <summary>
        /// Scans for targets in direction with field of view.
        /// Returns the direction scanned for debug
        /// </summary>
        /// <returns>The scan direction.</returns>
        /// <param name="myWpnManager">My wpn manager.</param>
        /// <param name="directionAngle">Direction angle.</param>
        /// <param name="referenceTransform">Reference transform.</param>
        /// <param name="fov">Fov.</param>
        /// <param name="results">Results.</param>
        /// <param name="maxDistance">Max distance.</param>
        public static Vector3 GuardScanInDirection(MissileFire myWpnManager, float directionAngle, Transform referenceTransform, float fov, out ViewScanResults results, float maxDistance)
        {
            fov    *= 1.1f;
            results = new ViewScanResults();
            results.foundMissile          = false;
            results.foundHeatMissile      = false;
            results.foundRadarMissile     = false;
            results.foundAGM              = false;
            results.firingAtMe            = false;
            results.missileThreatDistance = float.MaxValue;
            results.threatVessel          = null;
            results.threatWeaponManager   = null;

            if (!myWpnManager || !referenceTransform)
            {
                return(Vector3.zero);
            }

            Vector3  position      = referenceTransform.position;
            Vector3d geoPos        = VectorUtils.WorldPositionToGeoCoords(position, FlightGlobals.currentMainBody);
            Vector3  forwardVector = referenceTransform.forward;
            Vector3  upVector      = referenceTransform.up;
            Vector3  lookDirection = Quaternion.AngleAxis(directionAngle, upVector) * forwardVector;



            foreach (var vessel in BDATargetManager.LoadedVessels)
            {
                if (vessel == null)
                {
                    continue;
                }

                if (vessel.loaded)
                {
                    if (vessel == myWpnManager.vessel)
                    {
                        continue;                                                   //ignore self
                    }
                    Vector3 vesselProjectedDirection = Vector3.ProjectOnPlane(vessel.transform.position - position, upVector);
                    Vector3 vesselDirection          = vessel.transform.position - position;


                    if (Vector3.Dot(vesselDirection, lookDirection) < 0)
                    {
                        continue;
                    }

                    float vesselDistance = (vessel.transform.position - position).magnitude;

                    if (vesselDistance < maxDistance && Vector3.Angle(vesselProjectedDirection, lookDirection) < fov / 2 && Vector3.Angle(vessel.transform.position - position, -myWpnManager.transform.forward) < myWpnManager.guardAngle / 2)
                    {
                        //Debug.Log("Found vessel: " + vessel.vesselName);
                        if (TerrainCheck(referenceTransform.position, vessel.transform.position))
                        {
                            continue;                                                                                              //blocked by terrain
                        }
                        BDATargetManager.ReportVessel(vessel, myWpnManager);

                        TargetInfo tInfo;
                        if ((tInfo = vessel.GetComponent <TargetInfo>()))
                        {
                            if (tInfo.isMissile)
                            {
                                MissileLauncher missile;
                                if (missile = tInfo.missileModule)
                                {
                                    results.foundMissile = true;
                                    results.threatVessel = missile.vessel;
                                    Vector3 vectorFromMissile = myWpnManager.vessel.CoM - missile.part.transform.position;
                                    Vector3 relV        = missile.vessel.srf_velocity - myWpnManager.vessel.srf_velocity;
                                    bool    approaching = Vector3.Dot(relV, vectorFromMissile) > 0;
                                    if (missile.hasFired && missile.timeIndex > 1 && approaching && (missile.targetPosition - (myWpnManager.vessel.CoM + (myWpnManager.vessel.rb_velocity * Time.fixedDeltaTime))).sqrMagnitude < 3600)
                                    {
                                        if (missile.targetingMode == MissileLauncher.TargetingModes.Heat)
                                        {
                                            results.foundHeatMissile      = true;
                                            results.missileThreatDistance = Mathf.Min(results.missileThreatDistance, Vector3.Distance(missile.part.transform.position, myWpnManager.part.transform.position));
                                            results.threatPosition        = missile.transform.position;
                                            break;
                                        }
                                        else if (missile.targetingMode == MissileLauncher.TargetingModes.Radar)
                                        {
                                            results.foundRadarMissile     = true;
                                            results.missileThreatDistance = Mathf.Min(results.missileThreatDistance, Vector3.Distance(missile.part.transform.position, myWpnManager.part.transform.position));
                                            results.threatPosition        = missile.transform.position;
                                        }
                                        else if (missile.targetingMode == MissileLauncher.TargetingModes.Laser)
                                        {
                                            results.foundAGM = true;
                                            results.missileThreatDistance = Mathf.Min(results.missileThreatDistance, Vector3.Distance(missile.part.transform.position, myWpnManager.part.transform.position));
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                //check if its shooting guns at me
                                //if(!results.firingAtMe)       //more work, but we can't afford to be incorrect picking the closest threat
                                //{
                                foreach (var weapon in vessel.FindPartModulesImplementing <ModuleWeapon>())
                                {
                                    if (!weapon.recentlyFiring)
                                    {
                                        continue;
                                    }
                                    if (Vector3.Dot(weapon.fireTransforms[0].forward, vesselDirection) > 0)
                                    {
                                        continue;
                                    }

                                    if (Vector3.Angle(weapon.fireTransforms[0].forward, -vesselDirection) < 6500 / vesselDistance && (!results.firingAtMe || (weapon.vessel.ReferenceTransform.position - position).magnitude < (results.threatPosition - position).magnitude))
                                    {
                                        results.firingAtMe          = true;
                                        results.threatPosition      = weapon.vessel.transform.position;
                                        results.threatVessel        = weapon.vessel;
                                        results.threatWeaponManager = weapon.weaponManager;
                                        break;
                                    }
                                }
                                //}
                            }
                        }
                    }
                }
            }

            return(lookDirection);
        }
Beispiel #18
0
        public static void UpdateRadarLock(MissileFire myWpnManager, float directionAngle, Transform referenceTransform, float fov, Vector3 position, float minSignature, ModuleRadar radar, bool pingRWR, RadarWarningReceiver.RWRThreatTypes rwrType, bool radarSnapshot)
        {
            Vector3d geoPos        = VectorUtils.WorldPositionToGeoCoords(position, FlightGlobals.currentMainBody);
            Vector3  forwardVector = referenceTransform.forward;
            Vector3  upVector      = referenceTransform.up;      //VectorUtils.GetUpDirection(position);
            Vector3  lookDirection = Quaternion.AngleAxis(directionAngle, upVector) * forwardVector;

            foreach (var vessel in BDATargetManager.LoadedVessels)
            {
                if (vessel == null)
                {
                    continue;
                }
                if (!vessel.loaded)
                {
                    continue;
                }

                if (myWpnManager)
                {
                    if (vessel == myWpnManager.vessel)
                    {
                        continue;                                                   //ignore self
                    }
                }
                else if ((vessel.transform.position - position).sqrMagnitude < 3600)
                {
                    continue;
                }

                Vector3 vesselDirection = Vector3.ProjectOnPlane(vessel.CoM - position, upVector);

                if (Vector3.Angle(vesselDirection, lookDirection) < fov / 2)
                {
                    if (TerrainCheck(referenceTransform.position, vessel.transform.position))
                    {
                        continue;                                                                                          //blocked by terrain
                    }
                    float sig = float.MaxValue;
                    if (radarSnapshot && minSignature > 0)
                    {
                        sig = GetModifiedSignature(vessel, position);
                    }

                    RadarWarningReceiver.PingRWR(vessel, position, rwrType, radar.signalPersistTime);

                    float detectSig = sig;

                    VesselECMJInfo vesselJammer = vessel.GetComponent <VesselECMJInfo>();
                    if (vesselJammer)
                    {
                        sig       *= vesselJammer.rcsReductionFactor;
                        detectSig += vesselJammer.jammerStrength;
                    }

                    if (detectSig > minSignature)
                    {
                        if (vessel.vesselType == VesselType.Debris)
                        {
                            vessel.gameObject.AddComponent <TargetInfo>();
                        }
                        else if (myWpnManager != null)
                        {
                            BDATargetManager.ReportVessel(vessel, myWpnManager);
                        }

                        //radar.vesselRadarData.AddRadarContact(radar, new TargetSignatureData(vessel, detectSig), false);
                        radar.ReceiveContactData(new TargetSignatureData(vessel, detectSig), false);
                    }
                }
            }
        }