From 3f4c33778416d337d8ebefe5f5f339c6294e8b37 Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Fri, 18 May 2018 21:38:07 +0200 Subject: [PATCH 01/72] Less ballistic damage for HE bullets substracting explosive mass --- BDArmory.Core/Extension/PartExtensions.cs | 6 +----- BDArmory/Bullets/PooledBullet.cs | 15 ++++++++++++--- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/BDArmory.Core/Extension/PartExtensions.cs b/BDArmory.Core/Extension/PartExtensions.cs index eaa765a8e..d7b147570 100644 --- a/BDArmory.Core/Extension/PartExtensions.cs +++ b/BDArmory.Core/Extension/PartExtensions.cs @@ -82,8 +82,7 @@ public static void AddBallisticDamage(this Part p, float multiplier, float penetrationfactor, float bulletDmgMult, - float impactVelocity, - bool explosive) + float impactVelocity) { ////////////////////////////////////////////////////////// @@ -95,9 +94,6 @@ public static void AddBallisticDamage(this Part p, float damage_ = ((0.5f * (mass * Mathf.Pow(impactVelocity, 2))) * (BDArmorySettings.DMG_MULTIPLIER / 100) * bulletDmgMult * 1e-4f); - - //Explosive bullets should not cause much penetration damage, most damage needs to come from explosion - if (explosive) damage_ *= 0.725f; //penetration multipliers damage_ *= multiplier * Mathf.Clamp(penetrationfactor, 0 , 1.85f); diff --git a/BDArmory/Bullets/PooledBullet.cs b/BDArmory/Bullets/PooledBullet.cs index 533b7096b..4c88c3eec 100644 --- a/BDArmory/Bullets/PooledBullet.cs +++ b/BDArmory/Bullets/PooledBullet.cs @@ -502,11 +502,20 @@ private void ApplyDamage(Part hitPart, RaycastHit hit, float multiplier, float p if (BDArmorySettings.BULLET_HITS) { - BulletHitFX.CreateBulletHit(hitPart,hit.point, hit, hit.normal, hasRichocheted, caliber,penetrationfactor); + BulletHitFX.CreateBulletHit(hitPart, hit.point, hit, hit.normal, hasRichocheted, caliber, + penetrationfactor); } - hitPart.AddBallisticDamage(bulletMass, caliber, multiplier, penetrationfactor, - bulletDmgMult,impactVelocity, explosive); + if (explosive) + { + hitPart.AddBallisticDamage(bulletMass - tntMass, caliber, multiplier, penetrationfactor, + bulletDmgMult, impactVelocity); + } + else + { + hitPart.AddBallisticDamage(bulletMass, caliber, multiplier, penetrationfactor, + bulletDmgMult, impactVelocity); + } } private void CalculateDragNumericalIntegration() From 70633fd95e88a202f85cf40ae32f98f267679a9e Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Fri, 18 May 2018 21:41:59 +0200 Subject: [PATCH 02/72] Increasing a bit the forces --- BDArmory/Distribution/GameData/BDArmory/settings.cfg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BDArmory/Distribution/GameData/BDArmory/settings.cfg b/BDArmory/Distribution/GameData/BDArmory/settings.cfg index daddf922b..181c2e71c 100644 --- a/BDArmory/Distribution/GameData/BDArmory/settings.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/settings.cfg @@ -34,7 +34,7 @@ BDASettings DMG_MULTIPLIER = 100 EXP_DMG_MOD_BALLISTIC = 1.125 EXP_DMG_MOD_MISSILE = 6.75 - EXP_IMP_MOD = 0.125 + EXP_IMP_MOD = 0.250 ADVANCED_EDIT = true MAX_FIRES_PER_VESSEL = 10 FIRELIFETIME_IN_SECONDS = 90 From bd9c8f8ec95a87e59cb519db90761ead2e46f773 Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Fri, 18 May 2018 21:42:20 +0200 Subject: [PATCH 03/72] reducing hitpoints resolution to 100 round --- BDArmory.Core/Module/HitpointTracker.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/BDArmory.Core/Module/HitpointTracker.cs b/BDArmory.Core/Module/HitpointTracker.cs index 1fbe8af04..587858e67 100644 --- a/BDArmory.Core/Module/HitpointTracker.cs +++ b/BDArmory.Core/Module/HitpointTracker.cs @@ -176,9 +176,9 @@ private float CalculateTotalHitpoints() //3. final calculations hitpoints = areaCalculation * density * hitpointMultiplier; - hitpoints = Mathf.Round(hitpoints/500) * 500; + hitpoints = Mathf.Round(hitpoints/100) * 100; - if (hitpoints <= 0) hitpoints = 500; + if (hitpoints <= 0) hitpoints = 100; } else { @@ -193,7 +193,7 @@ private float CalculateTotalHitpoints() } - if (hitpoints <= 0) hitpoints = 500; + if (hitpoints <= 0) hitpoints = 100; return hitpoints; } From 601996eebcfb7870ed8ffe78bc2ba49dd7a6edb3 Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Sun, 20 May 2018 11:17:49 +0200 Subject: [PATCH 04/72] bullet mass rebalance for lower calibers --- .../GameData/BDArmory/BulletDefs/BD_Bullets.cfg | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg b/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg index 8b8fa12cb..eb1105960 100644 --- a/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg @@ -28,7 +28,7 @@ BULLET name = 7.62x39mmBullet caliber = 7.62 bulletVelocity = 718 - bulletMass = 0.0079 + bulletMass = 0.0965 //HE Bullet Values explosive = False tntMass = 0 @@ -45,7 +45,7 @@ BULLET name = 7.7x56mmBullet caliber = 7.7 bulletVelocity = 825 - bulletMass = 0.0079 + bulletMass = 0.0975 //HE Bullet Values explosive = False tntMass = 0 @@ -62,7 +62,7 @@ BULLET name = 7.92mmBullet caliber = 7.92 bulletVelocity = 825 - bulletMass = 0.0079 + bulletMass = 0.1 //HE Bullet Values explosive = False tntMass = 0 @@ -80,7 +80,7 @@ BULLET name = 9mmBullet caliber = 9 bulletVelocity = 380 - bulletMass = 0.0070 + bulletMass = 0.114 //HE Bullet Values explosive = False tntMass = 0 @@ -97,7 +97,7 @@ BULLET name = 12.7mmBullet caliber = 12.7 bulletVelocity = 890 - bulletMass = .0554 + bulletMass = .16 //HE Bullet Values explosive = False tntMass = 0 @@ -114,10 +114,10 @@ BULLET name = 12.7mmHEBullet caliber = 12.7 bulletVelocity = 890 - bulletMass = .0554 + bulletMass = .16 //HE Bullet Values explosive = True - tntMass = .0443 + tntMass = .14 blastPower = 3 blastHeat = 5 blastRadius = 2 From 85e1202a3d1ea83aff15c18fb3935d3c2b4dc4be Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Sun, 20 May 2018 11:18:09 +0200 Subject: [PATCH 05/72] No damage reduction for lowe calibers --- BDArmory.Core/Extension/PartExtensions.cs | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/BDArmory.Core/Extension/PartExtensions.cs b/BDArmory.Core/Extension/PartExtensions.cs index d7b147570..dee0d2294 100644 --- a/BDArmory.Core/Extension/PartExtensions.cs +++ b/BDArmory.Core/Extension/PartExtensions.cs @@ -95,15 +95,6 @@ public static void AddBallisticDamage(this Part p, * (BDArmorySettings.DMG_MULTIPLIER / 100) * bulletDmgMult * 1e-4f); - //penetration multipliers - damage_ *= multiplier * Mathf.Clamp(penetrationfactor, 0 , 1.85f); - - //Caliber Adjustments for Gameplay balance - if (caliber <= 30f) - { - damage_ *= 15f; - } - ////////////////////////////////////////////////////////// // Armor Reduction factors ////////////////////////////////////////////////////////// @@ -393,15 +384,6 @@ public static float DamageReduction(float armor, float damage,bool isMissile,flo } } - ///////////////////////////////// - // Caliber Adjustments - ///////////////////////////////// - - if (caliber < 20f && caliber != 0) - { - damage *= 0.625f; - } - return damage; } From 19168c16af58fdd352b62ac2b8150dd7a87794e1 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Wed, 4 Jul 2018 12:00:56 -0500 Subject: [PATCH 06/72] restore MS Compilers --- BDArmory/BDArmory.csproj | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/BDArmory/BDArmory.csproj b/BDArmory/BDArmory.csproj index ddb53dd87..9de52a2e0 100644 --- a/BDArmory/BDArmory.csproj +++ b/BDArmory/BDArmory.csproj @@ -1,5 +1,6 @@  + Debug AnyCPU @@ -377,8 +378,8 @@ - + @@ -672,4 +673,10 @@ copy /Y "%25KSP_DIR%25\KSP_x64_Data\Managed\UnityEngine.UI.dll" "$(ProjectDir)Lo @echo KSP API references copying complete! + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + \ No newline at end of file From bc5ac826765a894aa7d014c1a7545d1a548487d4 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Wed, 4 Jul 2018 13:03:38 -0500 Subject: [PATCH 07/72] cleanup formatting, organizing --- BDArmory/BDArmory.csproj | 6 +- BDArmory/RocketLauncher.cs | 1114 ------------------------------- BDArmory/TargetInfo.cs | 326 --------- BDArmory/TargetSignatureData.cs | 201 ------ 4 files changed, 3 insertions(+), 1644 deletions(-) delete mode 100644 BDArmory/RocketLauncher.cs delete mode 100644 BDArmory/TargetInfo.cs delete mode 100644 BDArmory/TargetSignatureData.cs diff --git a/BDArmory/BDArmory.csproj b/BDArmory/BDArmory.csproj index 9de52a2e0..37e3a2221 100644 --- a/BDArmory/BDArmory.csproj +++ b/BDArmory/BDArmory.csproj @@ -106,7 +106,7 @@ - + @@ -121,7 +121,7 @@ - + @@ -138,7 +138,7 @@ - + diff --git a/BDArmory/RocketLauncher.cs b/BDArmory/RocketLauncher.cs deleted file mode 100644 index 24114baf7..000000000 --- a/BDArmory/RocketLauncher.cs +++ /dev/null @@ -1,1114 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Text; -using BDArmory.Core; -using BDArmory.Core.Enum; -using BDArmory.Core.Extension; -using BDArmory.Core.Utils; -using BDArmory.FX; -using BDArmory.Misc; -using BDArmory.UI; -using UniLinq; -using UnityEngine; - -namespace BDArmory -{ - public class RocketLauncher : EngageableWeapon, IBDWeapon - { - public bool hasRocket = true; - - [KSPField] public string shortName = string.Empty; - - [KSPField(isPersistant = false)] public string rocketType; - - [KSPField(isPersistant = false)] public string rocketModelPath; - - [KSPField(isPersistant = false)] public float rocketMass; - - [KSPField(isPersistant = false)] public float thrust; - - [KSPField(isPersistant = false)] public float thrustTime; - - [KSPField(isPersistant = false)] public float blastRadius; - - [KSPField(isPersistant = false)] public float blastForce; - - [KSPField] public float blastHeat = -1; - - [KSPField(isPersistant = false)] public bool descendingOrder = true; - - [KSPField(isPersistant = false)] public string explModelPath = "BDArmory/Models/explosion/explosion"; - - [KSPField(isPersistant = false)] public string explSoundPath = "BDArmory/Sounds/explode1"; - - [KSPField] public float thrustDeviation = 0.10f; - - [KSPField] public float maxTargetingRange = 8000; - float currentTgtRange = 8000; - float predictedFlightTime = 1; - - public bool drawAimer; - - Vector3 rocketPrediction = Vector3.zero; - Texture2D aimerTexture; - - Transform[] rockets; - - public AudioSource sfAudioSource; - - //animation - [KSPField] public string deployAnimationName; - [KSPField] public float deployAnimationSpeed = 1; - AnimationState deployAnimState; - bool hasDeployAnimation; - public bool deployed; - Coroutine deployAnimRoutine; - - public bool readyToFire = true; - - public Vessel legacyGuardTarget = null; - public float lastAutoFiredTime; - public float autoRippleRate = 0; - public float autoFireStartTime = 0; - public float autoFireDuration = 0; - - //turret - [KSPField] public int turretID = 0; - public ModuleTurret turret; - Vector3 trajectoryOffset = Vector3.zero; - public MissileFire weaponManager; - bool targetInTurretView = true; - - public float yawRange - { - get { return turret ? turret.yawRange : 0; } - } - - public float maxPitch - { - get { return turret ? turret.maxPitch : 0; } - } - - public float minPitch - { - get { return turret ? turret.minPitch : 0; } - } - - Vector3 targetPosition; - public Vector3? FiringSolutionVector => targetPosition.IsZero() ? (Vector3?)null : (targetPosition - rockets[0].parent.transform.position).normalized; - - double lastRocketsLeft; - - //weapon interface - public Part GetPart() - { - return part; - } - - public string GetShortName() - { - return shortName; - } - - public WeaponClasses GetWeaponClass() - { - return WeaponClasses.Rocket; - } - - public string GetSubLabel() - { - return string.Empty; - } - - public string GetMissileType() - { - return string.Empty; - } - - - [KSPAction("Fire")] - public void AGFire(KSPActionParam param) - { - FireRocket(); - } - - [KSPEvent(guiActive = true, guiName = "Fire", active = true)] - public void GuiFire() - { - FireRocket(); - } - - [KSPEvent(guiActive = true, guiName = "Jettison", active = true, guiActiveEditor = false)] - public void Jettison() - { - if (turret) - { - return; - } - - part.decouple(0); - if (BDArmorySetup.Instance.ActiveWeaponManager != null) - BDArmorySetup.Instance.ActiveWeaponManager.UpdateList(); - } - - [KSPEvent(guiActive = false, guiName = "Toggle Turret", guiActiveEditor = false)] - public void ToggleTurret() - { - if (deployed) - { - DisableTurret(); - } - else - { - EnableTurret(); - } - } - - public void EnableTurret() - { - deployed = true; - drawAimer = true; - hasReturned = false; - - if (returnRoutine != null) - { - StopCoroutine(returnRoutine); - returnRoutine = null; - } - - if (hasDeployAnimation) - { - if (deployAnimRoutine != null) - { - StopCoroutine(deployAnimRoutine); - } - deployAnimRoutine = StartCoroutine(DeployAnimRoutine(true)); - } - else - { - readyToFire = true; - } - } - - public void DisableTurret() - { - deployed = false; - readyToFire = false; - drawAimer = false; - hasReturned = false; - targetInTurretView = false; - - if (returnRoutine != null) - { - StopCoroutine(returnRoutine); - } - returnRoutine = StartCoroutine(ReturnRoutine()); - - if (hasDeployAnimation) - { - if (deployAnimRoutine != null) - { - StopCoroutine(deployAnimRoutine); - } - - deployAnimRoutine = StartCoroutine(DeployAnimRoutine(false)); - } - } - - bool hasReturned = true; - Coroutine returnRoutine; - - IEnumerator ReturnRoutine() - { - if (deployed) - { - hasReturned = false; - yield break; - } - - yield return new WaitForSeconds(0.25f); - - while (!turret.ReturnTurret()) - { - yield return new WaitForFixedUpdate(); - } - - hasReturned = true; - } - - void SetupAudio() - { - sfAudioSource = gameObject.AddComponent(); - sfAudioSource.minDistance = 1; - sfAudioSource.maxDistance = 2000; - sfAudioSource.dopplerLevel = 0; - sfAudioSource.priority = 230; - sfAudioSource.spatialBlend = 1; - - UpdateVolume(); - BDArmorySetup.OnVolumeChange += UpdateVolume; - } - - void UpdateVolume() - { - if (sfAudioSource) - { - sfAudioSource.volume = BDArmorySettings.BDARMORY_WEAPONS_VOLUME; - } - } - - - public override void OnStart(StartState state) - { - // extension for feature_engagementenvelope - InitializeEngagementRange(0, maxTargetingRange); - - if (HighLogic.LoadedSceneIsFlight) - { - part.force_activate(); - - aimerTexture = BDArmorySetup.Instance.greenPointCircleTexture; - // GameDatabase.Instance.GetTexture("BDArmory/Textures/grayCircle", false); - - - MakeRocketArray(); - UpdateRocketScales(); - - if (shortName == string.Empty) - { - shortName = part.partInfo.title; - } - - UpdateAudio(); - BDArmorySetup.OnVolumeChange += UpdateAudio; - } - - if (HighLogic.LoadedSceneIsFlight || HighLogic.LoadedSceneIsEditor) - { - List.Enumerator turr = part.FindModulesImplementing().GetEnumerator(); - while (turr.MoveNext()) - { - if (turr.Current == null) continue; - if (turr.Current.turretID != turretID) continue; - turret = turr.Current; - targetInTurretView = false; - break; - } - turr.Dispose(); - - if (turret) - { - Events["GuiFire"].guiActive = false; - Events["Jettison"].guiActive = false; - Actions["AGFire"].active = false; - - if (HighLogic.LoadedSceneIsFlight) - { - Events["ToggleTurret"].guiActive = true; - } - } - - if (!string.IsNullOrEmpty(deployAnimationName)) - { - deployAnimState = Misc.Misc.SetUpSingleAnimation(deployAnimationName, part); - hasDeployAnimation = true; - - readyToFire = false; - } - } - SetupAudio(); - - blastForce = BlastPhysicsUtils.CalculateExplosiveMass(blastRadius); - } - - IEnumerator DeployAnimRoutine(bool forward) - { - readyToFire = false; - BDArmorySetup.Instance.UpdateCursorState(); - - if (forward) - { - while (deployAnimState.normalizedTime < 1) - { - deployAnimState.speed = deployAnimationSpeed; - yield return null; - } - - deployAnimState.normalizedTime = 1; - } - else - { - while (!hasReturned) - { - deployAnimState.speed = 0; - yield return null; - } - - while (deployAnimState.normalizedTime > 0) - { - deployAnimState.speed = -deployAnimationSpeed; - yield return null; - } - - deployAnimState.normalizedTime = 0; - } - - deployAnimState.speed = 0; - - readyToFire = deployed; - BDArmorySetup.Instance.UpdateCursorState(); - } - - void UpdateAudio() - { - if (sfAudioSource) - { - sfAudioSource.volume = BDArmorySettings.BDARMORY_WEAPONS_VOLUME; - } - } - - void OnDestroy() - { - BDArmorySetup.OnVolumeChange -= UpdateAudio; - } - - - public override void OnFixedUpdate() - { - if (GetRocketResource().amount != lastRocketsLeft) - { - UpdateRocketScales(); - lastRocketsLeft = GetRocketResource().amount; - } - - if (!vessel.IsControllable) - { - return; - } - - SimulateTrajectory(); - - currentTgtRange = maxTargetingRange; - - if (deployed && readyToFire && (turret || weaponManager?.AI?.pilotEnabled == true)) - { - Aim(); - } - else - { - targetPosition = Vector3.zero; - } - } - - public override void OnUpdate() - { - if (HighLogic.LoadedSceneIsFlight) - { - if (readyToFire && deployed) - { - if (returnRoutine != null) - { - StopCoroutine(returnRoutine); - returnRoutine = null; - } - - if (weaponManager && weaponManager.guardMode && weaponManager.selectedWeaponString == GetShortName()) - { - if (Time.time - autoFireStartTime < autoFireDuration) - { - float fireInterval = 0.5f; - if (autoRippleRate > 0) fireInterval = 60f/autoRippleRate; - if (Time.time - lastAutoFiredTime > fireInterval) - { - FireRocket(); - lastAutoFiredTime = Time.time; - } - } - } - else if ((!weaponManager || - (weaponManager.selectedWeaponString == GetShortName() && !weaponManager.guardMode))) - { - if (BDInputUtils.GetKeyDown(BDInputSettingsFields.WEAP_FIRE_KEY) && - (vessel.isActiveVessel || BDArmorySettings.REMOTE_SHOOTING)) - { - FireRocket(); - } - } - } - } - } - - bool mouseAiming; - - void Aim() - { - mouseAiming = false; - if (weaponManager && (weaponManager.slavingTurrets || weaponManager.guardMode || weaponManager.AI?.pilotEnabled == true)) - { - SlavedAim(); - } - else - { - if (vessel.isActiveVessel || BDArmorySettings.REMOTE_SHOOTING) - { - MouseAim(); - } - } - } - - void SlavedAim() - { - Vector3 targetVel; - Vector3 targetAccel; - if (weaponManager.slavingTurrets) - { - targetPosition = weaponManager.slavedPosition; - targetVel = weaponManager.slavedVelocity; - targetAccel = weaponManager.slavedAcceleration; - - //targetPosition -= vessel.Velocity * predictedFlightTime; - } - else if (legacyGuardTarget) - { - targetPosition = legacyGuardTarget.CoM; - targetVel = legacyGuardTarget.Velocity(); - targetAccel = legacyGuardTarget.acceleration; - } - else - { - targetInTurretView = false; - return; - } - - currentTgtRange = Vector3.Distance(targetPosition, rockets[0].parent.transform.position); - - - targetPosition += trajectoryOffset; - targetPosition += targetVel*predictedFlightTime; - targetPosition += 0.5f*targetAccel*predictedFlightTime*predictedFlightTime; - - turret.AimToTarget(targetPosition); - targetInTurretView = turret.TargetInRange(targetPosition, 2, maxTargetingRange); - } - - void MouseAim() - { - mouseAiming = true; - Vector3 targetPosition; - // float maxTargetingRange = 8000; - - float targetDistance; - - //MouseControl - Vector3 mouseAim = new Vector3(Input.mousePosition.x/Screen.width, Input.mousePosition.y/Screen.height, 0); - Ray ray = FlightCamera.fetch.mainCamera.ViewportPointToRay(mouseAim); - RaycastHit hit; - if (Physics.Raycast(ray, out hit, maxTargetingRange, 557057)) - { - targetPosition = hit.point; - - //aim through self vessel if occluding mouseray - Part p = hit.collider.gameObject.GetComponentInParent(); - if (p && p.vessel && p.vessel == vessel) - { - targetPosition = ray.direction*maxTargetingRange + FlightCamera.fetch.mainCamera.transform.position; - } - - targetDistance = Vector3.Distance(hit.point, rockets[0].parent.position); - } - else - { - targetPosition = (ray.direction*(maxTargetingRange + (FlightCamera.fetch.Distance*0.75f))) + - FlightCamera.fetch.mainCamera.transform.position; - targetDistance = maxTargetingRange; - } - - currentTgtRange = targetDistance; - - targetPosition += trajectoryOffset; - - - turret.AimToTarget(targetPosition); - targetInTurretView = turret.TargetInRange(targetPosition, 2, maxTargetingRange); - } - - public void FireRocket() - { - if (!readyToFire) return; - if (!targetInTurretView) return; - - PartResource rocketResource = GetRocketResource(); - - if (rocketResource == null) - { - Debug.Log(part.name + " doesn't carry the rocket resource it was meant to"); - return; - } - - int rocketsLeft = (int)Math.Floor(rocketResource.amount); - - if (BDArmorySettings.INFINITE_AMMO && rocketsLeft < 1) - rocketsLeft = 1; - - if (rocketsLeft >= 1) - { - Transform currentRocketTfm = rockets[rocketsLeft - 1]; - - GameObject rocketObj = GameDatabase.Instance.GetModel(rocketModelPath); - rocketObj = - (GameObject) Instantiate(rocketObj, currentRocketTfm.position, currentRocketTfm.parent.rotation); - rocketObj.transform.rotation = currentRocketTfm.parent.rotation; - rocketObj.transform.localScale = part.rescaleFactor*Vector3.one; - currentRocketTfm.localScale = Vector3.zero; - Rocket rocket = rocketObj.AddComponent(); - rocket.explModelPath = explModelPath; - rocket.explSoundPath = explSoundPath; - rocket.spawnTransform = currentRocketTfm; - rocket.mass = rocketMass; - rocket.blastForce = blastForce; - rocket.blastHeat = blastHeat; - rocket.blastRadius = blastRadius; - rocket.thrust = thrust; - rocket.thrustTime = thrustTime; - rocket.randomThrustDeviation = thrustDeviation; - if (BDArmorySettings.ALLOW_LEGACY_TARGETING && vessel.targetObject != null) - { - rocket.targetVessel = vessel.targetObject.GetVessel(); - } - - rocket.sourceVessel = vessel; - rocketObj.SetActive(true); - rocketObj.transform.SetParent(currentRocketTfm.parent); - rocket.parentRB = part.rb; - - sfAudioSource.PlayOneShot(GameDatabase.Instance.GetAudioClip("BDArmory/Sounds/launch")); - if (!BDArmorySettings.INFINITE_AMMO) - rocketResource.amount--; - - lastRocketsLeft = rocketResource.amount; - } - } - - - void SimulateTrajectory() - { - if ((BDArmorySettings.AIM_ASSIST && BDArmorySettings.DRAW_AIMERS && drawAimer && vessel.isActiveVessel) || - (weaponManager && weaponManager.guardMode && weaponManager.selectedWeaponString == GetShortName())) - { - float simTime = 0; - Transform fireTransform = rockets[0].parent; - Vector3 pointingDirection = fireTransform.forward; - Vector3 simVelocity = part.rb.velocity; - Vector3 simCurrPos = fireTransform.position + (part.rb.velocity*Time.fixedDeltaTime); - Vector3 simPrevPos = fireTransform.position + (part.rb.velocity*Time.fixedDeltaTime); - Vector3 simStartPos = fireTransform.position + (part.rb.velocity*Time.fixedDeltaTime); - bool simulating = true; - float simDeltaTime = 0.02f; - List pointPositions = new List(); - pointPositions.Add(simCurrPos); - - bool slaved = turret && weaponManager && (weaponManager.slavingTurrets || weaponManager.guardMode); - float atmosMultiplier = - Mathf.Clamp01(2.5f* - (float) - FlightGlobals.getAtmDensity(vessel.staticPressurekPa, vessel.externalTemperature, - vessel.mainBody)); - while (simulating) - { - RaycastHit hit; - - if (simTime > thrustTime) - { - simDeltaTime = 0.1f; - } - - if (simTime > 0.04f) - { - simDeltaTime = 0.02f; - if (simTime < thrustTime) - { - simVelocity += thrust/rocketMass*simDeltaTime*pointingDirection; - } - - //rotation (aero stabilize) - pointingDirection = Vector3.RotateTowards(pointingDirection, - simVelocity + Krakensbane.GetFrameVelocity(), - atmosMultiplier*(0.5f*(simTime))*50*simDeltaTime*Mathf.Deg2Rad, 0); - } - - //gravity - simVelocity += FlightGlobals.getGeeForceAtPosition(simCurrPos)*simDeltaTime; - - simCurrPos += simVelocity*simDeltaTime; - pointPositions.Add(simCurrPos); - if (!mouseAiming && !slaved) - { - if (simTime > 0.1f && Physics.Raycast(simPrevPos, simCurrPos - simPrevPos, out hit, - Vector3.Distance(simPrevPos, simCurrPos), 9076737)) - { - rocketPrediction = hit.point; - simulating = false; - break; - } - else if (FlightGlobals.getAltitudeAtPos(simCurrPos) < 0) - { - rocketPrediction = simCurrPos; - simulating = false; - break; - } - } - - - simPrevPos = simCurrPos; - - if ((simStartPos - simCurrPos).sqrMagnitude > currentTgtRange*currentTgtRange) - { - rocketPrediction = simStartPos + (simCurrPos - simStartPos).normalized*currentTgtRange; - //rocketPrediction = simCurrPos; - simulating = false; - } - simTime += simDeltaTime; - } - - Vector3 pointingPos = fireTransform.position + (fireTransform.forward*currentTgtRange); - trajectoryOffset = pointingPos - rocketPrediction; - predictedFlightTime = simTime; - - if (BDArmorySettings.DRAW_DEBUG_LINES && BDArmorySettings.DRAW_AIMERS) - { - Vector3[] pointsArray = pointPositions.ToArray(); - if (gameObject.GetComponent() == null) - { - LineRenderer lr = gameObject.AddComponent(); - lr.startWidth = .1f; - lr.endWidth = .1f; - lr.positionCount = pointsArray.Length; - for (int i = 0; i < pointsArray.Length; i++) - { - lr.SetPosition(i, pointsArray[i]); - } - } - else - { - LineRenderer lr = gameObject.GetComponent(); - lr.enabled = true; - lr.positionCount = pointsArray.Length; - for (int i = 0; i < pointsArray.Length; i++) - { - lr.SetPosition(i, pointsArray[i]); - } - } - } - else - { - if (gameObject.GetComponent() != null) - { - gameObject.GetComponent().enabled = false; - } - } - } - - //for straight aimer - else if (BDArmorySettings.DRAW_AIMERS && drawAimer && vessel.isActiveVessel) - { - RaycastHit hit; - float distance = 2500; - if (Physics.Raycast(transform.position, transform.forward, out hit, distance, 9076737)) - { - rocketPrediction = hit.point; - } - else - { - rocketPrediction = transform.position + (transform.forward*distance); - } - } - } - - void OnGUI() - { - if (drawAimer && vessel.isActiveVessel && BDArmorySettings.DRAW_AIMERS && !MapView.MapIsEnabled) - { - float size = 30; - - Vector3 aimPosition = FlightCamera.fetch.mainCamera.WorldToViewportPoint(rocketPrediction); - - Rect drawRect = new Rect(aimPosition.x*Screen.width - (0.5f*size), - (1 - aimPosition.y)*Screen.height - (0.5f*size), size, size); - float cameraAngle = Vector3.Angle(FlightCamera.fetch.GetCameraTransform().forward, - rocketPrediction - FlightCamera.fetch.mainCamera.transform.position); - if (cameraAngle < 90) GUI.DrawTexture(drawRect, aimerTexture); - } - } - - void MakeRocketArray() - { - Transform rocketsTransform = part.FindModelTransform("rockets"); - int numOfRockets = rocketsTransform.childCount; - rockets = new Transform[numOfRockets]; - - for (int i = 0; i < numOfRockets; i++) - { - string rocketName = rocketsTransform.GetChild(i).name; - int rocketIndex = int.Parse(rocketName.Substring(7)) - 1; - rockets[rocketIndex] = rocketsTransform.GetChild(i); - } - - if (!descendingOrder) Array.Reverse(rockets); - } - - - public PartResource GetRocketResource() - { - IEnumerator res = part.Resources.GetEnumerator(); - while (res.MoveNext()) - { - if (res.Current == null) continue; - if (res.Current.resourceName == rocketType) return res.Current; - } - res.Dispose(); - return null; - } - - void UpdateRocketScales() - { - PartResource rocketResource = GetRocketResource(); - double rocketsLeft = Math.Floor(rocketResource.amount); - double rocketsMax = rocketResource.maxAmount; - for (int i = 0; i < rocketsMax; i++) - { - if (i < rocketsLeft) rockets[i].localScale = Vector3.one; - else rockets[i].localScale = Vector3.zero; - } - } - - // RMB info in editor - public override string GetInfo() - { - StringBuilder output = new StringBuilder(); - output.Append(Environment.NewLine); - output.Append("Weapon Type: Rocket Launcher"); - output.Append(Environment.NewLine); - output.Append($"Rocket Type: {rocketType}"); - output.Append(Environment.NewLine); - output.Append($"Max Range: {maxTargetingRange} m"); - output.Append(Environment.NewLine); - - output.Append($"Blast radius/power/heat:"); - output.Append(Environment.NewLine); - output.Append($"{blastRadius} / {blastForce} / {blastHeat}"); - output.Append(Environment.NewLine); - - return output.ToString(); - - } - } - - - public class Rocket : MonoBehaviour - { - public Transform spawnTransform; - public Vessel targetVessel; - public Vessel sourceVessel; - public Vector3 startVelocity; - public float mass; - public float thrust; - public float thrustTime; - public float blastRadius; - public float blastForce; - public float blastHeat; - public string explModelPath; - public string explSoundPath; - - public float randomThrustDeviation = 0.05f; - - public Rigidbody parentRB; - - float startTime; - public AudioSource audioSource; - - Vector3 prevPosition; - Vector3 currPosition; - - - Vector3 relativePos; - - float stayTime = 0.04f; - float lifeTime = 10; - - //bool isThrusting = true; - - Rigidbody rb; - - - KSPParticleEmitter[] pEmitters; - - float randThrustSeed; - - void Start() - { - BDArmorySetup.numberOfParticleEmitters++; - - rb = gameObject.AddComponent(); - pEmitters = gameObject.GetComponentsInChildren(); - - IEnumerator pe = pEmitters.AsEnumerable().GetEnumerator(); - while (pe.MoveNext()) - { - if (pe.Current == null) continue; - if (FlightGlobals.getStaticPressure(transform.position) == 0 && pe.Current.useWorldSpace) - { - pe.Current.emit = false; - } - else if (pe.Current.useWorldSpace) - { - BDAGaplessParticleEmitter gpe = pe.Current.gameObject.AddComponent(); - gpe.rb = rb; - gpe.emit = true; - } - else - { - EffectBehaviour.AddParticleEmitter(pe.Current); - } - } - pe.Dispose(); - - prevPosition = transform.position; - currPosition = transform.position; - startTime = Time.time; - - rb.mass = mass; - rb.isKinematic = true; - //rigidbody.velocity = startVelocity; - if (!FlightGlobals.RefFrameIsRotating) rb.useGravity = false; - - rb.useGravity = false; - - randThrustSeed = UnityEngine.Random.Range(0f, 100f); - - SetupAudio(); - } - - void FixedUpdate() - { - //floatingOrigin fix - if (sourceVessel != null && - (transform.position - sourceVessel.transform.position - relativePos).sqrMagnitude > 800*800) - { - transform.position = sourceVessel.transform.position + relativePos + (rb.velocity*Time.fixedDeltaTime); - } - if (sourceVessel != null) relativePos = transform.position - sourceVessel.transform.position; - // - - - if (Time.time - startTime < stayTime && transform.parent != null) - { - transform.rotation = transform.parent.rotation; - transform.position = spawnTransform.position; - //+(transform.parent.rigidbody.velocity*Time.fixedDeltaTime); - } - else - { - if (transform.parent != null && parentRB) - { - startVelocity = parentRB.velocity; - transform.parent = null; - rb.isKinematic = false; - rb.velocity = startVelocity; - } - } - - if (rb && !rb.isKinematic) - { - //physics - if (FlightGlobals.RefFrameIsRotating) - { - rb.velocity += FlightGlobals.getGeeForceAtPosition(transform.position)*Time.fixedDeltaTime; - } - - //guidance and attitude stabilisation scales to atmospheric density. - float atmosMultiplier = - Mathf.Clamp01(2.5f* - (float) - FlightGlobals.getAtmDensity(FlightGlobals.getStaticPressure(transform.position), - FlightGlobals.getExternalTemperature(), FlightGlobals.currentMainBody)); - - //model transform. always points prograde - transform.rotation = Quaternion.RotateTowards(transform.rotation, - Quaternion.LookRotation(rb.velocity + Krakensbane.GetFrameVelocity(), transform.up), - atmosMultiplier*(0.5f*(Time.time - startTime))*50*Time.fixedDeltaTime); - - - if (Time.time - startTime < thrustTime && Time.time - startTime > stayTime) - { - float random = randomThrustDeviation*(1 - (Mathf.PerlinNoise(4*Time.time, randThrustSeed)*2)); - float random2 = randomThrustDeviation*(1 - (Mathf.PerlinNoise(randThrustSeed, 4*Time.time)*2)); - rb.AddRelativeForce(new Vector3(random, random2, thrust)); - } - } - - - if (Time.time - startTime > thrustTime) - { - //isThrusting = false; - IEnumerator pEmitter = pEmitters.AsEnumerable().GetEnumerator(); - while (pEmitter.MoveNext()) - { - if (pEmitter.Current == null) continue; - if (pEmitter.Current.useWorldSpace) - { - pEmitter.Current.minSize = Mathf.MoveTowards(pEmitter.Current.minSize, 0.1f, 0.05f); - pEmitter.Current.maxSize = Mathf.MoveTowards(pEmitter.Current.maxSize, 0.2f, 0.05f); - } - else - { - pEmitter.Current.minSize = Mathf.MoveTowards(pEmitter.Current.minSize, 0, 0.1f); - pEmitter.Current.maxSize = Mathf.MoveTowards(pEmitter.Current.maxSize, 0, 0.1f); - if (pEmitter.Current.maxSize == 0) - { - pEmitter.Current.emit = false; - } - } - } - pEmitter.Dispose(); - } - - if (Time.time - startTime > 0.1f + stayTime) - { - currPosition = transform.position; - float dist = (currPosition - prevPosition).magnitude; - Ray ray = new Ray(prevPosition, currPosition - prevPosition); - RaycastHit hit; - KerbalEVA hitEVA = null; - //if (Physics.Raycast(ray, out hit, dist, 2228224)) - //{ - // try - // { - // hitEVA = hit.collider.gameObject.GetComponentUpwards(); - // if (hitEVA != null) - // Debug.Log("[BDArmory]:Hit on kerbal confirmed!"); - // } - // catch (NullReferenceException) - // { - // Debug.Log("[BDArmory]:Whoops ran amok of the exception handler"); - // } - - // if (hitEVA && hitEVA.part.vessel != sourceVessel) - // { - // Detonate(hit.point); - // } - //} - - if (!hitEVA) - { - if (Physics.Raycast(ray, out hit, dist, 9076737)) - { - Part hitPart = null; - try - { - KerbalEVA eva = hit.collider.gameObject.GetComponentUpwards(); - hitPart = eva ? eva.part : hit.collider.gameObject.GetComponentInParent(); - } - catch (NullReferenceException) - { - } - - - if (hitPart == null || (hitPart != null && hitPart.vessel != sourceVessel)) - { - Detonate(hit.point); - } - } - else if (FlightGlobals.getAltitudeAtPos(transform.position) < 0) - { - Detonate(transform.position); - } - } - } - else if (FlightGlobals.getAltitudeAtPos(currPosition) <= 0) - { - Detonate(currPosition); - } - prevPosition = currPosition; - - if (Time.time - startTime > lifeTime) - { - Detonate(transform.position); - } - - //proxy detonation - if (targetVessel != null && - (transform.position - targetVessel.transform.position).sqrMagnitude < 0.5f*blastRadius*blastRadius) - { - Detonate(transform.position); - } - } - - void Update() - { - if (HighLogic.LoadedSceneIsFlight) - { - if (BDArmorySetup.GameIsPaused) - { - if (audioSource.isPlaying) - { - audioSource.Stop(); - } - } - else - { - if (!audioSource.isPlaying) - { - audioSource.Play(); - } - } - } - } - - void Detonate(Vector3 pos) - { - BDArmorySetup.numberOfParticleEmitters--; - - ExplosionFx.CreateExplosion(pos, BlastPhysicsUtils.CalculateExplosiveMass(blastRadius), - explModelPath, explSoundPath, true); - - IEnumerator emitter = pEmitters.AsEnumerable().GetEnumerator(); - while (emitter.MoveNext()) - { - if (emitter.Current == null) continue; - if (!emitter.Current.useWorldSpace) continue; - emitter.Current.gameObject.AddComponent(); - emitter.Current.transform.parent = null; - } - emitter.Dispose(); - Destroy(gameObject); //destroy rocket on collision - } - - - void SetupAudio() - { - audioSource = gameObject.AddComponent(); - audioSource.loop = true; - audioSource.minDistance = 1; - audioSource.maxDistance = 2000; - audioSource.dopplerLevel = 0.5f; - audioSource.volume = 0.9f*BDArmorySettings.BDARMORY_WEAPONS_VOLUME; - audioSource.pitch = 1f; - audioSource.priority = 255; - audioSource.spatialBlend = 1; - - audioSource.clip = GameDatabase.Instance.GetAudioClip("BDArmory/Sounds/rocketLoop"); - - UpdateVolume(); - BDArmorySetup.OnVolumeChange += UpdateVolume; - } - - void UpdateVolume() - { - if (audioSource) - { - audioSource.volume = BDArmorySettings.BDARMORY_WEAPONS_VOLUME; - } - } - } -} \ No newline at end of file diff --git a/BDArmory/TargetInfo.cs b/BDArmory/TargetInfo.cs deleted file mode 100644 index 05df9470d..000000000 --- a/BDArmory/TargetInfo.cs +++ /dev/null @@ -1,326 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using BDArmory.Core.Extension; -using BDArmory.Parts; -using BDArmory.UI; -using UnityEngine; - -namespace BDArmory -{ - public class TargetInfo : MonoBehaviour - { - public BDArmorySetup.BDATeams team; - public bool isMissile; - public MissileBase MissileBaseModule; - public MissileFire weaponManager; - List friendliesEngaging; - public float detectedTime; - - public float radarBaseSignature = -1; - public bool radarBaseSignatureNeedsUpdate = true; - public float radarModifiedSignature; - public float radarLockbreakFactor; - public float radarJammingDistance; - public bool alreadyScheduledRCSUpdate = false; - - - public bool isLanded - { - get - { - if (!vessel) return false; - if ( - (vessel.situation == Vessel.Situations.LANDED || - vessel.situation == Vessel.Situations.SPLASHED) && // Boats should be included - !isUnderwater //refrain from shooting subs with missiles - ) - { - - return true; - } - - else - return false; - } - } - - public bool isFlying - { - get - { - if (!vessel) return false; - if (vessel.situation == Vessel.Situations.FLYING || vessel.InOrbit()) return true; - else - return false; - } - - } - - public bool isUnderwater - { - get - { - if (!vessel) return false; - if (vessel.altitude < -20) //some boats sit slightly underwater, this is only for submersibles - { - return true; - } - else - { - return false; - } - } - } - - public bool isSplashed - { - get - { - if (!vessel) return false; - if (vessel.situation == Vessel.Situations.SPLASHED) return true; - else - return false; - } - } - - public Vector3 velocity - { - get - { - if(!vessel) return Vector3.zero; - return vessel.Velocity(); - } - } - - public Vector3 position - { - get - { - return vessel.vesselTransform.position; - } - } - - private Vessel vessel; - - public Vessel Vessel - { - get - { - return vessel; - } - set - { - vessel = value; - } - } - - public bool isThreat - { - get - { - if(!Vessel) - { - return false; - } - - if(isMissile && MissileBaseModule && !MissileBaseModule.HasMissed) - { - return true; - } - else if(weaponManager && weaponManager.vessel.IsControllable) - { - return true; - } - - return false; - } - } - - void Awake() - { - if(!vessel) - { - vessel = GetComponent(); - } - - if(!vessel) - { - //Debug.Log ("[BDArmory]: TargetInfo was added to a non-vessel"); - Destroy (this); - return; - } - - //destroy this if a target info is already attached to the vessel - IEnumerator otherInfo = vessel.gameObject.GetComponents().GetEnumerator(); - while (otherInfo.MoveNext()) - { - if ((object)otherInfo.Current != this) - { - Destroy(this); - return; - } - } - - team = BDArmorySetup.BDATeams.None; - bool foundMf = false; - List.Enumerator mf = vessel.FindPartModulesImplementing().GetEnumerator(); - while (mf.MoveNext()) - { - foundMf = true; - team = BDATargetManager.BoolToTeam(mf.Current.team); - weaponManager = mf.Current; - break; - } - mf.Dispose(); - - if(!foundMf) - { - List.Enumerator ml = vessel.FindPartModulesImplementing().GetEnumerator(); - while (ml.MoveNext()) - { - isMissile = true; - MissileBaseModule = ml.Current; - team = BDATargetManager.BoolToTeam(ml.Current.Team); - break; - } - ml.Dispose(); - } - - if(team != BDArmorySetup.BDATeams.None) - { - BDATargetManager.AddTarget(this); - } - - friendliesEngaging = new List(); - - vessel.OnJustAboutToBeDestroyed += AboutToBeDestroyed; - - //add delegate to peace enable event - BDArmorySetup.OnPeaceEnabled += OnPeaceEnabled; - - //lifeRoutine = StartCoroutine(LifetimeRoutine()); // TODO: CHECK BEHAVIOUR AND SIDE EFFECTS! - - if (!isMissile && team != BDArmorySetup.BDATeams.None) - { - GameEvents.onVesselPartCountChanged.Add(VesselModified); - //massRoutine = StartCoroutine(MassRoutine()); // TODO: CHECK BEHAVIOUR AND SIDE EFFECTS! - } - } - - void OnPeaceEnabled() - { - //Destroy(this); - } - - void OnDestroy() - { - //remove delegate from peace enable event - BDArmorySetup.OnPeaceEnabled -= OnPeaceEnabled; - vessel.OnJustAboutToBeDestroyed -= AboutToBeDestroyed; - GameEvents.onVesselPartCountChanged.Remove(VesselModified); - } - - IEnumerator UpdateRCSDelayed() - { - alreadyScheduledRCSUpdate = true; - yield return new WaitForSeconds(1.0f); - //radarBaseSignatureNeedsUpdate = true; //TODO: currently disabled to reduce stuttering effects due to more demanding radar rendering! - } - - void Update() - { - if(!vessel) - { - AboutToBeDestroyed(); - } - else - { - if((vessel.vesselType == VesselType.Debris) && (weaponManager == null)) - { - RemoveFromDatabases(); - team = BDArmorySetup.BDATeams.None; - } - } - } - - public int numFriendliesEngaging - { - get - { - if(friendliesEngaging == null) - { - return 0; - } - friendliesEngaging.RemoveAll(item => item == null); - return friendliesEngaging.Count; - } - } - - public void Engage(MissileFire mf) - { - if (mf == null || friendliesEngaging == null) - return; - - if(!friendliesEngaging.Contains(mf)) - { - friendliesEngaging?.Add(mf); - } - } - - public void Disengage(MissileFire mf) - { - if (mf == null) - return; - - friendliesEngaging?.Remove(mf); - } - - void AboutToBeDestroyed() - { - RemoveFromDatabases(); - Destroy(this); - } - - public bool IsCloser(TargetInfo otherTarget, MissileFire myMf) - { - float thisSqrDist = (position-myMf.transform.position).sqrMagnitude; - float otherSqrDist = (otherTarget.position-myMf.transform.position).sqrMagnitude; - return thisSqrDist < otherSqrDist; - } - - public void RemoveFromDatabases() - { - BDATargetManager.TargetDatabase[BDArmorySetup.BDATeams.A].Remove(this); - BDATargetManager.TargetDatabase[BDArmorySetup.BDATeams.B].Remove(this); - } - - public void VesselModified(Vessel v) - { - if (v && v == this.vessel) - { - if (!alreadyScheduledRCSUpdate) - StartCoroutine(UpdateRCSDelayed()); - } - } - - public static Vector3 TargetCOMDispersion(Vessel v) - { - Vector3 TargetCOM_ = new Vector3(0,0); - ShipConstruct sc = new ShipConstruct("ship", "temp ship", v.parts[0]); - - Vector3 size = ShipConstruction.CalculateCraftSize(sc); - - float dispersionMax = size.y; - - //float dispersionMax = 100f; - - float dispersion = Random.Range(0, dispersionMax); - - TargetCOM_ = v.CoM + new Vector3(0,dispersion); - - return TargetCOM_; - } - } -} - -; \ No newline at end of file diff --git a/BDArmory/TargetSignatureData.cs b/BDArmory/TargetSignatureData.cs deleted file mode 100644 index c254ad2a1..000000000 --- a/BDArmory/TargetSignatureData.cs +++ /dev/null @@ -1,201 +0,0 @@ -using System; -using BDArmory.Core.Extension; -using BDArmory.CounterMeasure; -using BDArmory.Misc; -using BDArmory.Radar; -using BDArmory.UI; -using UnityEngine; -using System.Collections.Generic; - -namespace BDArmory -{ - public struct TargetSignatureData : IEquatable - { - public Vector3 velocity; - public Vector3 geoPos; - public Vector3 acceleration; - public bool exists; - public float timeAcquired; - public float signalStrength; - public TargetInfo targetInfo; - public BDArmorySetup.BDATeams team; - public Vector2 pingPosition; - public VesselECMJInfo vesselJammer; - public ModuleRadar lockedByRadar; - public Vessel vessel; - bool orbital; - Orbit orbit; - - public bool Equals(TargetSignatureData other) - { - return - exists == other.exists && - geoPos == other.geoPos && - timeAcquired == other.timeAcquired; - } - - public TargetSignatureData(Vessel v, float _signalStrength) - { - orbital = v.InOrbit(); - orbit = v.orbit; - - timeAcquired = Time.time; - vessel = v; - velocity = v.Velocity(); - - geoPos = VectorUtils.WorldPositionToGeoCoords(v.CoM, v.mainBody); - acceleration = v.acceleration_immediate; - exists = true; - - signalStrength = _signalStrength; - - targetInfo = v.gameObject.GetComponent (); - - // vessel never been picked up on radar before: create new targetinfo record - if (targetInfo == null) - { - targetInfo = v.gameObject.AddComponent(); - } - - team = BDArmorySetup.BDATeams.None; - - if(targetInfo) - { - team = targetInfo.team; - targetInfo.detectedTime = Time.time; - } - else - { - List.Enumerator mf = v.FindPartModulesImplementing().GetEnumerator(); - while (mf.MoveNext()) - { - team = BDATargetManager.BoolToTeam(mf.Current.team); - break; - } - mf.Dispose(); - } - - vesselJammer = v.gameObject.GetComponent(); - - pingPosition = Vector2.zero; - lockedByRadar = null; - } - - public TargetSignatureData(CMFlare flare, float _signalStrength) - { - velocity = flare.velocity; - geoPos = VectorUtils.WorldPositionToGeoCoords(flare.transform.position, FlightGlobals.currentMainBody); - exists = true; - acceleration = Vector3.zero; - timeAcquired = Time.time; - signalStrength = _signalStrength; - targetInfo = null; - vesselJammer = null; - team = BDArmorySetup.BDATeams.None; - pingPosition = Vector2.zero; - orbital = false; - orbit = null; - lockedByRadar = null; - vessel = null; - } - - public TargetSignatureData(Vector3 _velocity, Vector3 _position, Vector3 _acceleration, bool _exists, float _signalStrength) - { - velocity = _velocity; - geoPos = VectorUtils.WorldPositionToGeoCoords(_position, FlightGlobals.currentMainBody); - acceleration = _acceleration; - exists = _exists; - timeAcquired = Time.time; - signalStrength = _signalStrength; - targetInfo = null; - vesselJammer = null; - team = BDArmorySetup.BDATeams.None; - pingPosition = Vector2.zero; - orbital = false; - orbit = null; - lockedByRadar = null; - vessel = null; - } - - public Vector3 position - { - get - { - return VectorUtils.GetWorldSurfacePostion(geoPos, FlightGlobals.currentMainBody); - } - set - { - geoPos = VectorUtils.WorldPositionToGeoCoords(value, FlightGlobals.currentMainBody); - } - } - - public Vector3 predictedPosition - { - get - { - return position + (velocity * age); - } - } - - public Vector3 predictedPositionWithChaffFactor - { - get - { - // get chaff factor of vessel and calculate decoy distortion caused by chaff echos - float decoyFactor = 0f; - Vector3 posDistortion = Vector3.zero; - - if (vessel != null) - { - // chaff check - decoyFactor = (1f - RadarUtils.GetVesselChaffFactor(vessel)); - - if (decoyFactor > 0f) - { - // with ecm on better chaff effectiveness due to higher modifiedSignature - // higher speed -> missile decoyed further "behind" where the chaff drops (also means that for head-on engagements chaff is most like less effective!) - posDistortion = (vessel.GetSrfVelocity() * -1f * Mathf.Clamp(decoyFactor * decoyFactor, 0f, 0.5f)) + (UnityEngine.Random.insideUnitSphere * UnityEngine.Random.Range(targetInfo.radarModifiedSignature, targetInfo.radarModifiedSignature * targetInfo.radarModifiedSignature) * decoyFactor); - } - } - - return position + (velocity * age) + posDistortion; - - } - } - - public float altitude - { - get - { - return geoPos.z; - } - } - - public float age - { - get - { - return (Time.time - timeAcquired); - } - } - - public static TargetSignatureData noTarget - { - get - { - return new TargetSignatureData(Vector3.zero, Vector3.zero, Vector3.zero, false, 0); - } - } - - public static void ResetTSDArray(ref TargetSignatureData[] tsdArray) - { - for(int i = 0; i < tsdArray.Length; i++) - { - tsdArray[i] = noTarget; - } - } - - - } -} - From 419b3253b46cede8e4c959a54a80aff2ed452862 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Wed, 4 Jul 2018 13:18:29 -0500 Subject: [PATCH 08/72] cleanup, add action for jettison Issue #539 --- BDArmory/Parts/MissileLauncher.cs | 287 +++++++++++++++--------------- 1 file changed, 147 insertions(+), 140 deletions(-) diff --git a/BDArmory/Parts/MissileLauncher.cs b/BDArmory/Parts/MissileLauncher.cs index 8e94f0fa9..334595b4f 100644 --- a/BDArmory/Parts/MissileLauncher.cs +++ b/BDArmory/Parts/MissileLauncher.cs @@ -14,118 +14,118 @@ using UnityEngine; namespace BDArmory.Parts -{ - public class MissileLauncher : MissileBase +{ + public class MissileLauncher : MissileBase { #region Variable Declarations [KSPField] - public string homingType = "AAM"; + public string homingType = "AAM"; [KSPField] - public string targetingType = "none"; - + public string targetingType = "none"; + public MissileTurret missileTurret = null; - public BDRotaryRail rotaryRail = null; + public BDRotaryRail rotaryRail = null; - [KSPField] - public string exhaustPrefabPath; + [KSPField] + public string exhaustPrefabPath; - [KSPField] - public string boostExhaustPrefabPath; + [KSPField] + public string boostExhaustPrefabPath; - [KSPField] - public string boostExhaustTransformName; + [KSPField] + public string boostExhaustTransformName; #region Aero [KSPField] - public bool aero = false; - [KSPField] - public float liftArea = 0.015f; - [KSPField] - public float steerMult = 0.5f; - [KSPField] - public float torqueRampUp = 30f; - Vector3 aeroTorque = Vector3.zero; - float controlAuthority; - float finalMaxTorque; - [KSPField] - public float aeroSteerDamping = 0; + public bool aero = false; + [KSPField] + public float liftArea = 0.015f; + [KSPField] + public float steerMult = 0.5f; + [KSPField] + public float torqueRampUp = 30f; + Vector3 aeroTorque = Vector3.zero; + float controlAuthority; + float finalMaxTorque; + [KSPField] + public float aeroSteerDamping = 0; #endregion [KSPField] - public float maxTorque = 90; - - [KSPField] - public float thrust = 30; - [KSPField] - public float cruiseThrust = 3; - - [KSPField] - public float boostTime = 2.2f; - [KSPField] - public float cruiseTime = 45; - [KSPField] - public float cruiseDelay = 0; - - [KSPField] - public float maxAoA = 35; - - [KSPField(isPersistant = true, guiActive = false, guiActiveEditor = false, guiName = "Direction: "), - UI_Toggle(disabledText = "Lateral", enabledText = "Forward")] - public bool decoupleForward = false; + public float maxTorque = 90; + + [KSPField] + public float thrust = 30; + [KSPField] + public float cruiseThrust = 3; + + [KSPField] + public float boostTime = 2.2f; + [KSPField] + public float cruiseTime = 45; + [KSPField] + public float cruiseDelay = 0; + + [KSPField] + public float maxAoA = 35; + + [KSPField(isPersistant = true, guiActive = false, guiActiveEditor = false, guiName = "Direction: "), + UI_Toggle(disabledText = "Lateral", enabledText = "Forward")] + public bool decoupleForward = false; [KSPField(isPersistant = true, guiActive = false, guiActiveEditor = true, guiName = "Decouple Speed"), UI_FloatRange(minValue = 0f, maxValue = 10f, stepIncrement = 0.1f, scene = UI_Scene.Editor)] public float decoupleSpeed = 0; [KSPField] - public float optimumAirspeed = 220; - - [KSPField] - public float blastRadius = 150; + public float optimumAirspeed = 220; + + [KSPField] + public float blastRadius = 150; [KSPField] public float blastPower = 25; [KSPField] - public float blastHeat = -1; + public float blastHeat = -1; [KSPField] - public float maxTurnRateDPS = 20; + public float maxTurnRateDPS = 20; [KSPField] - public bool proxyDetonate = true; - - [KSPField] - public string audioClipPath = string.Empty; + public bool proxyDetonate = true; - AudioClip thrustAudio; + [KSPField] + public string audioClipPath = string.Empty; - [KSPField] - public string boostClipPath = string.Empty; + AudioClip thrustAudio; + + [KSPField] + public string boostClipPath = string.Empty; + + AudioClip boostAudio; + + [KSPField] + public bool isSeismicCharge = false; + + [KSPField] + public float rndAngVel = 0; - AudioClip boostAudio; - - [KSPField] - public bool isSeismicCharge = false; - - [KSPField] - public float rndAngVel = 0; - [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Max Altitude"), UI_FloatRange(minValue = 0f, maxValue = 5000f, stepIncrement = 10f, scene = UI_Scene.All)] public float maxAltitude = 0f; [KSPField] - public string rotationTransformName = string.Empty; - Transform rotationTransform; + public string rotationTransformName = string.Empty; + Transform rotationTransform; - [KSPField] - public bool terminalManeuvering = false; + [KSPField] + public bool terminalManeuvering = false; [KSPField] public string terminalGuidanceType = ""; @@ -137,87 +137,87 @@ public class MissileLauncher : MissileBase public bool terminalGuidanceShouldActivate = true; [KSPField] - public string explModelPath = "BDArmory/Models/explosion/explosion"; - - public string explSoundPath = "BDArmory/Sounds/explode1"; - - [KSPField] - public bool spoolEngine = false; - - [KSPField] - public bool hasRCS = false; - [KSPField] - public float rcsThrust = 1; - float rcsRVelThreshold = 0.13f; - KSPParticleEmitter upRCS; - KSPParticleEmitter downRCS; - KSPParticleEmitter leftRCS; - KSPParticleEmitter rightRCS; - KSPParticleEmitter forwardRCS; - float rcsAudioMinInterval = 0.2f; - - private AudioSource audioSource; - public AudioSource sfAudioSource; - List pEmitters; - List gaplessEmitters; - - float cmTimer; - - //deploy animation - [KSPField] - public string deployAnimationName = ""; - - [KSPField] - public float deployedDrag = 0.02f; - - [KSPField] - public float deployTime = 0.2f; + public string explModelPath = "BDArmory/Models/explosion/explosion"; - [KSPField] - public bool useSimpleDrag = false; + public string explSoundPath = "BDArmory/Sounds/explode1"; [KSPField] - public float simpleDrag = 0.02f; + public bool spoolEngine = false; [KSPField] - public float simpleStableTorque = 5; + public bool hasRCS = false; + [KSPField] + public float rcsThrust = 1; + float rcsRVelThreshold = 0.13f; + KSPParticleEmitter upRCS; + KSPParticleEmitter downRCS; + KSPParticleEmitter leftRCS; + KSPParticleEmitter rightRCS; + KSPParticleEmitter forwardRCS; + float rcsAudioMinInterval = 0.2f; + + private AudioSource audioSource; + public AudioSource sfAudioSource; + List pEmitters; + List gaplessEmitters; + + float cmTimer; + + //deploy animation + [KSPField] + public string deployAnimationName = ""; - [KSPField] - public Vector3 simpleCoD = new Vector3(0,0,-1); + [KSPField] + public float deployedDrag = 0.02f; - [KSPField] - public float agmDescentRatio = 1.45f; - - float currentThrust; - - public bool deployed; - //public float deployedTime; - - AnimationState[] deployStates; - - bool hasPlayedFlyby; - - float debugTurnRate; + [KSPField] + public float deployTime = 0.2f; - List boosters; - [KSPField] - public bool decoupleBoosters = false; - [KSPField] - public float boosterDecoupleSpeed = 5; - [KSPField] - public float boosterMass = 0; + [KSPField] + public bool useSimpleDrag = false; - Transform vesselReferenceTransform; + [KSPField] + public float simpleDrag = 0.02f; - [KSPField] - public string boostTransformName = string.Empty; - List boostEmitters; - List boostGaplessEmitters; - - [KSPField] - public bool torpedo = false; - [KSPField] - public float waterImpactTolerance = 25; + [KSPField] + public float simpleStableTorque = 5; + + [KSPField] + public Vector3 simpleCoD = new Vector3(0, 0, -1); + + [KSPField] + public float agmDescentRatio = 1.45f; + + float currentThrust; + + public bool deployed; + //public float deployedTime; + + AnimationState[] deployStates; + + bool hasPlayedFlyby; + + float debugTurnRate; + + List boosters; + [KSPField] + public bool decoupleBoosters = false; + [KSPField] + public float boosterDecoupleSpeed = 5; + [KSPField] + public float boosterMass = 0; + + Transform vesselReferenceTransform; + + [KSPField] + public string boostTransformName = string.Empty; + List boostEmitters; + List boostGaplessEmitters; + + [KSPField] + public bool torpedo = false; + [KSPField] + public float waterImpactTolerance = 25; //ballistic options [KSPField] @@ -282,6 +282,13 @@ public override void Jettison() if (BDArmorySetup.Instance.ActiveWeaponManager != null) BDArmorySetup.Instance.ActiveWeaponManager.UpdateList(); } + [KSPAction("Jettison")] + public void AGJettsion(KSPActionParam param) + { + Jettison(); + } + + void ParseWeaponClass() { missileType = missileType.ToLower(); From 69e62d8a7e38fffe9efe8f2e9323c1c42933bd40 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Wed, 4 Jul 2018 13:22:03 -0500 Subject: [PATCH 09/72] increase default det range issue #527 --- BDArmory/ModuleWeapon.cs | 2 +- BDArmory/Parts/MissileLauncher.cs | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/BDArmory/ModuleWeapon.cs b/BDArmory/ModuleWeapon.cs index f28b5a294..b0c2e9549 100644 --- a/BDArmory/ModuleWeapon.cs +++ b/BDArmory/ModuleWeapon.cs @@ -406,7 +406,7 @@ public string GetMissileType() public bool proximityDetonation = false; [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Default Detonation Range"), - UI_FloatRange(minValue = 500, maxValue = 3500f, stepIncrement = 1f, scene = UI_Scene.All)] + UI_FloatRange(minValue = 500, maxValue = 8000f, stepIncrement = 5f, scene = UI_Scene.All)] public float defaultDetonationRange = 3500; [KSPField] diff --git a/BDArmory/Parts/MissileLauncher.cs b/BDArmory/Parts/MissileLauncher.cs index 334595b4f..b472fcd6f 100644 --- a/BDArmory/Parts/MissileLauncher.cs +++ b/BDArmory/Parts/MissileLauncher.cs @@ -286,8 +286,7 @@ public override void Jettison() public void AGJettsion(KSPActionParam param) { Jettison(); - } - + } void ParseWeaponClass() { From 91ff8e086353ba9e545504bc5d6f8115877db7e5 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Wed, 4 Jul 2018 13:30:18 -0500 Subject: [PATCH 10/72] reorg files --- BDArmory/Parts/RocketLauncher.cs | 1080 +++++++++++++++++++++ BDArmory/Targeting/TargetInfo.cs | 326 +++++++ BDArmory/Targeting/TargetSignatureData.cs | 201 ++++ 3 files changed, 1607 insertions(+) create mode 100644 BDArmory/Parts/RocketLauncher.cs create mode 100644 BDArmory/Targeting/TargetInfo.cs create mode 100644 BDArmory/Targeting/TargetSignatureData.cs diff --git a/BDArmory/Parts/RocketLauncher.cs b/BDArmory/Parts/RocketLauncher.cs new file mode 100644 index 000000000..7c4b3b8d5 --- /dev/null +++ b/BDArmory/Parts/RocketLauncher.cs @@ -0,0 +1,1080 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using BDArmory.Core; +using BDArmory.Core.Enum; +using BDArmory.Core.Extension; +using BDArmory.Core.Utils; +using BDArmory.FX; +using BDArmory.Misc; +using BDArmory.UI; +using UniLinq; +using UnityEngine; + +namespace BDArmory +{ + public class RocketLauncher : EngageableWeapon, IBDWeapon + { + public bool hasRocket = true; + [KSPField] public string shortName = string.Empty; + [KSPField(isPersistant = false)] public string rocketType; + [KSPField(isPersistant = false)] public string rocketModelPath; + [KSPField(isPersistant = false)] public float rocketMass; + [KSPField(isPersistant = false)] public float thrust; + [KSPField(isPersistant = false)] public float thrustTime; + [KSPField(isPersistant = false)] public float blastRadius; + [KSPField(isPersistant = false)] public float blastForce; + [KSPField] public float blastHeat = -1; + [KSPField(isPersistant = false)] public bool descendingOrder = true; + [KSPField(isPersistant = false)] public string explModelPath = "BDArmory/Models/explosion/explosion"; + [KSPField(isPersistant = false)] public string explSoundPath = "BDArmory/Sounds/explode1"; + [KSPField] public float thrustDeviation = 0.10f; + [KSPField] public float maxTargetingRange = 8000; + float currentTgtRange = 8000; + float predictedFlightTime = 1; + public bool drawAimer; + Vector3 rocketPrediction = Vector3.zero; + Texture2D aimerTexture; + Transform[] rockets; + public AudioSource sfAudioSource; + + //animation + [KSPField] public string deployAnimationName; + [KSPField] public float deployAnimationSpeed = 1; + AnimationState deployAnimState; + bool hasDeployAnimation; + public bool deployed; + Coroutine deployAnimRoutine; + + public bool readyToFire = true; + + public Vessel legacyGuardTarget = null; + public float lastAutoFiredTime; + public float autoRippleRate = 0; + public float autoFireStartTime = 0; + public float autoFireDuration = 0; + + //turret + [KSPField] public int turretID = 0; + public ModuleTurret turret; + Vector3 trajectoryOffset = Vector3.zero; + public MissileFire weaponManager; + bool targetInTurretView = true; + + public float yawRange + { + get { return turret ? turret.yawRange : 0; } + } + + public float maxPitch + { + get { return turret ? turret.maxPitch : 0; } + } + + public float minPitch + { + get { return turret ? turret.minPitch : 0; } + } + + Vector3 targetPosition; + public Vector3? FiringSolutionVector => targetPosition.IsZero() ? (Vector3?)null : (targetPosition - rockets[0].parent.transform.position).normalized; + + double lastRocketsLeft; + + bool hasReturned = true; + Coroutine returnRoutine; + bool mouseAiming; + + //weapon interface + public Part GetPart() + { + return part; + } + + public string GetShortName() + { + return shortName; + } + + public WeaponClasses GetWeaponClass() + { + return WeaponClasses.Rocket; + } + + public string GetSubLabel() + { + return string.Empty; + } + + public string GetMissileType() + { + return string.Empty; + } + + [KSPAction("Fire")] + public void AGFire(KSPActionParam param) + { + FireRocket(); + } + + [KSPEvent(guiActive = true, guiName = "Fire", active = true)] + public void GuiFire() + { + FireRocket(); + } + + [KSPEvent(guiActive = true, guiName = "Jettison", active = true, guiActiveEditor = false)] + public void Jettison() + { + if (turret) + { + return; + } + + part.decouple(0); + if (BDArmorySetup.Instance.ActiveWeaponManager != null) + BDArmorySetup.Instance.ActiveWeaponManager.UpdateList(); + } + + [KSPEvent(guiActive = false, guiName = "Toggle Turret", guiActiveEditor = false)] + public void ToggleTurret() + { + if (deployed) + { + DisableTurret(); + } + else + { + EnableTurret(); + } + } + + public void EnableTurret() + { + deployed = true; + drawAimer = true; + hasReturned = false; + + if (returnRoutine != null) + { + StopCoroutine(returnRoutine); + returnRoutine = null; + } + + if (hasDeployAnimation) + { + if (deployAnimRoutine != null) + { + StopCoroutine(deployAnimRoutine); + } + deployAnimRoutine = StartCoroutine(DeployAnimRoutine(true)); + } + else + { + readyToFire = true; + } + } + + public void DisableTurret() + { + deployed = false; + readyToFire = false; + drawAimer = false; + hasReturned = false; + targetInTurretView = false; + + if (returnRoutine != null) + { + StopCoroutine(returnRoutine); + } + returnRoutine = StartCoroutine(ReturnRoutine()); + + if (hasDeployAnimation) + { + if (deployAnimRoutine != null) + { + StopCoroutine(deployAnimRoutine); + } + + deployAnimRoutine = StartCoroutine(DeployAnimRoutine(false)); + } + } + + IEnumerator ReturnRoutine() + { + if (deployed) + { + hasReturned = false; + yield break; + } + + yield return new WaitForSeconds(0.25f); + + while (!turret.ReturnTurret()) + { + yield return new WaitForFixedUpdate(); + } + + hasReturned = true; + } + + void SetupAudio() + { + sfAudioSource = gameObject.AddComponent(); + sfAudioSource.minDistance = 1; + sfAudioSource.maxDistance = 2000; + sfAudioSource.dopplerLevel = 0; + sfAudioSource.priority = 230; + sfAudioSource.spatialBlend = 1; + + UpdateVolume(); + BDArmorySetup.OnVolumeChange += UpdateVolume; + } + + void UpdateVolume() + { + if (sfAudioSource) + { + sfAudioSource.volume = BDArmorySettings.BDARMORY_WEAPONS_VOLUME; + } + } + + public override void OnStart(StartState state) + { + // extension for feature_engagementenvelope + InitializeEngagementRange(0, maxTargetingRange); + + if (HighLogic.LoadedSceneIsFlight) + { + part.force_activate(); + + aimerTexture = BDArmorySetup.Instance.greenPointCircleTexture; + // GameDatabase.Instance.GetTexture("BDArmory/Textures/grayCircle", false); + + + MakeRocketArray(); + UpdateRocketScales(); + + if (shortName == string.Empty) + { + shortName = part.partInfo.title; + } + + UpdateAudio(); + BDArmorySetup.OnVolumeChange += UpdateAudio; + } + + if (HighLogic.LoadedSceneIsFlight || HighLogic.LoadedSceneIsEditor) + { + List.Enumerator turr = part.FindModulesImplementing().GetEnumerator(); + while (turr.MoveNext()) + { + if (turr.Current == null) continue; + if (turr.Current.turretID != turretID) continue; + turret = turr.Current; + targetInTurretView = false; + break; + } + turr.Dispose(); + + if (turret) + { + Events["GuiFire"].guiActive = false; + Events["Jettison"].guiActive = false; + Actions["AGFire"].active = false; + + if (HighLogic.LoadedSceneIsFlight) + { + Events["ToggleTurret"].guiActive = true; + } + } + + if (!string.IsNullOrEmpty(deployAnimationName)) + { + deployAnimState = Misc.Misc.SetUpSingleAnimation(deployAnimationName, part); + hasDeployAnimation = true; + + readyToFire = false; + } + } + SetupAudio(); + + blastForce = BlastPhysicsUtils.CalculateExplosiveMass(blastRadius); + } + + IEnumerator DeployAnimRoutine(bool forward) + { + readyToFire = false; + BDArmorySetup.Instance.UpdateCursorState(); + + if (forward) + { + while (deployAnimState.normalizedTime < 1) + { + deployAnimState.speed = deployAnimationSpeed; + yield return null; + } + + deployAnimState.normalizedTime = 1; + } + else + { + while (!hasReturned) + { + deployAnimState.speed = 0; + yield return null; + } + + while (deployAnimState.normalizedTime > 0) + { + deployAnimState.speed = -deployAnimationSpeed; + yield return null; + } + + deployAnimState.normalizedTime = 0; + } + + deployAnimState.speed = 0; + + readyToFire = deployed; + BDArmorySetup.Instance.UpdateCursorState(); + } + + void UpdateAudio() + { + if (sfAudioSource) + { + sfAudioSource.volume = BDArmorySettings.BDARMORY_WEAPONS_VOLUME; + } + } + + void OnDestroy() + { + BDArmorySetup.OnVolumeChange -= UpdateAudio; + } + + public override void OnFixedUpdate() + { + if (GetRocketResource().amount != lastRocketsLeft) + { + UpdateRocketScales(); + lastRocketsLeft = GetRocketResource().amount; + } + + if (!vessel.IsControllable) + { + return; + } + + SimulateTrajectory(); + + currentTgtRange = maxTargetingRange; + + if (deployed && readyToFire && (turret || weaponManager?.AI?.pilotEnabled == true)) + { + Aim(); + } + else + { + targetPosition = Vector3.zero; + } + } + + public override void OnUpdate() + { + if (HighLogic.LoadedSceneIsFlight) + { + if (readyToFire && deployed) + { + if (returnRoutine != null) + { + StopCoroutine(returnRoutine); + returnRoutine = null; + } + + if (weaponManager && weaponManager.guardMode && weaponManager.selectedWeaponString == GetShortName()) + { + if (Time.time - autoFireStartTime < autoFireDuration) + { + float fireInterval = 0.5f; + if (autoRippleRate > 0) fireInterval = 60f/autoRippleRate; + if (Time.time - lastAutoFiredTime > fireInterval) + { + FireRocket(); + lastAutoFiredTime = Time.time; + } + } + } + else if ((!weaponManager || + (weaponManager.selectedWeaponString == GetShortName() && !weaponManager.guardMode))) + { + if (BDInputUtils.GetKeyDown(BDInputSettingsFields.WEAP_FIRE_KEY) && + (vessel.isActiveVessel || BDArmorySettings.REMOTE_SHOOTING)) + { + FireRocket(); + } + } + } + } + } + + void Aim() + { + mouseAiming = false; + if (weaponManager && (weaponManager.slavingTurrets || weaponManager.guardMode || weaponManager.AI?.pilotEnabled == true)) + { + SlavedAim(); + } + else + { + if (vessel.isActiveVessel || BDArmorySettings.REMOTE_SHOOTING) + { + MouseAim(); + } + } + } + + void SlavedAim() + { + Vector3 targetVel; + Vector3 targetAccel; + if (weaponManager.slavingTurrets) + { + targetPosition = weaponManager.slavedPosition; + targetVel = weaponManager.slavedVelocity; + targetAccel = weaponManager.slavedAcceleration; + + //targetPosition -= vessel.Velocity * predictedFlightTime; + } + else if (legacyGuardTarget) + { + targetPosition = legacyGuardTarget.CoM; + targetVel = legacyGuardTarget.Velocity(); + targetAccel = legacyGuardTarget.acceleration; + } + else + { + targetInTurretView = false; + return; + } + + currentTgtRange = Vector3.Distance(targetPosition, rockets[0].parent.transform.position); + + + targetPosition += trajectoryOffset; + targetPosition += targetVel*predictedFlightTime; + targetPosition += 0.5f*targetAccel*predictedFlightTime*predictedFlightTime; + + turret.AimToTarget(targetPosition); + targetInTurretView = turret.TargetInRange(targetPosition, 2, maxTargetingRange); + } + + void MouseAim() + { + mouseAiming = true; + Vector3 targetPosition; + // float maxTargetingRange = 8000; + + float targetDistance; + + //MouseControl + Vector3 mouseAim = new Vector3(Input.mousePosition.x/Screen.width, Input.mousePosition.y/Screen.height, 0); + Ray ray = FlightCamera.fetch.mainCamera.ViewportPointToRay(mouseAim); + RaycastHit hit; + if (Physics.Raycast(ray, out hit, maxTargetingRange, 557057)) + { + targetPosition = hit.point; + + //aim through self vessel if occluding mouseray + Part p = hit.collider.gameObject.GetComponentInParent(); + if (p && p.vessel && p.vessel == vessel) + { + targetPosition = ray.direction*maxTargetingRange + FlightCamera.fetch.mainCamera.transform.position; + } + + targetDistance = Vector3.Distance(hit.point, rockets[0].parent.position); + } + else + { + targetPosition = (ray.direction*(maxTargetingRange + (FlightCamera.fetch.Distance*0.75f))) + + FlightCamera.fetch.mainCamera.transform.position; + targetDistance = maxTargetingRange; + } + + currentTgtRange = targetDistance; + + targetPosition += trajectoryOffset; + + + turret.AimToTarget(targetPosition); + targetInTurretView = turret.TargetInRange(targetPosition, 2, maxTargetingRange); + } + + public void FireRocket() + { + if (!readyToFire) return; + if (!targetInTurretView) return; + + PartResource rocketResource = GetRocketResource(); + + if (rocketResource == null) + { + Debug.Log(part.name + " doesn't carry the rocket resource it was meant to"); + return; + } + + int rocketsLeft = (int)Math.Floor(rocketResource.amount); + + if (BDArmorySettings.INFINITE_AMMO && rocketsLeft < 1) + rocketsLeft = 1; + + if (rocketsLeft >= 1) + { + Transform currentRocketTfm = rockets[rocketsLeft - 1]; + + GameObject rocketObj = GameDatabase.Instance.GetModel(rocketModelPath); + rocketObj = + (GameObject) Instantiate(rocketObj, currentRocketTfm.position, currentRocketTfm.parent.rotation); + rocketObj.transform.rotation = currentRocketTfm.parent.rotation; + rocketObj.transform.localScale = part.rescaleFactor*Vector3.one; + currentRocketTfm.localScale = Vector3.zero; + + Rocket rocket = rocketObj.AddComponent(); + rocket.explModelPath = explModelPath; + rocket.explSoundPath = explSoundPath; + rocket.spawnTransform = currentRocketTfm; + rocket.mass = rocketMass; + rocket.blastForce = blastForce; + rocket.blastHeat = blastHeat; + rocket.blastRadius = blastRadius; + rocket.thrust = thrust; + rocket.thrustTime = thrustTime; + rocket.randomThrustDeviation = thrustDeviation; + + if (BDArmorySettings.ALLOW_LEGACY_TARGETING && vessel.targetObject != null) + { + rocket.targetVessel = vessel.targetObject.GetVessel(); + } + + rocket.sourceVessel = vessel; + rocketObj.SetActive(true); + rocketObj.transform.SetParent(currentRocketTfm.parent); + rocket.parentRB = part.rb; + + sfAudioSource.PlayOneShot(GameDatabase.Instance.GetAudioClip("BDArmory/Sounds/launch")); + + if (!BDArmorySettings.INFINITE_AMMO) + rocketResource.amount--; + + lastRocketsLeft = rocketResource.amount; + } + } + + void SimulateTrajectory() + { + if ((BDArmorySettings.AIM_ASSIST && BDArmorySettings.DRAW_AIMERS && drawAimer && vessel.isActiveVessel) || + (weaponManager && weaponManager.guardMode && weaponManager.selectedWeaponString == GetShortName())) + { + float simTime = 0; + Transform fireTransform = rockets[0].parent; + Vector3 pointingDirection = fireTransform.forward; + Vector3 simVelocity = part.rb.velocity; + Vector3 simCurrPos = fireTransform.position + (part.rb.velocity*Time.fixedDeltaTime); + Vector3 simPrevPos = fireTransform.position + (part.rb.velocity*Time.fixedDeltaTime); + Vector3 simStartPos = fireTransform.position + (part.rb.velocity*Time.fixedDeltaTime); + bool simulating = true; + float simDeltaTime = 0.02f; + List pointPositions = new List(); + pointPositions.Add(simCurrPos); + + bool slaved = turret && weaponManager && (weaponManager.slavingTurrets || weaponManager.guardMode); + float atmosMultiplier = + Mathf.Clamp01(2.5f* + (float) + FlightGlobals.getAtmDensity(vessel.staticPressurekPa, vessel.externalTemperature, + vessel.mainBody)); + while (simulating) + { + RaycastHit hit; + + if (simTime > thrustTime) + { + simDeltaTime = 0.1f; + } + + if (simTime > 0.04f) + { + simDeltaTime = 0.02f; + if (simTime < thrustTime) + { + simVelocity += thrust/rocketMass*simDeltaTime*pointingDirection; + } + + //rotation (aero stabilize) + pointingDirection = Vector3.RotateTowards(pointingDirection, + simVelocity + Krakensbane.GetFrameVelocity(), + atmosMultiplier*(0.5f*(simTime))*50*simDeltaTime*Mathf.Deg2Rad, 0); + } + + //gravity + simVelocity += FlightGlobals.getGeeForceAtPosition(simCurrPos)*simDeltaTime; + + simCurrPos += simVelocity*simDeltaTime; + pointPositions.Add(simCurrPos); + if (!mouseAiming && !slaved) + { + if (simTime > 0.1f && Physics.Raycast(simPrevPos, simCurrPos - simPrevPos, out hit, + Vector3.Distance(simPrevPos, simCurrPos), 9076737)) + { + rocketPrediction = hit.point; + simulating = false; + break; + } + else if (FlightGlobals.getAltitudeAtPos(simCurrPos) < 0) + { + rocketPrediction = simCurrPos; + simulating = false; + break; + } + } + + + simPrevPos = simCurrPos; + + if ((simStartPos - simCurrPos).sqrMagnitude > currentTgtRange*currentTgtRange) + { + rocketPrediction = simStartPos + (simCurrPos - simStartPos).normalized*currentTgtRange; + //rocketPrediction = simCurrPos; + simulating = false; + } + simTime += simDeltaTime; + } + + Vector3 pointingPos = fireTransform.position + (fireTransform.forward*currentTgtRange); + trajectoryOffset = pointingPos - rocketPrediction; + predictedFlightTime = simTime; + + if (BDArmorySettings.DRAW_DEBUG_LINES && BDArmorySettings.DRAW_AIMERS) + { + Vector3[] pointsArray = pointPositions.ToArray(); + if (gameObject.GetComponent() == null) + { + LineRenderer lr = gameObject.AddComponent(); + lr.startWidth = .1f; + lr.endWidth = .1f; + lr.positionCount = pointsArray.Length; + for (int i = 0; i < pointsArray.Length; i++) + { + lr.SetPosition(i, pointsArray[i]); + } + } + else + { + LineRenderer lr = gameObject.GetComponent(); + lr.enabled = true; + lr.positionCount = pointsArray.Length; + for (int i = 0; i < pointsArray.Length; i++) + { + lr.SetPosition(i, pointsArray[i]); + } + } + } + else + { + if (gameObject.GetComponent() != null) + { + gameObject.GetComponent().enabled = false; + } + } + } + + //for straight aimer + else if (BDArmorySettings.DRAW_AIMERS && drawAimer && vessel.isActiveVessel) + { + RaycastHit hit; + float distance = 2500; + if (Physics.Raycast(transform.position, transform.forward, out hit, distance, 9076737)) + { + rocketPrediction = hit.point; + } + else + { + rocketPrediction = transform.position + (transform.forward*distance); + } + } + } + + void OnGUI() + { + if (drawAimer && vessel.isActiveVessel && BDArmorySettings.DRAW_AIMERS && !MapView.MapIsEnabled) + { + float size = 30; + + Vector3 aimPosition = FlightCamera.fetch.mainCamera.WorldToViewportPoint(rocketPrediction); + + Rect drawRect = new Rect(aimPosition.x*Screen.width - (0.5f*size), + (1 - aimPosition.y)*Screen.height - (0.5f*size), size, size); + float cameraAngle = Vector3.Angle(FlightCamera.fetch.GetCameraTransform().forward, + rocketPrediction - FlightCamera.fetch.mainCamera.transform.position); + if (cameraAngle < 90) GUI.DrawTexture(drawRect, aimerTexture); + } + } + + void MakeRocketArray() + { + Transform rocketsTransform = part.FindModelTransform("rockets"); + int numOfRockets = rocketsTransform.childCount; + rockets = new Transform[numOfRockets]; + + for (int i = 0; i < numOfRockets; i++) + { + string rocketName = rocketsTransform.GetChild(i).name; + int rocketIndex = int.Parse(rocketName.Substring(7)) - 1; + rockets[rocketIndex] = rocketsTransform.GetChild(i); + } + + if (!descendingOrder) Array.Reverse(rockets); + } + + public PartResource GetRocketResource() + { + IEnumerator res = part.Resources.GetEnumerator(); + while (res.MoveNext()) + { + if (res.Current == null) continue; + if (res.Current.resourceName == rocketType) return res.Current; + } + res.Dispose(); + return null; + } + + void UpdateRocketScales() + { + PartResource rocketResource = GetRocketResource(); + double rocketsLeft = Math.Floor(rocketResource.amount); + double rocketsMax = rocketResource.maxAmount; + for (int i = 0; i < rocketsMax; i++) + { + if (i < rocketsLeft) rockets[i].localScale = Vector3.one; + else rockets[i].localScale = Vector3.zero; + } + } + + // RMB info in editor + public override string GetInfo() + { + StringBuilder output = new StringBuilder(); + output.Append(Environment.NewLine); + output.Append("Weapon Type: Rocket Launcher"); + output.Append(Environment.NewLine); + output.Append($"Rocket Type: {rocketType}"); + output.Append(Environment.NewLine); + output.Append($"Max Range: {maxTargetingRange} m"); + output.Append(Environment.NewLine); + + output.Append($"Blast radius/power/heat:"); + output.Append(Environment.NewLine); + output.Append($"{blastRadius} / {blastForce} / {blastHeat}"); + output.Append(Environment.NewLine); + + return output.ToString(); + + } + } + + + public class Rocket : MonoBehaviour + { + public Transform spawnTransform; + public Vessel targetVessel; + public Vessel sourceVessel; + public Vector3 startVelocity; + public float mass; + public float thrust; + public float thrustTime; + public float blastRadius; + public float blastForce; + public float blastHeat; + public string explModelPath; + public string explSoundPath; + public float randomThrustDeviation = 0.05f; + public Rigidbody parentRB; + float startTime; + public AudioSource audioSource; + Vector3 prevPosition; + Vector3 currPosition; + Vector3 relativePos; + float stayTime = 0.04f; + float lifeTime = 10; + //bool isThrusting = true; + Rigidbody rb; + KSPParticleEmitter[] pEmitters; + float randThrustSeed; + + void Start() + { + BDArmorySetup.numberOfParticleEmitters++; + + rb = gameObject.AddComponent(); + pEmitters = gameObject.GetComponentsInChildren(); + + IEnumerator pe = pEmitters.AsEnumerable().GetEnumerator(); + while (pe.MoveNext()) + { + if (pe.Current == null) continue; + if (FlightGlobals.getStaticPressure(transform.position) == 0 && pe.Current.useWorldSpace) + { + pe.Current.emit = false; + } + else if (pe.Current.useWorldSpace) + { + BDAGaplessParticleEmitter gpe = pe.Current.gameObject.AddComponent(); + gpe.rb = rb; + gpe.emit = true; + } + else + { + EffectBehaviour.AddParticleEmitter(pe.Current); + } + } + pe.Dispose(); + + prevPosition = transform.position; + currPosition = transform.position; + startTime = Time.time; + + rb.mass = mass; + rb.isKinematic = true; + //rigidbody.velocity = startVelocity; + if (!FlightGlobals.RefFrameIsRotating) rb.useGravity = false; + + rb.useGravity = false; + + randThrustSeed = UnityEngine.Random.Range(0f, 100f); + + SetupAudio(); + } + + void FixedUpdate() + { + //floatingOrigin fix + if (sourceVessel != null && + (transform.position - sourceVessel.transform.position - relativePos).sqrMagnitude > 800*800) + { + transform.position = sourceVessel.transform.position + relativePos + (rb.velocity*Time.fixedDeltaTime); + } + if (sourceVessel != null) relativePos = transform.position - sourceVessel.transform.position; + // + + + if (Time.time - startTime < stayTime && transform.parent != null) + { + transform.rotation = transform.parent.rotation; + transform.position = spawnTransform.position; + //+(transform.parent.rigidbody.velocity*Time.fixedDeltaTime); + } + else + { + if (transform.parent != null && parentRB) + { + startVelocity = parentRB.velocity; + transform.parent = null; + rb.isKinematic = false; + rb.velocity = startVelocity; + } + } + + if (rb && !rb.isKinematic) + { + //physics + if (FlightGlobals.RefFrameIsRotating) + { + rb.velocity += FlightGlobals.getGeeForceAtPosition(transform.position)*Time.fixedDeltaTime; + } + + //guidance and attitude stabilisation scales to atmospheric density. + float atmosMultiplier = + Mathf.Clamp01(2.5f* + (float) + FlightGlobals.getAtmDensity(FlightGlobals.getStaticPressure(transform.position), + FlightGlobals.getExternalTemperature(), FlightGlobals.currentMainBody)); + + //model transform. always points prograde + transform.rotation = Quaternion.RotateTowards(transform.rotation, + Quaternion.LookRotation(rb.velocity + Krakensbane.GetFrameVelocity(), transform.up), + atmosMultiplier*(0.5f*(Time.time - startTime))*50*Time.fixedDeltaTime); + + + if (Time.time - startTime < thrustTime && Time.time - startTime > stayTime) + { + float random = randomThrustDeviation*(1 - (Mathf.PerlinNoise(4*Time.time, randThrustSeed)*2)); + float random2 = randomThrustDeviation*(1 - (Mathf.PerlinNoise(randThrustSeed, 4*Time.time)*2)); + rb.AddRelativeForce(new Vector3(random, random2, thrust)); + } + } + + + if (Time.time - startTime > thrustTime) + { + //isThrusting = false; + IEnumerator pEmitter = pEmitters.AsEnumerable().GetEnumerator(); + while (pEmitter.MoveNext()) + { + if (pEmitter.Current == null) continue; + if (pEmitter.Current.useWorldSpace) + { + pEmitter.Current.minSize = Mathf.MoveTowards(pEmitter.Current.minSize, 0.1f, 0.05f); + pEmitter.Current.maxSize = Mathf.MoveTowards(pEmitter.Current.maxSize, 0.2f, 0.05f); + } + else + { + pEmitter.Current.minSize = Mathf.MoveTowards(pEmitter.Current.minSize, 0, 0.1f); + pEmitter.Current.maxSize = Mathf.MoveTowards(pEmitter.Current.maxSize, 0, 0.1f); + if (pEmitter.Current.maxSize == 0) + { + pEmitter.Current.emit = false; + } + } + } + pEmitter.Dispose(); + } + + if (Time.time - startTime > 0.1f + stayTime) + { + currPosition = transform.position; + float dist = (currPosition - prevPosition).magnitude; + Ray ray = new Ray(prevPosition, currPosition - prevPosition); + RaycastHit hit; + KerbalEVA hitEVA = null; + //if (Physics.Raycast(ray, out hit, dist, 2228224)) + //{ + // try + // { + // hitEVA = hit.collider.gameObject.GetComponentUpwards(); + // if (hitEVA != null) + // Debug.Log("[BDArmory]:Hit on kerbal confirmed!"); + // } + // catch (NullReferenceException) + // { + // Debug.Log("[BDArmory]:Whoops ran amok of the exception handler"); + // } + + // if (hitEVA && hitEVA.part.vessel != sourceVessel) + // { + // Detonate(hit.point); + // } + //} + + if (!hitEVA) + { + if (Physics.Raycast(ray, out hit, dist, 9076737)) + { + Part hitPart = null; + try + { + KerbalEVA eva = hit.collider.gameObject.GetComponentUpwards(); + hitPart = eva ? eva.part : hit.collider.gameObject.GetComponentInParent(); + } + catch (NullReferenceException) + { + } + + + if (hitPart == null || (hitPart != null && hitPart.vessel != sourceVessel)) + { + Detonate(hit.point); + } + } + else if (FlightGlobals.getAltitudeAtPos(transform.position) < 0) + { + Detonate(transform.position); + } + } + } + else if (FlightGlobals.getAltitudeAtPos(currPosition) <= 0) + { + Detonate(currPosition); + } + prevPosition = currPosition; + + if (Time.time - startTime > lifeTime) + { + Detonate(transform.position); + } + + //proxy detonation + if (targetVessel != null && + (transform.position - targetVessel.transform.position).sqrMagnitude < 0.5f*blastRadius*blastRadius) + { + Detonate(transform.position); + } + } + + void Update() + { + if (HighLogic.LoadedSceneIsFlight) + { + if (BDArmorySetup.GameIsPaused) + { + if (audioSource.isPlaying) + { + audioSource.Stop(); + } + } + else + { + if (!audioSource.isPlaying) + { + audioSource.Play(); + } + } + } + } + + void Detonate(Vector3 pos) + { + BDArmorySetup.numberOfParticleEmitters--; + + ExplosionFx.CreateExplosion(pos, BlastPhysicsUtils.CalculateExplosiveMass(blastRadius), + explModelPath, explSoundPath, true); + + IEnumerator emitter = pEmitters.AsEnumerable().GetEnumerator(); + while (emitter.MoveNext()) + { + if (emitter.Current == null) continue; + if (!emitter.Current.useWorldSpace) continue; + emitter.Current.gameObject.AddComponent(); + emitter.Current.transform.parent = null; + } + emitter.Dispose(); + Destroy(gameObject); //destroy rocket on collision + } + + void SetupAudio() + { + audioSource = gameObject.AddComponent(); + audioSource.loop = true; + audioSource.minDistance = 1; + audioSource.maxDistance = 2000; + audioSource.dopplerLevel = 0.5f; + audioSource.volume = 0.9f*BDArmorySettings.BDARMORY_WEAPONS_VOLUME; + audioSource.pitch = 1f; + audioSource.priority = 255; + audioSource.spatialBlend = 1; + + audioSource.clip = GameDatabase.Instance.GetAudioClip("BDArmory/Sounds/rocketLoop"); + + UpdateVolume(); + BDArmorySetup.OnVolumeChange += UpdateVolume; + } + + void UpdateVolume() + { + if (audioSource) + { + audioSource.volume = BDArmorySettings.BDARMORY_WEAPONS_VOLUME; + } + } + } +} \ No newline at end of file diff --git a/BDArmory/Targeting/TargetInfo.cs b/BDArmory/Targeting/TargetInfo.cs new file mode 100644 index 000000000..05df9470d --- /dev/null +++ b/BDArmory/Targeting/TargetInfo.cs @@ -0,0 +1,326 @@ +using System.Collections; +using System.Collections.Generic; +using BDArmory.Core.Extension; +using BDArmory.Parts; +using BDArmory.UI; +using UnityEngine; + +namespace BDArmory +{ + public class TargetInfo : MonoBehaviour + { + public BDArmorySetup.BDATeams team; + public bool isMissile; + public MissileBase MissileBaseModule; + public MissileFire weaponManager; + List friendliesEngaging; + public float detectedTime; + + public float radarBaseSignature = -1; + public bool radarBaseSignatureNeedsUpdate = true; + public float radarModifiedSignature; + public float radarLockbreakFactor; + public float radarJammingDistance; + public bool alreadyScheduledRCSUpdate = false; + + + public bool isLanded + { + get + { + if (!vessel) return false; + if ( + (vessel.situation == Vessel.Situations.LANDED || + vessel.situation == Vessel.Situations.SPLASHED) && // Boats should be included + !isUnderwater //refrain from shooting subs with missiles + ) + { + + return true; + } + + else + return false; + } + } + + public bool isFlying + { + get + { + if (!vessel) return false; + if (vessel.situation == Vessel.Situations.FLYING || vessel.InOrbit()) return true; + else + return false; + } + + } + + public bool isUnderwater + { + get + { + if (!vessel) return false; + if (vessel.altitude < -20) //some boats sit slightly underwater, this is only for submersibles + { + return true; + } + else + { + return false; + } + } + } + + public bool isSplashed + { + get + { + if (!vessel) return false; + if (vessel.situation == Vessel.Situations.SPLASHED) return true; + else + return false; + } + } + + public Vector3 velocity + { + get + { + if(!vessel) return Vector3.zero; + return vessel.Velocity(); + } + } + + public Vector3 position + { + get + { + return vessel.vesselTransform.position; + } + } + + private Vessel vessel; + + public Vessel Vessel + { + get + { + return vessel; + } + set + { + vessel = value; + } + } + + public bool isThreat + { + get + { + if(!Vessel) + { + return false; + } + + if(isMissile && MissileBaseModule && !MissileBaseModule.HasMissed) + { + return true; + } + else if(weaponManager && weaponManager.vessel.IsControllable) + { + return true; + } + + return false; + } + } + + void Awake() + { + if(!vessel) + { + vessel = GetComponent(); + } + + if(!vessel) + { + //Debug.Log ("[BDArmory]: TargetInfo was added to a non-vessel"); + Destroy (this); + return; + } + + //destroy this if a target info is already attached to the vessel + IEnumerator otherInfo = vessel.gameObject.GetComponents().GetEnumerator(); + while (otherInfo.MoveNext()) + { + if ((object)otherInfo.Current != this) + { + Destroy(this); + return; + } + } + + team = BDArmorySetup.BDATeams.None; + bool foundMf = false; + List.Enumerator mf = vessel.FindPartModulesImplementing().GetEnumerator(); + while (mf.MoveNext()) + { + foundMf = true; + team = BDATargetManager.BoolToTeam(mf.Current.team); + weaponManager = mf.Current; + break; + } + mf.Dispose(); + + if(!foundMf) + { + List.Enumerator ml = vessel.FindPartModulesImplementing().GetEnumerator(); + while (ml.MoveNext()) + { + isMissile = true; + MissileBaseModule = ml.Current; + team = BDATargetManager.BoolToTeam(ml.Current.Team); + break; + } + ml.Dispose(); + } + + if(team != BDArmorySetup.BDATeams.None) + { + BDATargetManager.AddTarget(this); + } + + friendliesEngaging = new List(); + + vessel.OnJustAboutToBeDestroyed += AboutToBeDestroyed; + + //add delegate to peace enable event + BDArmorySetup.OnPeaceEnabled += OnPeaceEnabled; + + //lifeRoutine = StartCoroutine(LifetimeRoutine()); // TODO: CHECK BEHAVIOUR AND SIDE EFFECTS! + + if (!isMissile && team != BDArmorySetup.BDATeams.None) + { + GameEvents.onVesselPartCountChanged.Add(VesselModified); + //massRoutine = StartCoroutine(MassRoutine()); // TODO: CHECK BEHAVIOUR AND SIDE EFFECTS! + } + } + + void OnPeaceEnabled() + { + //Destroy(this); + } + + void OnDestroy() + { + //remove delegate from peace enable event + BDArmorySetup.OnPeaceEnabled -= OnPeaceEnabled; + vessel.OnJustAboutToBeDestroyed -= AboutToBeDestroyed; + GameEvents.onVesselPartCountChanged.Remove(VesselModified); + } + + IEnumerator UpdateRCSDelayed() + { + alreadyScheduledRCSUpdate = true; + yield return new WaitForSeconds(1.0f); + //radarBaseSignatureNeedsUpdate = true; //TODO: currently disabled to reduce stuttering effects due to more demanding radar rendering! + } + + void Update() + { + if(!vessel) + { + AboutToBeDestroyed(); + } + else + { + if((vessel.vesselType == VesselType.Debris) && (weaponManager == null)) + { + RemoveFromDatabases(); + team = BDArmorySetup.BDATeams.None; + } + } + } + + public int numFriendliesEngaging + { + get + { + if(friendliesEngaging == null) + { + return 0; + } + friendliesEngaging.RemoveAll(item => item == null); + return friendliesEngaging.Count; + } + } + + public void Engage(MissileFire mf) + { + if (mf == null || friendliesEngaging == null) + return; + + if(!friendliesEngaging.Contains(mf)) + { + friendliesEngaging?.Add(mf); + } + } + + public void Disengage(MissileFire mf) + { + if (mf == null) + return; + + friendliesEngaging?.Remove(mf); + } + + void AboutToBeDestroyed() + { + RemoveFromDatabases(); + Destroy(this); + } + + public bool IsCloser(TargetInfo otherTarget, MissileFire myMf) + { + float thisSqrDist = (position-myMf.transform.position).sqrMagnitude; + float otherSqrDist = (otherTarget.position-myMf.transform.position).sqrMagnitude; + return thisSqrDist < otherSqrDist; + } + + public void RemoveFromDatabases() + { + BDATargetManager.TargetDatabase[BDArmorySetup.BDATeams.A].Remove(this); + BDATargetManager.TargetDatabase[BDArmorySetup.BDATeams.B].Remove(this); + } + + public void VesselModified(Vessel v) + { + if (v && v == this.vessel) + { + if (!alreadyScheduledRCSUpdate) + StartCoroutine(UpdateRCSDelayed()); + } + } + + public static Vector3 TargetCOMDispersion(Vessel v) + { + Vector3 TargetCOM_ = new Vector3(0,0); + ShipConstruct sc = new ShipConstruct("ship", "temp ship", v.parts[0]); + + Vector3 size = ShipConstruction.CalculateCraftSize(sc); + + float dispersionMax = size.y; + + //float dispersionMax = 100f; + + float dispersion = Random.Range(0, dispersionMax); + + TargetCOM_ = v.CoM + new Vector3(0,dispersion); + + return TargetCOM_; + } + } +} + +; \ No newline at end of file diff --git a/BDArmory/Targeting/TargetSignatureData.cs b/BDArmory/Targeting/TargetSignatureData.cs new file mode 100644 index 000000000..c254ad2a1 --- /dev/null +++ b/BDArmory/Targeting/TargetSignatureData.cs @@ -0,0 +1,201 @@ +using System; +using BDArmory.Core.Extension; +using BDArmory.CounterMeasure; +using BDArmory.Misc; +using BDArmory.Radar; +using BDArmory.UI; +using UnityEngine; +using System.Collections.Generic; + +namespace BDArmory +{ + public struct TargetSignatureData : IEquatable + { + public Vector3 velocity; + public Vector3 geoPos; + public Vector3 acceleration; + public bool exists; + public float timeAcquired; + public float signalStrength; + public TargetInfo targetInfo; + public BDArmorySetup.BDATeams team; + public Vector2 pingPosition; + public VesselECMJInfo vesselJammer; + public ModuleRadar lockedByRadar; + public Vessel vessel; + bool orbital; + Orbit orbit; + + public bool Equals(TargetSignatureData other) + { + return + exists == other.exists && + geoPos == other.geoPos && + timeAcquired == other.timeAcquired; + } + + public TargetSignatureData(Vessel v, float _signalStrength) + { + orbital = v.InOrbit(); + orbit = v.orbit; + + timeAcquired = Time.time; + vessel = v; + velocity = v.Velocity(); + + geoPos = VectorUtils.WorldPositionToGeoCoords(v.CoM, v.mainBody); + acceleration = v.acceleration_immediate; + exists = true; + + signalStrength = _signalStrength; + + targetInfo = v.gameObject.GetComponent (); + + // vessel never been picked up on radar before: create new targetinfo record + if (targetInfo == null) + { + targetInfo = v.gameObject.AddComponent(); + } + + team = BDArmorySetup.BDATeams.None; + + if(targetInfo) + { + team = targetInfo.team; + targetInfo.detectedTime = Time.time; + } + else + { + List.Enumerator mf = v.FindPartModulesImplementing().GetEnumerator(); + while (mf.MoveNext()) + { + team = BDATargetManager.BoolToTeam(mf.Current.team); + break; + } + mf.Dispose(); + } + + vesselJammer = v.gameObject.GetComponent(); + + pingPosition = Vector2.zero; + lockedByRadar = null; + } + + public TargetSignatureData(CMFlare flare, float _signalStrength) + { + velocity = flare.velocity; + geoPos = VectorUtils.WorldPositionToGeoCoords(flare.transform.position, FlightGlobals.currentMainBody); + exists = true; + acceleration = Vector3.zero; + timeAcquired = Time.time; + signalStrength = _signalStrength; + targetInfo = null; + vesselJammer = null; + team = BDArmorySetup.BDATeams.None; + pingPosition = Vector2.zero; + orbital = false; + orbit = null; + lockedByRadar = null; + vessel = null; + } + + public TargetSignatureData(Vector3 _velocity, Vector3 _position, Vector3 _acceleration, bool _exists, float _signalStrength) + { + velocity = _velocity; + geoPos = VectorUtils.WorldPositionToGeoCoords(_position, FlightGlobals.currentMainBody); + acceleration = _acceleration; + exists = _exists; + timeAcquired = Time.time; + signalStrength = _signalStrength; + targetInfo = null; + vesselJammer = null; + team = BDArmorySetup.BDATeams.None; + pingPosition = Vector2.zero; + orbital = false; + orbit = null; + lockedByRadar = null; + vessel = null; + } + + public Vector3 position + { + get + { + return VectorUtils.GetWorldSurfacePostion(geoPos, FlightGlobals.currentMainBody); + } + set + { + geoPos = VectorUtils.WorldPositionToGeoCoords(value, FlightGlobals.currentMainBody); + } + } + + public Vector3 predictedPosition + { + get + { + return position + (velocity * age); + } + } + + public Vector3 predictedPositionWithChaffFactor + { + get + { + // get chaff factor of vessel and calculate decoy distortion caused by chaff echos + float decoyFactor = 0f; + Vector3 posDistortion = Vector3.zero; + + if (vessel != null) + { + // chaff check + decoyFactor = (1f - RadarUtils.GetVesselChaffFactor(vessel)); + + if (decoyFactor > 0f) + { + // with ecm on better chaff effectiveness due to higher modifiedSignature + // higher speed -> missile decoyed further "behind" where the chaff drops (also means that for head-on engagements chaff is most like less effective!) + posDistortion = (vessel.GetSrfVelocity() * -1f * Mathf.Clamp(decoyFactor * decoyFactor, 0f, 0.5f)) + (UnityEngine.Random.insideUnitSphere * UnityEngine.Random.Range(targetInfo.radarModifiedSignature, targetInfo.radarModifiedSignature * targetInfo.radarModifiedSignature) * decoyFactor); + } + } + + return position + (velocity * age) + posDistortion; + + } + } + + public float altitude + { + get + { + return geoPos.z; + } + } + + public float age + { + get + { + return (Time.time - timeAcquired); + } + } + + public static TargetSignatureData noTarget + { + get + { + return new TargetSignatureData(Vector3.zero, Vector3.zero, Vector3.zero, false, 0); + } + } + + public static void ResetTSDArray(ref TargetSignatureData[] tsdArray) + { + for(int i = 0; i < tsdArray.Length; i++) + { + tsdArray[i] = noTarget; + } + } + + + } +} + From 06361f80d2339c4546ca417b5b56d505ff42c0de Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Sun, 8 Jul 2018 15:17:55 -0500 Subject: [PATCH 11/72] whitespace --- BDArmory/ModuleWeapon.cs | 2 ++ BDArmory/Radar/ModuleRadar.cs | 56 ++++++++++------------------------- 2 files changed, 18 insertions(+), 40 deletions(-) diff --git a/BDArmory/ModuleWeapon.cs b/BDArmory/ModuleWeapon.cs index b0c2e9549..bec0ddd49 100644 --- a/BDArmory/ModuleWeapon.cs +++ b/BDArmory/ModuleWeapon.cs @@ -261,6 +261,8 @@ public string GetMissileType() public float bulletDmgMult = 1; //Used for heat damage modifier for non-explosive bullets [KSPField] public float bulletVelocity = 1030; //velocity in meters/second + [KSPField] + public float ECPerShot = 0; //EC to use per shot for weapons like railguns [KSPField] public string bulletDragTypeName = "AnalyticEstimate"; diff --git a/BDArmory/Radar/ModuleRadar.cs b/BDArmory/Radar/ModuleRadar.cs index 41007c7c9..3ab19d573 100644 --- a/BDArmory/Radar/ModuleRadar.cs +++ b/BDArmory/Radar/ModuleRadar.cs @@ -118,7 +118,6 @@ public class ModuleRadar : PartModule #endregion - #region KSP Events & Actions [KSPAction("Toggle Radar")] public void AGEnable(KSPActionParam param) @@ -160,7 +159,6 @@ public void TargetPrev(KSPActionParam param) #endregion - #region Part members //locks [KSPField(isPersistant = false, guiActive = true, guiActiveEditor = false, guiName = "Current Locks")] @@ -265,15 +263,13 @@ public MissileFire weaponManager public float leftLimit; public float rightLimit; private int snapshotTicker; - #endregion - + #endregion void UpdateToggleGuiName() { Events["Toggle"].guiName = radarEnabled ? "Disable Radar" : "Enable Radar"; } - public void EnsureVesselRadarData() { @@ -289,7 +285,6 @@ public void EnsureVesselRadarData() vesselRadarData.weaponManager = weaponManager; } } - public void EnableRadar() { @@ -312,7 +307,6 @@ public void EnableRadar() UpdateToggleGuiName(); vesselRadarData.AddRadar(this); } - public void DisableRadar() { @@ -338,7 +332,6 @@ public void DisableRadar() vrd.Dispose(); } - void OnDestroy() { if (HighLogic.LoadedSceneIsFlight) @@ -369,7 +362,6 @@ void OnDestroy() } } - public override void OnStart(StartState state) { base.OnStart(state); @@ -450,7 +442,6 @@ public override void OnStart(StartState state) Debug.Log("[BDArmory]: WARNING: " + part.name + " has legacy definition, missing new radarDetectionCurve and radarLockTrackCurve definitions! Please update for the part to be usable!"); } } - /* void OnGoOnRails(Vessel v) { @@ -487,8 +478,7 @@ IEnumerator StartUpRoutine() UpdateToggleGuiName(); startupComplete = true; } - - + void Update() { if (HighLogic.LoadedSceneIsFlight && FlightGlobals.ready && !vessel.packed && radarEnabled) @@ -512,8 +502,7 @@ void Update() drawGUI = (HighLogic.LoadedSceneIsFlight && FlightGlobals.ready && !vessel.packed && radarEnabled && vessel.isActiveVessel && BDArmorySetup.GAME_UI_ENABLED && !MapView.MapIsEnabled); } - - + void FixedUpdate() { if (HighLogic.LoadedSceneIsFlight && FlightGlobals.ready && startupComplete) @@ -551,8 +540,7 @@ void FixedUpdate() } } - - + void UpdateSlaveData() { if (slaveTurrets && weaponManager) @@ -567,8 +555,7 @@ void UpdateSlaveData() } } } - - + void LateUpdate() { if (HighLogic.LoadedSceneIsFlight && (canScan || canLock)) @@ -576,8 +563,7 @@ void LateUpdate() UpdateModel(); } } - - + void UpdateModel() { //model rotation @@ -633,8 +619,7 @@ void UpdateModel() } } } - - + void Scan() { float angleDelta = scanRotationSpeed*Time.fixedDeltaTime; @@ -680,7 +665,6 @@ void Scan() } } - public bool TryLockTarget(Vector3 position) { if (!canLock) @@ -710,7 +694,7 @@ public bool TryLockTarget(Vector3 position) for (int i = 0; i < attemptedLocks.Length; i++) { - if (attemptedLocks[i].exists && (attemptedLocks[i].predictedPosition - position).sqrMagnitude < 40*40) + if (attemptedLocks[i].exists && (attemptedLocks[i].predictedPosition - position).sqrMagnitude < 40 * 40) { if (!locked && !omnidirectional) { @@ -735,9 +719,8 @@ public bool TryLockTarget(Vector3 position) Debug.Log("[BDArmory]: - Failed to lock on target."); return false; - } + } - void BoresightScan() { if (locked) @@ -757,8 +740,7 @@ void BoresightScan() return; } } - - + void UpdateLock(int index) { TargetSignatureData lockedTarget = lockedTargets[index]; @@ -834,8 +816,7 @@ void UpdateLock(int index) } } } - - + public void UnlockAllTargets() { if (!locked) return; @@ -852,8 +833,7 @@ public void UnlockAllTargets() if (BDArmorySettings.DRAW_DEBUG_LABELS) Debug.Log("[BDArmory]: Radar Targets were cleared (" + radarName + ")."); } - - + public void SetActiveLock(TargetSignatureData target) { for (int i = 0; i < lockedTargets.Count; i++) @@ -865,8 +845,7 @@ public void SetActiveLock(TargetSignatureData target) } } } - - + public void UnlockTargetAt(int index, bool tryRelock = false) { Vessel rVess = lockedTargets[index].vessel; @@ -898,15 +877,13 @@ public void UnlockTargetAt(int index, bool tryRelock = false) vesselRadarData.RemoveVesselFromTargets(rVess); } } - - + IEnumerator RetryLockRoutine(Vessel v) { yield return null; vesselRadarData.TryLockTarget(v); } - - + public void UnlockTargetVessel(Vessel v) { for (int i = 0; i < lockedTargets.Count; i++) @@ -918,8 +895,7 @@ public void UnlockTargetVessel(Vessel v) } } } - - + void SlaveTurrets() { List.Enumerator mtc = vessel.FindPartModulesImplementing().GetEnumerator(); From 038afbfcca8a6c03c0a8a014709b4714dab58d75 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Sun, 8 Jul 2018 15:21:19 -0500 Subject: [PATCH 12/72] whitespace --- BDArmory/Radar/ModuleRadar.cs | 34 +++++++++++----------------------- 1 file changed, 11 insertions(+), 23 deletions(-) diff --git a/BDArmory/Radar/ModuleRadar.cs b/BDArmory/Radar/ModuleRadar.cs index 3ab19d573..645bd00a0 100644 --- a/BDArmory/Radar/ModuleRadar.cs +++ b/BDArmory/Radar/ModuleRadar.cs @@ -916,8 +916,7 @@ void SlaveTurrets() slaveTurrets = true; } - - + void UnslaveTurrets() { List.Enumerator mtc = vessel.FindPartModulesImplementing().GetEnumerator(); @@ -941,8 +940,7 @@ void UnslaveTurrets() slaveTurrets = false; } - - + public void UpdateLockedTargetInfo(TargetSignatureData newData) { int index = -1; @@ -958,8 +956,7 @@ public void UpdateLockedTargetInfo(TargetSignatureData newData) lockedTargets[index] = newData; } } - - + public void ReceiveContactData(TargetSignatureData contactData, bool _locked) { if (vesselRadarData) @@ -978,8 +975,7 @@ public void ReceiveContactData(TargetSignatureData contactData, bool _locked) } vrd.Dispose(); } - - + public void AddExternalVRD(VesselRadarData vrd) { if (!linkedToVessels.Contains(vrd)) @@ -987,14 +983,12 @@ public void AddExternalVRD(VesselRadarData vrd) linkedToVessels.Add(vrd); } } - - + public void RemoveExternalVRD(VesselRadarData vrd) { linkedToVessels.Remove(vrd); } - - + void OnGUI() { if (drawGUI) @@ -1006,8 +1000,7 @@ void OnGUI() } } } - - + public void RecoverLinkedVessels() { string[] vesselIDs = linkedVesselID.Split(new char[] {','}); @@ -1016,8 +1009,7 @@ public void RecoverLinkedVessels() StartCoroutine(RecoverLinkedVesselRoutine(vesselIDs[i])); } } - - + IEnumerator RecoverLinkedVesselRoutine(string vesselID) { while (true) @@ -1037,8 +1029,7 @@ IEnumerator RecoverLinkedVesselRoutine(string vesselID) yield return new WaitForSeconds(0.5f); } } - - + IEnumerator RelinkVRDWhenReadyRoutine(VesselRadarData vrd) { while (!vrd.radarsReady || vrd.vessel.packed) @@ -1050,8 +1041,7 @@ IEnumerator RelinkVRDWhenReadyRoutine(VesselRadarData vrd) Debug.Log("[BDArmory]: Radar data link recovered: Local - " + vessel.vesselName + ", External - " + vrd.vessel.vesselName); } - - + public string getRWRType(int i) { switch (i) @@ -1074,7 +1064,6 @@ public string getRWRType(int i) //{SAM = 0, Fighter = 1, AWACS = 2, MissileLaunch = 3, MissileLock = 4, Detection = 5, Sonar = 6} } - // RMB info in editor public override string GetInfo() { @@ -1130,8 +1119,7 @@ public override string GetInfo() return output.ToString(); } - - + void DrainElectricity() { if (resourceDrain <= 0) From 8146622b90a5e44f5196d03181be6cc1edb58eb4 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Sun, 8 Jul 2018 16:16:28 -0500 Subject: [PATCH 13/72] adding ecpershot option for weapons #486 --- BDArmory/BDArmory.csproj | 1 + BDArmory/ModuleWeapon.cs | 34 ++++++++++++++++++++++++++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/BDArmory/BDArmory.csproj b/BDArmory/BDArmory.csproj index 37e3a2221..5cec25fe5 100644 --- a/BDArmory/BDArmory.csproj +++ b/BDArmory/BDArmory.csproj @@ -90,6 +90,7 @@ + diff --git a/BDArmory/ModuleWeapon.cs b/BDArmory/ModuleWeapon.cs index bec0ddd49..e5482e00b 100644 --- a/BDArmory/ModuleWeapon.cs +++ b/BDArmory/ModuleWeapon.cs @@ -980,8 +980,9 @@ private void Fire() //Transform[] fireTransforms = part.FindModelTransforms("fireTransform"); for (int i = 0; i < fireTransforms.Length; i++) { - if ((BDArmorySettings.INFINITE_AMMO || part.RequestResource(ammoName, requestResourceAmount) > 0)) - { + //if ((BDArmorySettings.INFINITE_AMMO || part.RequestResource(ammoName, requestResourceAmount) > 0)) + if (CanFire()) + { Transform fireTransform = fireTransforms[i]; spinningDown = false; @@ -1211,6 +1212,8 @@ private void Fire() //heat heat += heatPerShot; + //EC + DrainECPerShot(); } else { @@ -1444,6 +1447,33 @@ void ParseWeaponType() } } + void DrainECPerShot() + { + if (ECPerShot == 0) return; + //double drainAmount = ECPerShot * TimeWarp.fixedDeltaTime; + double drainAmount = ECPerShot; + double chargeAvailable = part.RequestResource("ElectricCharge", drainAmount, ResourceFlowMode.ALL_VESSEL); + } + + bool CanFire() + { + if ((BDArmorySettings.INFINITE_AMMO || part.RequestResource(ammoName, requestResourceAmount) > 0)) + { + if (ECPerShot != 0) + { + double chargeAvailable = part.RequestResource("ElectricCharge", ECPerShot, ResourceFlowMode.ALL_VESSEL); + if (chargeAvailable < ECPerShot * 0.95f) + { + ScreenMessages.PostScreenMessage("Weapon Requires EC", 5.0f, ScreenMessageStyle.UPPER_CENTER); + return false; + } + } + + return true; + } + + return false; + } #endregion From 9a9b7af56c529e5416c084e85d67f578df5ec879 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Sun, 8 Jul 2018 16:28:53 -0500 Subject: [PATCH 14/72] ec pershot logic --- BDArmory/ModuleWeapon.cs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/BDArmory/ModuleWeapon.cs b/BDArmory/ModuleWeapon.cs index e5482e00b..13793aaa9 100644 --- a/BDArmory/ModuleWeapon.cs +++ b/BDArmory/ModuleWeapon.cs @@ -1457,18 +1457,19 @@ void DrainECPerShot() bool CanFire() { - if ((BDArmorySettings.INFINITE_AMMO || part.RequestResource(ammoName, requestResourceAmount) > 0)) + + if (ECPerShot != 0) { - if (ECPerShot != 0) + double chargeAvailable = part.RequestResource("ElectricCharge", ECPerShot, ResourceFlowMode.ALL_VESSEL); + if (chargeAvailable < ECPerShot * 0.95f) { - double chargeAvailable = part.RequestResource("ElectricCharge", ECPerShot, ResourceFlowMode.ALL_VESSEL); - if (chargeAvailable < ECPerShot * 0.95f) - { - ScreenMessages.PostScreenMessage("Weapon Requires EC", 5.0f, ScreenMessageStyle.UPPER_CENTER); - return false; - } + ScreenMessages.PostScreenMessage("Weapon Requires EC", 5.0f, ScreenMessageStyle.UPPER_CENTER); + return false; } + } + if ((BDArmorySettings.INFINITE_AMMO || part.RequestResource(ammoName, requestResourceAmount) > 0)) + { return true; } From 1cc800df4df68a98eeef67552b9689c13e03c562 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Sun, 8 Jul 2018 16:38:31 -0500 Subject: [PATCH 15/72] starting on #515, need logic input --- BDArmory.Core/BDAPersistantSettingsField.cs | 2 -- BDArmory.Core/BDArmorySettings.cs | 1 + BDArmory/Distribution/GameData/BDArmory/settings.cfg | 9 +++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/BDArmory.Core/BDAPersistantSettingsField.cs b/BDArmory.Core/BDAPersistantSettingsField.cs index 0fe21d16a..e2b14653b 100644 --- a/BDArmory.Core/BDAPersistantSettingsField.cs +++ b/BDArmory.Core/BDAPersistantSettingsField.cs @@ -12,7 +12,6 @@ public class BDAPersistantSettingsField : Attribute public BDAPersistantSettingsField() { } - public static void Save() { ConfigNode fileNode = ConfigNode.Load(BDArmorySettings.settingsConfigURL); @@ -34,7 +33,6 @@ public static void Save() field.Dispose(); fileNode.Save(BDArmorySettings.settingsConfigURL); } - public static void Load() { ConfigNode fileNode = ConfigNode.Load(BDArmorySettings.settingsConfigURL); diff --git a/BDArmory.Core/BDArmorySettings.cs b/BDArmory.Core/BDArmorySettings.cs index 5314edd81..1b4598fbc 100644 --- a/BDArmory.Core/BDArmorySettings.cs +++ b/BDArmory.Core/BDArmorySettings.cs @@ -48,6 +48,7 @@ public class BDArmorySettings [BDAPersistantSettingsField] public static float RECOIL_FACTOR = 0.75f; [BDAPersistantSettingsField] public static float DMG_MULTIPLIER = 100f; + [BDAPersistantSettingsField] public static float BALLISTIC_DMG_FACTOR = 1f; [BDAPersistantSettingsField] public static float HITPOINT_MULTIPLIER = 2.0f; [BDAPersistantSettingsField] public static float EXP_DMG_MOD_BALLISTIC; [BDAPersistantSettingsField] public static float EXP_DMG_MOD_MISSILE; diff --git a/BDArmory/Distribution/GameData/BDArmory/settings.cfg b/BDArmory/Distribution/GameData/BDArmory/settings.cfg index d14874b21..70cc16192 100644 --- a/BDArmory/Distribution/GameData/BDArmory/settings.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/settings.cfg @@ -5,8 +5,8 @@ BDASettings PHYSICS_RANGE = 200000 MAX_BULLET_RANGE = 8000 MAX_GUARD_VISUAL_RANGE = 200000 - MAX_ACTIVE_RADAR_RANGE = 200000 - MAX_ENGAGEMENT_RANGE = 200000 + MAX_ACTIVE_RADAR_RANGE = 200000 + MAX_ENGAGEMENT_RANGE = 200000 EJECT_SHELLS = True INFINITE_AMMO = False DRAW_DEBUG_LINES = False @@ -23,8 +23,8 @@ BDASettings SMOKE_DEFLECTION_FACTOR = 10 FLARE_THERMAL = 1350 RWR_WINDOW_SIZE = 1.0 - RADAR_WINDOW_SIZE = 1.0 - BDARMORY_UI_VOLUME = 0.35 + RADAR_WINDOW_SIZE = 1.0 + BDARMORY_UI_VOLUME = 0.35 BDARMORY_WEAPONS_VOLUME = 0.45 GLOBAL_LIFT_MULTIPLIER = 0.25 GLOBAL_DRAG_MULTIPLIER = 6 @@ -34,6 +34,7 @@ BDASettings HITPOINT_MULTIPLIER = 2.0 RECOIL_FACTOR = 0.75 DMG_MULTIPLIER = 100 + BALLISTIC_DMG_FACTOR = 1 EXP_DMG_MOD_BALLISTIC = 1.125 EXP_DMG_MOD_MISSILE = 6.75 EXP_IMP_MOD = 0.125 From 0718ce1f2488d92e3d7c02e38be51c75af459c79 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Sun, 8 Jul 2018 17:30:14 -0500 Subject: [PATCH 16/72] 120mm bullet adjust --- .../BDArmory/BulletDefs/BD_Bullets.cfg | 36 ++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg b/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg index eb1105960..eb34c92ed 100644 --- a/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg @@ -629,7 +629,24 @@ BULLET { name = 120mmBullet caliber = 120 - bulletVelocity = 1750 + bulletVelocity = 850 + bulletMass = 12 + //HE Bullet Values + explosive = False + tntMass = 0 + blastPower = 0 + blastHeat = 0 + blastRadius = 0 + apBulletMod = 6 + bulletDragTypeName = AnalyticEstimate + +} + +BULLET +{ + name = 120mmBulletHE + caliber = 120 + bulletVelocity = 850 bulletMass = 19.6 //HE Bullet Values explosive = True @@ -642,6 +659,23 @@ BULLET } +BULLET +{ + name = 120mmBulletSabot + caliber = 120 + bulletVelocity = 1750 + bulletMass = 19.6 + //HE Bullet Values + explosive = False + tntMass = 0 + blastPower = 0 + blastHeat = 0 + blastRadius = 0 + apBulletMod = 20 + bulletDragTypeName = AnalyticEstimate + +} + BULLET { name = 122mmBullet From a60facc6bcc88274bf47fa938565535baae8f8ee Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Mon, 9 Jul 2018 19:34:34 -0500 Subject: [PATCH 17/72] work in progress --- BDArmory/BDArmory.csproj | 5 +- BDArmory/UI/BDATargetManager.cs | 1039 ------------------------------- 2 files changed, 1 insertion(+), 1043 deletions(-) delete mode 100644 BDArmory/UI/BDATargetManager.cs diff --git a/BDArmory/BDArmory.csproj b/BDArmory/BDArmory.csproj index 8f2d09d5d..e139951ac 100644 --- a/BDArmory/BDArmory.csproj +++ b/BDArmory/BDArmory.csproj @@ -88,7 +88,6 @@ - @@ -121,7 +120,7 @@ - + @@ -138,8 +137,6 @@ - - diff --git a/BDArmory/UI/BDATargetManager.cs b/BDArmory/UI/BDATargetManager.cs deleted file mode 100644 index 9a2ef10f0..000000000 --- a/BDArmory/UI/BDATargetManager.cs +++ /dev/null @@ -1,1039 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using BDArmory.Core.Extension; -using BDArmory.CounterMeasure; -using BDArmory.Misc; -using BDArmory.Parts; -using BDArmory.Radar; -using KSP.UI.Screens; -using UnityEngine; -using System.Text; -using System; -using BDArmory.Core; -using BDArmory.Modules; - -namespace BDArmory.UI -{ - [KSPAddon(KSPAddon.Startup.Flight, false)] - public class BDATargetManager : MonoBehaviour - { - public static Dictionary> TargetDatabase; - public static Dictionary> GPSTargets; - public static List ActiveLasers; - public static List FiredMissiles; - public static List LoadedBuildings; - public static List LoadedVessels; - public static BDATargetManager Instance; - - private StringBuilder debugString = new StringBuilder(); - private float updateTimer = 0; - - public static bool hasAddedButton; - - void Awake() - { - GameEvents.onGameStateLoad.Add(LoadGPSTargets); - GameEvents.onGameStateSave.Add(SaveGPSTargets); - LoadedBuildings = new List(); - DestructibleBuilding.OnLoaded.Add(AddBuilding); - LoadedVessels = new List(); - GameEvents.onVesselLoaded.Add(AddVessel); - GameEvents.onVesselGoOnRails.Add(RemoveVessel); - GameEvents.onVesselGoOffRails.Add(AddVessel); - GameEvents.onVesselCreate.Add(AddVessel); - GameEvents.onVesselDestroy.Add(CleanVesselList); - - Instance = this; - } - - void OnDestroy() - { - if(GameEvents.onGameStateLoad != null && GameEvents.onGameStateSave != null) - { - GameEvents.onGameStateLoad.Remove(LoadGPSTargets); - GameEvents.onGameStateSave.Remove(SaveGPSTargets); - } - - GPSTargets = new Dictionary>(); - GPSTargets.Add(BDArmorySetup.BDATeams.A, new List()); - GPSTargets.Add(BDArmorySetup.BDATeams.B, new List()); - - GameEvents.onVesselLoaded.Remove(AddVessel); - GameEvents.onVesselGoOnRails.Remove(RemoveVessel); - GameEvents.onVesselGoOffRails.Remove(AddVessel); - GameEvents.onVesselCreate.Remove(AddVessel); - GameEvents.onVesselDestroy.Remove(CleanVesselList); - } - - void Start() - { - //legacy targetDatabase - TargetDatabase = new Dictionary>(); - TargetDatabase.Add(BDArmorySetup.BDATeams.A, new List()); - TargetDatabase.Add(BDArmorySetup.BDATeams.B, new List()); - StartCoroutine(CleanDatabaseRoutine()); - - if(GPSTargets == null) - { - GPSTargets = new Dictionary>(); - GPSTargets.Add(BDArmorySetup.BDATeams.A, new List()); - GPSTargets.Add(BDArmorySetup.BDATeams.B, new List()); - } - - //Laser points - ActiveLasers = new List(); - - FiredMissiles = new List(); - - //AddToolbarButton(); - StartCoroutine(ToolbarButtonRoutine()); - - } - - void AddBuilding(DestructibleBuilding b) - { - if(!LoadedBuildings.Contains(b)) - { - LoadedBuildings.Add(b); - } - - LoadedBuildings.RemoveAll(x => x == null); - } - - void AddVessel(Vessel v) - { - if(!LoadedVessels.Contains(v)) - { - LoadedVessels.Add(v); - } - CleanVesselList(v); - } - - void RemoveVessel(Vessel v) - { - if(v != null) - { - LoadedVessels.Remove(v); - } - CleanVesselList(v); - } - - void CleanVesselList(Vessel v) - { - LoadedVessels.RemoveAll(ves => ves == null); - LoadedVessels.RemoveAll(ves => ves.loaded == false); - } - - void AddToolbarButton() - { - if(HighLogic.LoadedSceneIsFlight) - { - if(!hasAddedButton) - { - Texture buttonTexture = GameDatabase.Instance.GetTexture(BDArmorySetup.textureDir + "icon", false); - ApplicationLauncher.Instance.AddModApplication(ShowToolbarGUI, HideToolbarGUI, Dummy, Dummy, Dummy, Dummy, ApplicationLauncher.AppScenes.FLIGHT, buttonTexture); - hasAddedButton = true; - - } - } - } - - IEnumerator ToolbarButtonRoutine() - { - if(hasAddedButton) yield break; - if(!HighLogic.LoadedSceneIsFlight) yield break; - while(!ApplicationLauncher.Ready) - { - yield return null; - } - - AddToolbarButton(); - } - public void ShowToolbarGUI() - { - BDArmorySetup.windowBDAToolBarEnabled = true; - } - - public void HideToolbarGUI() - { - BDArmorySetup.windowBDAToolBarEnabled = false; - } - void Dummy() - {} - - void Update() - { - if (BDArmorySettings.DRAW_DEBUG_LABELS && FlightGlobals.ready) - { - updateTimer -= Time.fixedDeltaTime; - if (updateTimer < 0) - { - UpdateDebugLabels(); - updateTimer = 0.5f; //next update in half a sec only - } - } - - } - - public static void RegisterLaserPoint(ModuleTargetingCamera cam) - { - if(ActiveLasers.Contains(cam)) - { - return; - } - else - { - ActiveLasers.Add(cam); - } - } - - ///// - ///// Gets the laser target painter with the least angle off boresight. Set the missileBase as the reference missilePosition. - ///// - ///// The laser target painter. - ///// Reference missilePosition. - ///// Max bore sight. - //public static ModuleTargetingCamera GetLaserTarget(MissileLauncher ml, bool parentOnly) - //{ - // return GetModuleTargeting(parentOnly, ml.transform.forward, ml.transform.position, ml.maxOffBoresight, ml.vessel, ml.SourceVessel); - // } - - // public static ModuleTargetingCamera GetLaserTarget(BDModularGuidance ml, bool parentOnly) - // { - // float maxOffBoresight = 45; - - // return GetModuleTargeting(parentOnly, ml.MissileReferenceTransform.forward, ml.MissileReferenceTransform.position, maxOffBoresight,ml.vessel,ml.SourceVessel); - // } - - /// - /// Gets the laser target painter with the least angle off boresight. Set the missileBase as the reference missilePosition. - /// - /// The laser target painter. - public static ModuleTargetingCamera GetLaserTarget(MissileBase ml, bool parentOnly) - { - return GetModuleTargeting(parentOnly, ml.GetForwardTransform(), ml.MissileReferenceTransform.position, ml.maxOffBoresight, ml.vessel, ml.SourceVessel); - } - - private static ModuleTargetingCamera GetModuleTargeting(bool parentOnly, Vector3 missilePosition, Vector3 position, float maxOffBoresight,Vessel vessel, Vessel sourceVessel) - { - ModuleTargetingCamera finalCam = null; - float smallestAngle = 360; - List.Enumerator cam = ActiveLasers.GetEnumerator(); - while (cam.MoveNext()) - { - if (cam.Current == null) continue; - if (parentOnly && !(cam.Current.vessel == vessel || cam.Current.vessel == sourceVessel)) continue; - if (!cam.Current.cameraEnabled || !cam.Current.groundStabilized || !cam.Current.surfaceDetected || - cam.Current.gimbalLimitReached) continue; - - float angle = Vector3.Angle(missilePosition, cam.Current.groundTargetPosition - position); - if (!(angle < maxOffBoresight) || !(angle < smallestAngle) || - !CanSeePosition(cam.Current.groundTargetPosition, vessel.transform.position, - (vessel.transform.position+missilePosition))) continue; - - smallestAngle = angle; - finalCam = cam.Current; - } - cam.Dispose(); - return finalCam; - } - - public static bool CanSeePosition(Vector3 groundTargetPosition, Vector3 vesselPosition, Vector3 missilePosition) - { - if ((groundTargetPosition - vesselPosition).sqrMagnitude < Mathf.Pow(20, 2)) - { - return false; - } - - float dist = BDArmorySettings.MAX_GUARD_VISUAL_RANGE; //replaced constant 10km with actual configured visual range - Ray ray = new Ray(missilePosition, groundTargetPosition - missilePosition); - ray.origin += 10 * ray.direction; - RaycastHit rayHit; - if (Physics.Raycast(ray, out rayHit, dist, 557057)) - { - if ((rayHit.point - groundTargetPosition).sqrMagnitude < 200) - { - return true; - } - else - { - return false; - } - } - - return true; - } - - /// - /// The the heat signature of a vessel (for Heat/IR targeting). - /// Returns the heat of the hottest part of the vessel - /// - /// Vessel - /// Heat signature value - public static float GetVesselHeatSignature(Vessel v) - { - float heatScore = 0f; - - List.Enumerator part = v.Parts.GetEnumerator(); - while (part.MoveNext()) - { - if (!part.Current) continue; - - float thisScore = (float)(part.Current.thermalInternalFluxPrevious + part.Current.skinTemperature); - heatScore = Mathf.Max(heatScore, thisScore); - } - - return heatScore; - } - - /// - /// Find a flare within acceptable thermal range that will "decoy" for the passed heatsignature - /// - public static TargetSignatureData GetFlareTarget(Ray ray, float scanRadius, float highpassThreshold, bool allAspect, float heatSignature) - { - TargetSignatureData flareTarget = TargetSignatureData.noTarget; - - List.Enumerator flare = BDArmorySetup.Flares.GetEnumerator(); - while (flare.MoveNext()) - { - if (!flare.Current) continue; - - float angle = Vector3.Angle(flare.Current.transform.position - ray.origin, ray.direction); - if (angle < scanRadius) - { - float score = flare.Current.thermal * Mathf.Clamp01(15 / angle); - - score *= Mathf.Pow(1400, 2) / Mathf.Clamp((flare.Current.transform.position - ray.origin).sqrMagnitude, 90000, 36000000); - score *= Mathf.Clamp(Vector3.Angle(flare.Current.transform.position - ray.origin, -VectorUtils.GetUpDirection(ray.origin)) / 90, 0.5f, 1.5f); - - // check acceptable range: - // flare cannot be too cool, but also not too bright - if ((score > heatSignature*0.9) && (score < heatSignature * 1.15)) - { - flareTarget = new TargetSignatureData(flare.Current, score); - } - } - } - - return flareTarget; - } - - public static TargetSignatureData GetHeatTarget(Ray ray, float scanRadius, float highpassThreshold, bool allAspect, MissileFire mf = null, bool favorGroundTargets = false) - { - float minMass = 0.05f; //otherwise the RAMs have trouble shooting down incoming missiles - TargetSignatureData finalData = TargetSignatureData.noTarget; - float finalScore = 0; - - foreach(Vessel vessel in LoadedVessels) - { - if(!vessel || !vessel.loaded) - { - continue; - } - - if (favorGroundTargets && !vessel.LandedOrSplashed) // for AGM heat guidance - continue; - - TargetInfo tInfo = vessel.gameObject.GetComponent(); - if(mf == null || - !tInfo || - !(mf && tInfo.isMissile && tInfo.team != BoolToTeam(mf.team) && (tInfo.MissileBaseModule.MissileState == MissileBase.MissileStates.Boost || tInfo.MissileBaseModule.MissileState == MissileBase.MissileStates.Cruise))) - { - if(vessel.GetTotalMass() < minMass) - { - continue; - } - } - - - float angle = Vector3.Angle(vessel.CoM-ray.origin, ray.direction); - if(angle < scanRadius) - { - if (RadarUtils.TerrainCheck(ray.origin, vessel.transform.position)) - continue; - - - if (!allAspect) - { - if (!Misc.Misc.CheckSightLineExactDistance(ray.origin, vessel.CoM + vessel.Velocity(), Vector3.Distance(vessel.CoM, ray.origin), 5, 5)) - continue; - } - - float score = GetVesselHeatSignature(vessel) * Mathf.Clamp01(15 / angle); - score *= Mathf.Pow(1400, 2) / Mathf.Clamp((vessel.CoM - ray.origin).sqrMagnitude, 90000, 36000000); - - if (vessel.LandedOrSplashed && !favorGroundTargets) - { - 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); - } - } - } - - // see if there are flares decoying us: - TargetSignatureData flareData = GetFlareTarget(ray, scanRadius, highpassThreshold, allAspect, finalScore); - - if(finalScore < highpassThreshold) - { - finalData = TargetSignatureData.noTarget; - } - - // return matching flare - if (!flareData.Equals(TargetSignatureData.noTarget)) - return flareData; - - //else return the target: - return finalData; - } - - void UpdateDebugLabels() - { - debugString.Length = 0; - - debugString.Append($"Team A's targets:"); - debugString.Append(Environment.NewLine); - foreach (TargetInfo targetInfo in TargetDatabase[BDArmorySetup.BDATeams.A]) - { - if(targetInfo) - { - if(!targetInfo.Vessel) - { - debugString.Append($"- A target with no vessel reference."); - debugString.Append(Environment.NewLine); - } - else - { - debugString.Append($"- {targetInfo.Vessel.vesselName} Engaged by {targetInfo.numFriendliesEngaging}"); - debugString.Append(Environment.NewLine); - } - } - else - { - debugString.Append($"- null target info."); - debugString.Append(Environment.NewLine); - } - } - - debugString.Append($"Team B's targets:"); - debugString.Append(Environment.NewLine); - foreach (TargetInfo targetInfo in TargetDatabase[BDArmorySetup.BDATeams.B]) - { - if(targetInfo) - { - if(!targetInfo.Vessel) - { - debugString.Append($"- A target with no vessel reference."); - debugString.Append(Environment.NewLine); - } - else - { - debugString.Append($"- {targetInfo.Vessel.vesselName} Engaged by {targetInfo.numFriendliesEngaging}"); - debugString.Append(Environment.NewLine); - } - } - else - { - debugString.Append($"- null target info."); - debugString.Append(Environment.NewLine); - } - } - - debugString.Append(Environment.NewLine); - debugString.Append($"Heat Signature: {GetVesselHeatSignature(FlightGlobals.ActiveVessel):#####}"); - debugString.Append(Environment.NewLine); - - debugString.Append($"Radar Signature: " + RadarUtils.GetVesselRadarSignature(FlightGlobals.ActiveVessel).radarModifiedSignature); - debugString.Append(Environment.NewLine); - - debugString.Append($"Chaff multiplier: " + RadarUtils.GetVesselChaffFactor(FlightGlobals.ActiveVessel)); - debugString.Append(Environment.NewLine); - - debugString.Append($"ECM Jammer Strength: " + FlightGlobals.ActiveVessel.gameObject.GetComponent()?.jammerStrength); - debugString.Append(Environment.NewLine); - - debugString.Append($"ECM Lockbreak Strength: " + FlightGlobals.ActiveVessel.gameObject.GetComponent()?.lockBreakStrength); - debugString.Append(Environment.NewLine); - } - - - void SaveGPSTargets(ConfigNode saveNode) - { - string saveTitle = HighLogic.CurrentGame.Title; - Debug.Log("[BDArmory]: Save title: " + saveTitle); - ConfigNode fileNode = ConfigNode.Load("GameData/BDArmory/gpsTargets.cfg"); - if(fileNode == null) - { - fileNode = new ConfigNode(); - fileNode.AddNode("BDARMORY"); - fileNode.Save("GameData/BDArmory/gpsTargets.cfg"); - - } - - if(fileNode!=null && fileNode.HasNode("BDARMORY")) - { - ConfigNode node = fileNode.GetNode("BDARMORY"); - - if(GPSTargets == null || !FlightGlobals.ready) - { - return; - } - - ConfigNode gpsNode = null; - if(node.HasNode("BDAGPSTargets")) - { - foreach(ConfigNode n in node.GetNodes("BDAGPSTargets")) - { - if(n.GetValue("SaveGame") == saveTitle) - { - gpsNode = n; - break; - } - } - - if(gpsNode == null) - { - gpsNode = node.AddNode("BDAGPSTargets"); - gpsNode.AddValue("SaveGame", saveTitle); - } - } - else - { - gpsNode = node.AddNode("BDAGPSTargets"); - gpsNode.AddValue("SaveGame", saveTitle); - } - - if(GPSTargets[BDArmorySetup.BDATeams.A].Count == 0 && GPSTargets[BDArmorySetup.BDATeams.B].Count == 0) - { - //gpsNode.SetValue("Targets", string.Empty, true); - return; - } - - string targetString = GPSListToString(); - gpsNode.SetValue("Targets", targetString, true); - fileNode.Save("GameData/BDArmory/gpsTargets.cfg"); - Debug.Log("[BDArmory]: ==== Saved BDA GPS Targets ===="); - } - } - - void LoadGPSTargets(ConfigNode saveNode) - { - ConfigNode fileNode = ConfigNode.Load("GameData/BDArmory/gpsTargets.cfg"); - string saveTitle = HighLogic.CurrentGame.Title; - - if(fileNode != null && fileNode.HasNode("BDARMORY")) - { - ConfigNode node = fileNode.GetNode("BDARMORY"); - - foreach(ConfigNode gpsNode in node.GetNodes("BDAGPSTargets")) - { - if(gpsNode.HasValue("SaveGame") && gpsNode.GetValue("SaveGame") == saveTitle) - { - if(gpsNode.HasValue("Targets")) - { - string targetString = gpsNode.GetValue("Targets"); - if(targetString == string.Empty) - { - Debug.Log("[BDArmory]: ==== BDA GPS Target string was empty! ===="); - return; - } - StringToGPSList(targetString); - Debug.Log("[BDArmory]: ==== Loaded BDA GPS Targets ===="); - } - else - { - Debug.Log("[BDArmory]: ==== No BDA GPS Targets value found! ===="); - } - } - } - } - } - - //format: SAVENAME&name,lat,long,alt;name,lat,long,alt:name,lat,long,alt (A;A;A:B;B) - private string GPSListToString() - { - string finalString = string.Empty; - string aString = string.Empty; - foreach(GPSTargetInfo gpsInfo in GPSTargets[BDArmorySetup.BDATeams.A]) - { - aString += gpsInfo.name; - aString += ","; - aString += gpsInfo.gpsCoordinates.x; - aString += ","; - aString += gpsInfo.gpsCoordinates.y; - aString += ","; - aString += gpsInfo.gpsCoordinates.z; - aString += ";"; - } - if(aString == string.Empty) - { - aString = "null"; - } - finalString += aString; - finalString += ":"; - - string bString = string.Empty; - foreach(GPSTargetInfo gpsInfo in GPSTargets[BDArmorySetup.BDATeams.B]) - { - bString += gpsInfo.name; - bString += ","; - bString += gpsInfo.gpsCoordinates.x; - bString += ","; - bString += gpsInfo.gpsCoordinates.y; - bString += ","; - bString += gpsInfo.gpsCoordinates.z; - bString += ";"; - } - if(bString == string.Empty) - { - bString = "null"; - } - finalString += bString; - - return finalString; - } - - private void StringToGPSList(string listString) - { - if(GPSTargets == null) - { - GPSTargets = new Dictionary>(); - } - GPSTargets.Clear(); - GPSTargets.Add(BDArmorySetup.BDATeams.A, new List()); - GPSTargets.Add(BDArmorySetup.BDATeams.B, new List()); - - if(listString == null || listString == string.Empty) - { - Debug.Log("[BDArmory]: === GPS List string was empty or null ==="); - return; - } - - string[] teams = listString.Split(new char[]{ ':' }); - - Debug.Log("[BDArmory]: ==== Loading GPS Targets. Number of teams: " + teams.Length); - - if(teams[0] != null && teams[0].Length > 0 && teams[0] != "null") - { - string[] teamACoords = teams[0].Split(new char[]{ ';' }); - for(int i = 0; i < teamACoords.Length; i++) - { - if(teamACoords[i] != null && teamACoords[i].Length > 0) - { - string[] data = teamACoords[i].Split(new char[]{ ',' }); - string name = data[0]; - double lat = double.Parse(data[1]); - double longi = double.Parse(data[2]); - double alt = double.Parse(data[3]); - GPSTargetInfo newInfo = new GPSTargetInfo(new Vector3d(lat, longi, alt), name); - GPSTargets[BDArmorySetup.BDATeams.A].Add(newInfo); - } - } - } - - if(teams[1] != null && teams[1].Length > 0 && teams[1] != "null") - { - string[] teamBCoords = teams[1].Split(new char[]{ ';' }); - for(int i = 0; i < teamBCoords.Length; i++) - { - if(teamBCoords[i] != null && teamBCoords[i].Length > 0) - { - string[] data = teamBCoords[i].Split(new char[]{ ',' }); - string name = data[0]; - double lat = double.Parse(data[1]); - double longi = double.Parse(data[2]); - double alt = double.Parse(data[3]); - GPSTargetInfo newInfo = new GPSTargetInfo(new Vector3d(lat, longi, alt), name); - GPSTargets[BDArmorySetup.BDATeams.B].Add(newInfo); - } - } - } - } - - //Legacy target managing stuff - - public static BDArmorySetup.BDATeams BoolToTeam(bool team) - { - return team ? BDArmorySetup.BDATeams.B : BDArmorySetup.BDATeams.A; - } - - public static BDArmorySetup.BDATeams OtherTeam(BDArmorySetup.BDATeams team) - { - return team == BDArmorySetup.BDATeams.A ? BDArmorySetup.BDATeams.B : BDArmorySetup.BDATeams.A; - } - - IEnumerator CleanDatabaseRoutine() - { - while(enabled) - { - yield return new WaitForSeconds(5); - - TargetDatabase[BDArmorySetup.BDATeams.A].RemoveAll(target => target == null); - TargetDatabase[BDArmorySetup.BDATeams.A].RemoveAll(target => target.team == BDArmorySetup.BDATeams.A); - TargetDatabase[BDArmorySetup.BDATeams.A].RemoveAll(target => !target.isThreat); - - TargetDatabase[BDArmorySetup.BDATeams.B].RemoveAll(target => target == null); - TargetDatabase[BDArmorySetup.BDATeams.B].RemoveAll(target => target.team == BDArmorySetup.BDATeams.B); - TargetDatabase[BDArmorySetup.BDATeams.B].RemoveAll(target => !target.isThreat); - } - } - - void RemoveTarget(TargetInfo target, BDArmorySetup.BDATeams team) - { - TargetDatabase[team].Remove(target); - } - - public static void ReportVessel(Vessel v, MissileFire reporter) - { - if (!v) return; - if (!reporter) return; - - TargetInfo info = v.gameObject.GetComponent(); - if (!info) - { - List.Enumerator mf = v.FindPartModulesImplementing().GetEnumerator(); - while (mf.MoveNext()) - { - if (mf.Current == null) continue; - if (mf.Current.team != reporter.team) - { - info = v.gameObject.AddComponent(); - break; - } - - } - mf.Dispose(); - - List.Enumerator ml = v.FindPartModulesImplementing().GetEnumerator(); - while (ml.MoveNext()) - { - if (ml.Current == null) continue; - if (ml.Current.HasFired) - { - if (ml.Current.Team != reporter.team) - { - info = v.gameObject.AddComponent(); - break; - } - } - - } - ml.Dispose(); - } - - // add target to database - if (info) - { - AddTarget(info); - info.detectedTime = Time.time; - } - } - - public static void AddTarget(TargetInfo target) - { - var team = target.team; - if (team == BDArmorySetup.BDATeams.None) return; - if (!BDATargetManager.TargetDatabase[BDATargetManager.OtherTeam(team)].Contains(target)) - { - BDATargetManager.TargetDatabase[BDATargetManager.OtherTeam(team)].Add(target); - } - } - - public static void ClearDatabase() - { - foreach(BDArmorySetup.BDATeams t in TargetDatabase.Keys) - { - foreach(TargetInfo target in TargetDatabase[t]) - { - target.detectedTime = 0; - } - } - - TargetDatabase[BDArmorySetup.BDATeams.A].Clear(); - TargetDatabase[BDArmorySetup.BDATeams.B].Clear(); - } - - public static TargetInfo GetAirToAirTarget(MissileFire mf) - { - BDArmorySetup.BDATeams team = mf.team ? BDArmorySetup.BDATeams.B : BDArmorySetup.BDATeams.A; - TargetInfo finalTarget = null; - - float finalTargetSuitability = 0; //this will determine how suitable the target is, based on where it is located relative to the targeting vessel and how far it is - - List.Enumerator target = TargetDatabase[team].GetEnumerator(); - while (target.MoveNext()) - { - if (target.Current == null) continue; - if (target.Current.numFriendliesEngaging >= 2) continue; - if(target.Current && target.Current.Vessel && target.Current.isFlying && !target.Current.isMissile && target.Current.isThreat) - { - Vector3 targetRelPos = target.Current.Vessel.vesselTransform.position - mf.vessel.vesselTransform.position; - float targetSuitability = Vector3.Dot(targetRelPos.normalized, mf.vessel.ReferenceTransform.up); //prefer targets ahead to those behind - targetSuitability += 500 / (targetRelPos.magnitude + 100); - - if (finalTarget == null || (target.Current.numFriendliesEngaging < finalTarget.numFriendliesEngaging) || targetSuitability > finalTargetSuitability + finalTarget.numFriendliesEngaging) - { - finalTarget = target.Current; - finalTargetSuitability = targetSuitability; - } - } - } - - return finalTarget; - } - - //this will search for an AA target that is immediately in front of the AI during an extend when it would otherwise be helpless - public static TargetInfo GetAirToAirTargetAbortExtend(MissileFire mf, float maxDistance, float cosAngleCheck) - { - BDArmorySetup.BDATeams team = mf.team ? BDArmorySetup.BDATeams.B : BDArmorySetup.BDATeams.A; - TargetInfo finalTarget = null; - - float finalTargetSuitability = 0; //this will determine how suitable the target is, based on where it is located relative to the targeting vessel and how far it is - - List.Enumerator target = TargetDatabase[team].GetEnumerator(); - while (target.MoveNext()) - { - if (target.Current == null || !target.Current.Vessel || target.Current.isLanded || target.Current.isMissile || !target.Current.isThreat) continue; - Vector3 targetRelPos = target.Current.Vessel.vesselTransform.position - mf.vessel.vesselTransform.position; - - float distance, dot; - distance = targetRelPos.magnitude; - dot = Vector3.Dot(targetRelPos.normalized, mf.vessel.ReferenceTransform.up); - - if (distance > maxDistance || cosAngleCheck > dot) - continue; - - float targetSuitability = dot; //prefer targets ahead to those behind - targetSuitability += 500 / (distance + 100); //same suitability check as above - - if (finalTarget != null && !(targetSuitability > finalTargetSuitability)) continue; - //just pick the most suitable one - finalTarget = target.Current; - finalTargetSuitability = targetSuitability; - } - target.Dispose(); - return finalTarget; - } - - //returns the nearest friendly target - public static TargetInfo GetClosestFriendly(MissileFire mf) - { - BDArmorySetup.BDATeams team = mf.team ? BDArmorySetup.BDATeams.A : BDArmorySetup.BDATeams.B; - TargetInfo finalTarget = null; - - List.Enumerator target = TargetDatabase[team].GetEnumerator(); - while (target.MoveNext()) - { - if (target.Current == null || !target.Current.Vessel || target.Current.weaponManager == mf) continue; - if (finalTarget == null || (target.Current.IsCloser(finalTarget, mf))) - { - finalTarget = target.Current; - } - } - target.Dispose(); - return finalTarget; - } - - //returns the target that owns this weapon manager - public static TargetInfo GetTargetFromWeaponManager(MissileFire mf) - { - BDArmorySetup.BDATeams team = mf.team ? BDArmorySetup.BDATeams.A : BDArmorySetup.BDATeams.B; - - List.Enumerator target = TargetDatabase[team].GetEnumerator(); - while (target.MoveNext()) - { - if (target.Current == null) continue; - if (target.Current.Vessel && target.Current.weaponManager == mf) - { - return target.Current; - } - } - target.Dispose(); - return null; - } - - public static TargetInfo GetClosestTarget(MissileFire mf) - { - BDArmorySetup.BDATeams team = mf.team ? BDArmorySetup.BDATeams.B : BDArmorySetup.BDATeams.A; - TargetInfo finalTarget = null; - - List.Enumerator target = TargetDatabase[team].GetEnumerator(); - while (target.MoveNext()) - { - if (target.Current == null) continue; - if (target.Current && target.Current.Vessel && mf.CanSeeTarget(target.Current) && !target.Current.isMissile) - { - if(finalTarget == null || (target.Current.IsCloser(finalTarget, mf))) - { - finalTarget = target.Current; - } - } - } - target.Dispose(); - return finalTarget; - } - - public static List GetAllTargetsExcluding(List excluding, MissileFire mf) - { - List finalTargets = new List(); - BDArmorySetup.BDATeams team = BoolToTeam(mf.team); - - List.Enumerator target = TargetDatabase[team].GetEnumerator(); - while (target.MoveNext()) - { - if (target.Current == null) continue; - if (target.Current && target.Current.Vessel && mf.CanSeeTarget(target.Current) && !excluding.Contains(target.Current)) - { - finalTargets.Add(target.Current); - } - } - target.Dispose(); - return finalTargets; - } - - public static TargetInfo GetLeastEngagedTarget(MissileFire mf) - { - BDArmorySetup.BDATeams team = mf.team ? BDArmorySetup.BDATeams.B : BDArmorySetup.BDATeams.A; - TargetInfo finalTarget = null; - - List.Enumerator target = TargetDatabase[team].GetEnumerator(); - while (target.MoveNext()) - { - if (target.Current == null) continue; - if (target.Current && target.Current.Vessel && mf.CanSeeTarget(target.Current) && !target.Current.isMissile && target.Current.isThreat) - { - if(finalTarget == null || target.Current.numFriendliesEngaging < finalTarget.numFriendliesEngaging) - { - finalTarget = target.Current; - } - } - } - target.Dispose(); - return finalTarget; - } - - public static TargetInfo GetMissileTarget(MissileFire mf, bool targetingMeOnly = false) - { - BDArmorySetup.BDATeams team = mf.team ? BDArmorySetup.BDATeams.B : BDArmorySetup.BDATeams.A; - TargetInfo finalTarget = null; - - List.Enumerator target = TargetDatabase[team].GetEnumerator(); - while (target.MoveNext()) - { - if (target.Current == null) continue; - if (target.Current && target.Current.Vessel && target.Current.isMissile && target.Current.isThreat && mf.CanSeeTarget(target.Current) ) - { - if(target.Current.MissileBaseModule) - { - if(targetingMeOnly) - { - if(Vector3.SqrMagnitude(target.Current.MissileBaseModule.TargetPosition - mf.vessel.CoM) > 60 * 60) - { - continue; - } - } - } - else - { - if (BDArmorySettings.DRAW_DEBUG_LABELS) - Debug.LogWarning("checking target missile - doesn't have missile module"); - } - - - if(((finalTarget == null && target.Current.numFriendliesEngaging < 2) || (finalTarget != null && target.Current.numFriendliesEngaging < finalTarget.numFriendliesEngaging))) - { - finalTarget = target.Current; - } - } - } - target.Dispose(); - return finalTarget; - } - - public static TargetInfo GetUnengagedMissileTarget(MissileFire mf) - { - BDArmorySetup.BDATeams team = mf.team ? BDArmorySetup.BDATeams.B : BDArmorySetup.BDATeams.A; - - List.Enumerator target = TargetDatabase[team].GetEnumerator(); - while (target.MoveNext()) - { - if (target.Current == null) continue; - if (target.Current && target.Current.Vessel && mf.CanSeeTarget(target.Current) && target.Current.isMissile && target.Current.isThreat) - { - if(target.Current.numFriendliesEngaging == 0) - { - return target.Current; - } - } - } - target.Dispose(); - return null; - } - - public static TargetInfo GetClosestMissileTarget(MissileFire mf) - { - BDArmorySetup.BDATeams team = BoolToTeam(mf.team); - TargetInfo finalTarget = null; - - List.Enumerator target = TargetDatabase[team].GetEnumerator(); - while (target.MoveNext()) - { - if (target.Current == null) continue; - if (target.Current && target.Current.Vessel && mf.CanSeeTarget(target.Current) && target.Current.isMissile) - { - bool isHostile = false; - if(target.Current.isThreat) - { - isHostile = true; - } - - if(isHostile && (finalTarget == null || target.Current.IsCloser(finalTarget, mf))) - { - finalTarget = target.Current; - } - } - } - target.Dispose(); - return finalTarget; - } - - //checks to see if a friendly is too close to the gun trajectory to fire them - public static bool CheckSafeToFireGuns(MissileFire weaponManager, Vector3 aimDirection, float safeDistance, float cosUnsafeAngle) - { - if (weaponManager == null) return false; - if (weaponManager.vessel == null) return false; - - BDArmorySetup.BDATeams team = weaponManager.team ? BDArmorySetup.BDATeams.A : BDArmorySetup.BDATeams.B; - List.Enumerator friendlyTarget = TargetDatabase[team].GetEnumerator(); - while (friendlyTarget.MoveNext()) - { - if (friendlyTarget.Current == null || !friendlyTarget.Current.Vessel || friendlyTarget.Current.weaponManager == weaponManager) continue; - float friendlyPosDot = Vector3.Dot(friendlyTarget.Current.position - weaponManager.vessel.CoM, aimDirection); - if (!(friendlyPosDot > 0)) continue; - float friendlyDistance = (friendlyTarget.Current.position - weaponManager.vessel.CoM).magnitude; - float friendlyPosDotNorm = friendlyPosDot / friendlyDistance; //scale down the dot to be a 0-1 so we can check it againts cosUnsafeAngle - - if (friendlyDistance < safeDistance && cosUnsafeAngle < friendlyPosDotNorm) //if it's too close and it's within the Unsafe Angle, don't fire - return false; - } - friendlyTarget.Dispose(); - return true; - } - - void OnGUI() - { - if(BDArmorySettings.DRAW_DEBUG_LABELS) - { - GUI.Label(new Rect(600,100,600,600), debugString.ToString()); - } - } - - } -} - From 984596eaeaf693529d0fca084dc4a4ffb9fdc6d8 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Mon, 9 Jul 2018 19:59:34 -0500 Subject: [PATCH 18/72] merge conflict resolve --- BDArmory/BDArmory.csproj | 1 - BDArmory/Guidances/MissileGuidance.cs | 1 - BDArmory/Modules/MissileLauncher.cs | 4 +- BDArmory/Parts/RocketLauncher.cs | 1077 ------------------------- 4 files changed, 2 insertions(+), 1081 deletions(-) delete mode 100644 BDArmory/Parts/RocketLauncher.cs diff --git a/BDArmory/BDArmory.csproj b/BDArmory/BDArmory.csproj index edbeca7d7..cb48c8e85 100644 --- a/BDArmory/BDArmory.csproj +++ b/BDArmory/BDArmory.csproj @@ -104,7 +104,6 @@ - diff --git a/BDArmory/Guidances/MissileGuidance.cs b/BDArmory/Guidances/MissileGuidance.cs index 57a27c59b..69dee6507 100644 --- a/BDArmory/Guidances/MissileGuidance.cs +++ b/BDArmory/Guidances/MissileGuidance.cs @@ -4,7 +4,6 @@ using BDArmory.Misc; using BDArmory.Modules; using UnityEngine; -using BDArmory.Parts; namespace BDArmory.Guidances { diff --git a/BDArmory/Modules/MissileLauncher.cs b/BDArmory/Modules/MissileLauncher.cs index 8480f0e33..5d66a9085 100644 --- a/BDArmory/Modules/MissileLauncher.cs +++ b/BDArmory/Modules/MissileLauncher.cs @@ -9,13 +9,13 @@ using BDArmory.FX; using BDArmory.Guidances; using BDArmory.Misc; -using BDArmory.Modules; using BDArmory.Radar; using UniLinq; using UnityEngine; using BDArmory.Targeting; +using BDArmory.Parts; -namespace BDArmory.Parts +namespace BDArmory.Modules { public class MissileLauncher : MissileBase { diff --git a/BDArmory/Parts/RocketLauncher.cs b/BDArmory/Parts/RocketLauncher.cs deleted file mode 100644 index 31a1bcc2a..000000000 --- a/BDArmory/Parts/RocketLauncher.cs +++ /dev/null @@ -1,1077 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Text; -using BDArmory.Core; -using BDArmory.Core.Enum; -using BDArmory.Core.Extension; -using BDArmory.Core.Utils; -using BDArmory.FX; -using BDArmory.Misc; -using BDArmory.Modules; -using BDArmory.UI; -using UniLinq; -using UnityEngine; - -namespace BDArmory -{ - public class RocketLauncher : EngageableWeapon, IBDWeapon - { - public bool hasRocket = true; - [KSPField] public string shortName = string.Empty; - [KSPField(isPersistant = false)] public string rocketType; - [KSPField(isPersistant = false)] public string rocketModelPath; - [KSPField(isPersistant = false)] public float rocketMass; - [KSPField(isPersistant = false)] public float thrust; - [KSPField(isPersistant = false)] public float thrustTime; - [KSPField(isPersistant = false)] public float blastRadius; - [KSPField(isPersistant = false)] public float blastForce; - [KSPField] public float blastHeat = -1; - [KSPField(isPersistant = false)] public bool descendingOrder = true; - [KSPField(isPersistant = false)] public string explModelPath = "BDArmory/Models/explosion/explosion"; - [KSPField(isPersistant = false)] public string explSoundPath = "BDArmory/Sounds/explode1"; - [KSPField] public float thrustDeviation = 0.10f; - [KSPField] public float maxTargetingRange = 8000; - float currentTgtRange = 8000; - float predictedFlightTime = 1; - public bool drawAimer; - Vector3 rocketPrediction = Vector3.zero; - Texture2D aimerTexture; - Transform[] rockets; - public AudioSource sfAudioSource; - - //animation - [KSPField] public string deployAnimationName; - [KSPField] public float deployAnimationSpeed = 1; - AnimationState deployAnimState; - bool hasDeployAnimation; - public bool deployed; - Coroutine deployAnimRoutine; - - public bool readyToFire = true; - - public Vessel legacyGuardTarget = null; - public float lastAutoFiredTime; - public float autoRippleRate = 0; - public float autoFireStartTime = 0; - public float autoFireDuration = 0; - - //turret - [KSPField] public int turretID = 0; - public ModuleTurret turret; - Vector3 trajectoryOffset = Vector3.zero; - public MissileFire weaponManager; - bool targetInTurretView = true; - - public float yawRange - { - get { return turret ? turret.yawRange : 0; } - } - - public float maxPitch - { - get { return turret ? turret.maxPitch : 0; } - } - - public float minPitch - { - get { return turret ? turret.minPitch : 0; } - } - - Vector3 targetPosition; - public Vector3? FiringSolutionVector => targetPosition.IsZero() ? (Vector3?)null : (targetPosition - rockets[0].parent.transform.position).normalized; - - double lastRocketsLeft; - - bool hasReturned = true; - Coroutine returnRoutine; - bool mouseAiming; - - //weapon interface - public Part GetPart() - { - return part; - } - - public string GetShortName() - { - return shortName; - } - - public WeaponClasses GetWeaponClass() - { - return WeaponClasses.Rocket; - } - - public string GetSubLabel() - { - return string.Empty; - } - - public string GetMissileType() - { - return string.Empty; - } - - [KSPAction("Fire")] - public void AGFire(KSPActionParam param) - { - FireRocket(); - } - - [KSPEvent(guiActive = true, guiName = "Fire", active = true)] - public void GuiFire() - { - FireRocket(); - } - - [KSPEvent(guiActive = true, guiName = "Jettison", active = true, guiActiveEditor = false)] - public void Jettison() - { - if (turret) - { - return; - } - - part.decouple(0); - if (BDArmorySetup.Instance.ActiveWeaponManager != null) - BDArmorySetup.Instance.ActiveWeaponManager.UpdateList(); - } - - [KSPEvent(guiActive = false, guiName = "Toggle Turret", guiActiveEditor = false)] - public void ToggleTurret() - { - if (deployed) - { - DisableTurret(); - } - else - { - EnableTurret(); - } - } - - public void EnableTurret() - { - deployed = true; - drawAimer = true; - hasReturned = false; - - if (returnRoutine != null) - { - StopCoroutine(returnRoutine); - returnRoutine = null; - } - - if (hasDeployAnimation) - { - if (deployAnimRoutine != null) - { - StopCoroutine(deployAnimRoutine); - } - deployAnimRoutine = StartCoroutine(DeployAnimRoutine(true)); - } - else - { - readyToFire = true; - } - } - - public void DisableTurret() - { - deployed = false; - readyToFire = false; - drawAimer = false; - hasReturned = false; - targetInTurretView = false; - - if (returnRoutine != null) - { - StopCoroutine(returnRoutine); - } - returnRoutine = StartCoroutine(ReturnRoutine()); - - if (hasDeployAnimation) - { - if (deployAnimRoutine != null) - { - StopCoroutine(deployAnimRoutine); - } - - deployAnimRoutine = StartCoroutine(DeployAnimRoutine(false)); - } - } - - IEnumerator ReturnRoutine() - { - if (deployed) - { - hasReturned = false; - yield break; - } - - yield return new WaitForSeconds(0.25f); - - while (!turret.ReturnTurret()) - { - yield return new WaitForFixedUpdate(); - } - - hasReturned = true; - } - - void SetupAudio() - { - sfAudioSource = gameObject.AddComponent(); - sfAudioSource.minDistance = 1; - sfAudioSource.maxDistance = 2000; - sfAudioSource.dopplerLevel = 0; - sfAudioSource.priority = 230; - sfAudioSource.spatialBlend = 1; - - UpdateVolume(); - BDArmorySetup.OnVolumeChange += UpdateVolume; - } - - void UpdateVolume() - { - if (sfAudioSource) - { - sfAudioSource.volume = BDArmorySettings.BDARMORY_WEAPONS_VOLUME; - } - } - - public override void OnStart(StartState state) - { - // extension for feature_engagementenvelope - InitializeEngagementRange(0, maxTargetingRange); - - if (HighLogic.LoadedSceneIsFlight) - { - part.force_activate(); - - aimerTexture = BDArmorySetup.Instance.greenPointCircleTexture; - // GameDatabase.Instance.GetTexture("BDArmory/Textures/grayCircle", false); - - - MakeRocketArray(); - UpdateRocketScales(); - - if (shortName == string.Empty) - { - shortName = part.partInfo.title; - } - - UpdateAudio(); - BDArmorySetup.OnVolumeChange += UpdateAudio; - } - - if (HighLogic.LoadedSceneIsFlight || HighLogic.LoadedSceneIsEditor) - { - List.Enumerator turr = part.FindModulesImplementing().GetEnumerator(); - while (turr.MoveNext()) - { - if (turr.Current == null) continue; - if (turr.Current.turretID != turretID) continue; - turret = turr.Current; - targetInTurretView = false; - break; - } - turr.Dispose(); - - if (turret) - { - Events["GuiFire"].guiActive = false; - Events["Jettison"].guiActive = false; - Actions["AGFire"].active = false; - - if (HighLogic.LoadedSceneIsFlight) - { - Events["ToggleTurret"].guiActive = true; - } - } - - if (!string.IsNullOrEmpty(deployAnimationName)) - { - deployAnimState = Misc.Misc.SetUpSingleAnimation(deployAnimationName, part); - hasDeployAnimation = true; - - readyToFire = false; - } - } - SetupAudio(); - - blastForce = BlastPhysicsUtils.CalculateExplosiveMass(blastRadius); - } - - IEnumerator DeployAnimRoutine(bool forward) - { - readyToFire = false; - BDArmorySetup.Instance.UpdateCursorState(); - - if (forward) - { - while (deployAnimState.normalizedTime < 1) - { - deployAnimState.speed = deployAnimationSpeed; - yield return null; - } - - deployAnimState.normalizedTime = 1; - } - else - { - while (!hasReturned) - { - deployAnimState.speed = 0; - yield return null; - } - - while (deployAnimState.normalizedTime > 0) - { - deployAnimState.speed = -deployAnimationSpeed; - yield return null; - } - - deployAnimState.normalizedTime = 0; - } - - deployAnimState.speed = 0; - - readyToFire = deployed; - BDArmorySetup.Instance.UpdateCursorState(); - } - - void UpdateAudio() - { - if (sfAudioSource) - { - sfAudioSource.volume = BDArmorySettings.BDARMORY_WEAPONS_VOLUME; - } - } - - void OnDestroy() - { - BDArmorySetup.OnVolumeChange -= UpdateAudio; - } - - public override void OnFixedUpdate() - { - if (GetRocketResource().amount != lastRocketsLeft) - { - UpdateRocketScales(); - lastRocketsLeft = GetRocketResource().amount; - } - - if (!vessel.IsControllable) - { - return; - } - - SimulateTrajectory(); - - currentTgtRange = maxTargetingRange; - - if (deployed && readyToFire && (turret || weaponManager?.AI?.pilotEnabled == true)) - { - Aim(); - } - else - { - targetPosition = Vector3.zero; - } - } - - public override void OnUpdate() - { - if (HighLogic.LoadedSceneIsFlight) - { - if (readyToFire && deployed) - { - if (returnRoutine != null) - { - StopCoroutine(returnRoutine); - returnRoutine = null; - } - - if (weaponManager && weaponManager.guardMode && weaponManager.selectedWeaponString == GetShortName()) - { - if (Time.time - autoFireStartTime < autoFireDuration) - { - float fireInterval = 0.5f; - if (autoRippleRate > 0) fireInterval = 60f/autoRippleRate; - if (Time.time - lastAutoFiredTime > fireInterval) - { - FireRocket(); - lastAutoFiredTime = Time.time; - } - } - } - else if ((!weaponManager || - (weaponManager.selectedWeaponString == GetShortName() && !weaponManager.guardMode))) - { - if (BDInputUtils.GetKeyDown(BDInputSettingsFields.WEAP_FIRE_KEY) && - (vessel.isActiveVessel || BDArmorySettings.REMOTE_SHOOTING)) - { - FireRocket(); - } - } - } - } - } - - void Aim() - { - mouseAiming = false; - if (weaponManager && (weaponManager.slavingTurrets || weaponManager.guardMode || weaponManager.AI?.pilotEnabled == true)) - { - SlavedAim(); - } - else - { - if (vessel.isActiveVessel || BDArmorySettings.REMOTE_SHOOTING) - { - MouseAim(); - } - } - } - - void SlavedAim() - { - Vector3 targetVel; - Vector3 targetAccel; - if (weaponManager.slavingTurrets) - { - targetPosition = weaponManager.slavedPosition; - targetVel = weaponManager.slavedVelocity; - targetAccel = weaponManager.slavedAcceleration; - - //targetPosition -= vessel.Velocity * predictedFlightTime; - } - else if (legacyGuardTarget) - { - targetPosition = legacyGuardTarget.CoM; - targetVel = legacyGuardTarget.Velocity(); - targetAccel = legacyGuardTarget.acceleration; - } - else - { - targetInTurretView = false; - return; - } - - currentTgtRange = Vector3.Distance(targetPosition, rockets[0].parent.transform.position); - - - targetPosition += trajectoryOffset; - targetPosition += targetVel*predictedFlightTime; - targetPosition += 0.5f*targetAccel*predictedFlightTime*predictedFlightTime; - - turret.AimToTarget(targetPosition); - targetInTurretView = turret.TargetInRange(targetPosition, 2, maxTargetingRange); - } - - void MouseAim() - { - mouseAiming = true; - Vector3 targetPosition; - // float maxTargetingRange = 8000; - - float targetDistance; - - //MouseControl - Vector3 mouseAim = new Vector3(Input.mousePosition.x/Screen.width, Input.mousePosition.y/Screen.height, 0); - Ray ray = FlightCamera.fetch.mainCamera.ViewportPointToRay(mouseAim); - RaycastHit hit; - if (Physics.Raycast(ray, out hit, maxTargetingRange, 557057)) - { - targetPosition = hit.point; - - //aim through self vessel if occluding mouseray - Part p = hit.collider.gameObject.GetComponentInParent(); - if (p && p.vessel && p.vessel == vessel) - { - targetPosition = ray.direction*maxTargetingRange + FlightCamera.fetch.mainCamera.transform.position; - } - - targetDistance = Vector3.Distance(hit.point, rockets[0].parent.position); - } - else - { - targetPosition = (ray.direction*(maxTargetingRange + (FlightCamera.fetch.Distance*0.75f))) + - FlightCamera.fetch.mainCamera.transform.position; - targetDistance = maxTargetingRange; - } - - currentTgtRange = targetDistance; - - targetPosition += trajectoryOffset; - - - turret.AimToTarget(targetPosition); - targetInTurretView = turret.TargetInRange(targetPosition, 2, maxTargetingRange); - } - - public void FireRocket() - { - if (!readyToFire) return; - if (!targetInTurretView) return; - - PartResource rocketResource = GetRocketResource(); - - if (rocketResource == null) - { - Debug.Log(part.name + " doesn't carry the rocket resource it was meant to"); - return; - } - - int rocketsLeft = (int)Math.Floor(rocketResource.amount); - - if (BDArmorySettings.INFINITE_AMMO && rocketsLeft < 1) - rocketsLeft = 1; - - if (rocketsLeft >= 1) - { - Transform currentRocketTfm = rockets[rocketsLeft - 1]; - - GameObject rocketObj = GameDatabase.Instance.GetModel(rocketModelPath); - rocketObj = - (GameObject) Instantiate(rocketObj, currentRocketTfm.position, currentRocketTfm.parent.rotation); - rocketObj.transform.rotation = currentRocketTfm.parent.rotation; - rocketObj.transform.localScale = part.rescaleFactor*Vector3.one; - currentRocketTfm.localScale = Vector3.zero; - - Rocket rocket = rocketObj.AddComponent(); - rocket.explModelPath = explModelPath; - rocket.explSoundPath = explSoundPath; - rocket.spawnTransform = currentRocketTfm; - rocket.mass = rocketMass; - rocket.blastForce = blastForce; - rocket.blastHeat = blastHeat; - rocket.blastRadius = blastRadius; - rocket.thrust = thrust; - rocket.thrustTime = thrustTime; - rocket.randomThrustDeviation = thrustDeviation; - - if (BDArmorySettings.ALLOW_LEGACY_TARGETING && vessel.targetObject != null) - { - rocket.targetVessel = vessel.targetObject.GetVessel(); - } - - rocket.sourceVessel = vessel; - rocketObj.SetActive(true); - rocketObj.transform.SetParent(currentRocketTfm.parent); - rocket.parentRB = part.rb; - - sfAudioSource.PlayOneShot(GameDatabase.Instance.GetAudioClip("BDArmory/Sounds/launch")); - - if (!BDArmorySettings.INFINITE_AMMO) - rocketResource.amount--; - - lastRocketsLeft = rocketResource.amount; - } - } - - void SimulateTrajectory() - { - if ((BDArmorySettings.AIM_ASSIST && BDArmorySettings.DRAW_AIMERS && drawAimer && vessel.isActiveVessel) || - (weaponManager && weaponManager.guardMode && weaponManager.selectedWeaponString == GetShortName())) - { - float simTime = 0; - Transform fireTransform = rockets[0].parent; - Vector3 pointingDirection = fireTransform.forward; - Vector3 simVelocity = part.rb.velocity; - Vector3 simCurrPos = fireTransform.position + (part.rb.velocity*Time.fixedDeltaTime); - Vector3 simPrevPos = fireTransform.position + (part.rb.velocity*Time.fixedDeltaTime); - Vector3 simStartPos = fireTransform.position + (part.rb.velocity*Time.fixedDeltaTime); - bool simulating = true; - float simDeltaTime = 0.02f; - List pointPositions = new List(); - pointPositions.Add(simCurrPos); - - bool slaved = turret && weaponManager && (weaponManager.slavingTurrets || weaponManager.guardMode); - float atmosMultiplier = - Mathf.Clamp01(2.5f* - (float) - FlightGlobals.getAtmDensity(vessel.staticPressurekPa, vessel.externalTemperature, - vessel.mainBody)); - while (simulating) - { - RaycastHit hit; - - if (simTime > thrustTime) - { - simDeltaTime = 0.1f; - } - - if (simTime > 0.04f) - { - simDeltaTime = 0.02f; - if (simTime < thrustTime) - { - simVelocity += thrust/rocketMass*simDeltaTime*pointingDirection; - } - - //rotation (aero stabilize) - pointingDirection = Vector3.RotateTowards(pointingDirection, - simVelocity + Krakensbane.GetFrameVelocity(), - atmosMultiplier*(0.5f*(simTime))*50*simDeltaTime*Mathf.Deg2Rad, 0); - } - - //gravity - simVelocity += FlightGlobals.getGeeForceAtPosition(simCurrPos)*simDeltaTime; - - simCurrPos += simVelocity*simDeltaTime; - pointPositions.Add(simCurrPos); - if (!mouseAiming && !slaved) - { - if (simTime > 0.1f && Physics.Raycast(simPrevPos, simCurrPos - simPrevPos, out hit, - Vector3.Distance(simPrevPos, simCurrPos), 9076737)) - { - rocketPrediction = hit.point; - simulating = false; - break; - } - else if (FlightGlobals.getAltitudeAtPos(simCurrPos) < 0) - { - rocketPrediction = simCurrPos; - simulating = false; - break; - } - } - - - simPrevPos = simCurrPos; - - if ((simStartPos - simCurrPos).sqrMagnitude > currentTgtRange*currentTgtRange) - { - rocketPrediction = simStartPos + (simCurrPos - simStartPos).normalized*currentTgtRange; - //rocketPrediction = simCurrPos; - simulating = false; - } - simTime += simDeltaTime; - } - - Vector3 pointingPos = fireTransform.position + (fireTransform.forward*currentTgtRange); - trajectoryOffset = pointingPos - rocketPrediction; - predictedFlightTime = simTime; - - if (BDArmorySettings.DRAW_DEBUG_LINES && BDArmorySettings.DRAW_AIMERS) - { - Vector3[] pointsArray = pointPositions.ToArray(); - if (gameObject.GetComponent() == null) - { - LineRenderer lr = gameObject.AddComponent(); - lr.startWidth = .1f; - lr.endWidth = .1f; - lr.positionCount = pointsArray.Length; - for (int i = 0; i < pointsArray.Length; i++) - { - lr.SetPosition(i, pointsArray[i]); - } - } - else - { - LineRenderer lr = gameObject.GetComponent(); - lr.enabled = true; - lr.positionCount = pointsArray.Length; - for (int i = 0; i < pointsArray.Length; i++) - { - lr.SetPosition(i, pointsArray[i]); - } - } - } - else - { - if (gameObject.GetComponent() != null) - { - gameObject.GetComponent().enabled = false; - } - } - } - - //for straight aimer - else if (BDArmorySettings.DRAW_AIMERS && drawAimer && vessel.isActiveVessel) - { - RaycastHit hit; - float distance = 2500; - if (Physics.Raycast(transform.position, transform.forward, out hit, distance, 9076737)) - { - rocketPrediction = hit.point; - } - else - { - rocketPrediction = transform.position + (transform.forward*distance); - } - } - } - - void OnGUI() - { - if (drawAimer && vessel.isActiveVessel && BDArmorySettings.DRAW_AIMERS && !MapView.MapIsEnabled) - { - float size = 30; - - Vector3 aimPosition = FlightCamera.fetch.mainCamera.WorldToViewportPoint(rocketPrediction); - - Rect drawRect = new Rect(aimPosition.x*Screen.width - (0.5f*size), - (1 - aimPosition.y)*Screen.height - (0.5f*size), size, size); - float cameraAngle = Vector3.Angle(FlightCamera.fetch.GetCameraTransform().forward, - rocketPrediction - FlightCamera.fetch.mainCamera.transform.position); - if (cameraAngle < 90) GUI.DrawTexture(drawRect, aimerTexture); - } - } - - void MakeRocketArray() - { - Transform rocketsTransform = part.FindModelTransform("rockets"); - int numOfRockets = rocketsTransform.childCount; - rockets = new Transform[numOfRockets]; - - for (int i = 0; i < numOfRockets; i++) - { - string rocketName = rocketsTransform.GetChild(i).name; - int rocketIndex = int.Parse(rocketName.Substring(7)) - 1; - rockets[rocketIndex] = rocketsTransform.GetChild(i); - } - - if (!descendingOrder) Array.Reverse(rockets); - } - - public PartResource GetRocketResource() - { - IEnumerator res = part.Resources.GetEnumerator(); - while (res.MoveNext()) - { - if (res.Current == null) continue; - if (res.Current.resourceName == rocketType) return res.Current; - } - res.Dispose(); - return null; - } - - void UpdateRocketScales() - { - PartResource rocketResource = GetRocketResource(); - double rocketsLeft = Math.Floor(rocketResource.amount); - double rocketsMax = rocketResource.maxAmount; - for (int i = 0; i < rocketsMax; i++) - { - if (i < rocketsLeft) rockets[i].localScale = Vector3.one; - else rockets[i].localScale = Vector3.zero; - } - } - - // RMB info in editor - public override string GetInfo() - { - StringBuilder output = new StringBuilder(); - output.Append(Environment.NewLine); - output.AppendLine("Weapon Type: Rocket Launcher"); - output.AppendLine($"Rocket Type: {rocketType}"); - output.AppendLine($"Max Range: {maxTargetingRange} m"); - - output.AppendLine($"Blast:"); - output.AppendLine($"- radius: {blastRadius}"); - output.AppendLine($"- power: {blastForce}"); - output.AppendLine($"- heat: {blastHeat}"); - - return output.ToString(); - } - } - - - public class Rocket : MonoBehaviour - { - public Transform spawnTransform; - public Vessel targetVessel; - public Vessel sourceVessel; - public Vector3 startVelocity; - public float mass; - public float thrust; - public float thrustTime; - public float blastRadius; - public float blastForce; - public float blastHeat; - public string explModelPath; - public string explSoundPath; - public float randomThrustDeviation = 0.05f; - public Rigidbody parentRB; - float startTime; - public AudioSource audioSource; - Vector3 prevPosition; - Vector3 currPosition; - Vector3 relativePos; - float stayTime = 0.04f; - float lifeTime = 10; - //bool isThrusting = true; - Rigidbody rb; - KSPParticleEmitter[] pEmitters; - float randThrustSeed; - - void Start() - { - BDArmorySetup.numberOfParticleEmitters++; - - rb = gameObject.AddComponent(); - pEmitters = gameObject.GetComponentsInChildren(); - - IEnumerator pe = pEmitters.AsEnumerable().GetEnumerator(); - while (pe.MoveNext()) - { - if (pe.Current == null) continue; - if (FlightGlobals.getStaticPressure(transform.position) == 0 && pe.Current.useWorldSpace) - { - pe.Current.emit = false; - } - else if (pe.Current.useWorldSpace) - { - BDAGaplessParticleEmitter gpe = pe.Current.gameObject.AddComponent(); - gpe.rb = rb; - gpe.emit = true; - } - else - { - EffectBehaviour.AddParticleEmitter(pe.Current); - } - } - pe.Dispose(); - - prevPosition = transform.position; - currPosition = transform.position; - startTime = Time.time; - - rb.mass = mass; - rb.isKinematic = true; - //rigidbody.velocity = startVelocity; - if (!FlightGlobals.RefFrameIsRotating) rb.useGravity = false; - - rb.useGravity = false; - - randThrustSeed = UnityEngine.Random.Range(0f, 100f); - - SetupAudio(); - } - - void FixedUpdate() - { - //floatingOrigin fix - if (sourceVessel != null && - (transform.position - sourceVessel.transform.position - relativePos).sqrMagnitude > 800*800) - { - transform.position = sourceVessel.transform.position + relativePos + (rb.velocity*Time.fixedDeltaTime); - } - if (sourceVessel != null) relativePos = transform.position - sourceVessel.transform.position; - // - - - if (Time.time - startTime < stayTime && transform.parent != null) - { - transform.rotation = transform.parent.rotation; - transform.position = spawnTransform.position; - //+(transform.parent.rigidbody.velocity*Time.fixedDeltaTime); - } - else - { - if (transform.parent != null && parentRB) - { - startVelocity = parentRB.velocity; - transform.parent = null; - rb.isKinematic = false; - rb.velocity = startVelocity; - } - } - - if (rb && !rb.isKinematic) - { - //physics - if (FlightGlobals.RefFrameIsRotating) - { - rb.velocity += FlightGlobals.getGeeForceAtPosition(transform.position)*Time.fixedDeltaTime; - } - - //guidance and attitude stabilisation scales to atmospheric density. - float atmosMultiplier = - Mathf.Clamp01(2.5f* - (float) - FlightGlobals.getAtmDensity(FlightGlobals.getStaticPressure(transform.position), - FlightGlobals.getExternalTemperature(), FlightGlobals.currentMainBody)); - - //model transform. always points prograde - transform.rotation = Quaternion.RotateTowards(transform.rotation, - Quaternion.LookRotation(rb.velocity + Krakensbane.GetFrameVelocity(), transform.up), - atmosMultiplier*(0.5f*(Time.time - startTime))*50*Time.fixedDeltaTime); - - - if (Time.time - startTime < thrustTime && Time.time - startTime > stayTime) - { - float random = randomThrustDeviation*(1 - (Mathf.PerlinNoise(4*Time.time, randThrustSeed)*2)); - float random2 = randomThrustDeviation*(1 - (Mathf.PerlinNoise(randThrustSeed, 4*Time.time)*2)); - rb.AddRelativeForce(new Vector3(random, random2, thrust)); - } - } - - - if (Time.time - startTime > thrustTime) - { - //isThrusting = false; - IEnumerator pEmitter = pEmitters.AsEnumerable().GetEnumerator(); - while (pEmitter.MoveNext()) - { - if (pEmitter.Current == null) continue; - if (pEmitter.Current.useWorldSpace) - { - pEmitter.Current.minSize = Mathf.MoveTowards(pEmitter.Current.minSize, 0.1f, 0.05f); - pEmitter.Current.maxSize = Mathf.MoveTowards(pEmitter.Current.maxSize, 0.2f, 0.05f); - } - else - { - pEmitter.Current.minSize = Mathf.MoveTowards(pEmitter.Current.minSize, 0, 0.1f); - pEmitter.Current.maxSize = Mathf.MoveTowards(pEmitter.Current.maxSize, 0, 0.1f); - if (pEmitter.Current.maxSize == 0) - { - pEmitter.Current.emit = false; - } - } - } - pEmitter.Dispose(); - } - - if (Time.time - startTime > 0.1f + stayTime) - { - currPosition = transform.position; - float dist = (currPosition - prevPosition).magnitude; - Ray ray = new Ray(prevPosition, currPosition - prevPosition); - RaycastHit hit; - KerbalEVA hitEVA = null; - //if (Physics.Raycast(ray, out hit, dist, 2228224)) - //{ - // try - // { - // hitEVA = hit.collider.gameObject.GetComponentUpwards(); - // if (hitEVA != null) - // Debug.Log("[BDArmory]:Hit on kerbal confirmed!"); - // } - // catch (NullReferenceException) - // { - // Debug.Log("[BDArmory]:Whoops ran amok of the exception handler"); - // } - - // if (hitEVA && hitEVA.part.vessel != sourceVessel) - // { - // Detonate(hit.point); - // } - //} - - if (!hitEVA) - { - if (Physics.Raycast(ray, out hit, dist, 9076737)) - { - Part hitPart = null; - try - { - KerbalEVA eva = hit.collider.gameObject.GetComponentUpwards(); - hitPart = eva ? eva.part : hit.collider.gameObject.GetComponentInParent(); - } - catch (NullReferenceException) - { - } - - - if (hitPart == null || (hitPart != null && hitPart.vessel != sourceVessel)) - { - Detonate(hit.point); - } - } - else if (FlightGlobals.getAltitudeAtPos(transform.position) < 0) - { - Detonate(transform.position); - } - } - } - else if (FlightGlobals.getAltitudeAtPos(currPosition) <= 0) - { - Detonate(currPosition); - } - prevPosition = currPosition; - - if (Time.time - startTime > lifeTime) - { - Detonate(transform.position); - } - - //proxy detonation - if (targetVessel != null && - (transform.position - targetVessel.transform.position).sqrMagnitude < 0.5f*blastRadius*blastRadius) - { - Detonate(transform.position); - } - } - - void Update() - { - if (HighLogic.LoadedSceneIsFlight) - { - if (BDArmorySetup.GameIsPaused) - { - if (audioSource.isPlaying) - { - audioSource.Stop(); - } - } - else - { - if (!audioSource.isPlaying) - { - audioSource.Play(); - } - } - } - } - - void Detonate(Vector3 pos) - { - BDArmorySetup.numberOfParticleEmitters--; - - ExplosionFx.CreateExplosion(pos, BlastPhysicsUtils.CalculateExplosiveMass(blastRadius), - explModelPath, explSoundPath, true); - - IEnumerator emitter = pEmitters.AsEnumerable().GetEnumerator(); - while (emitter.MoveNext()) - { - if (emitter.Current == null) continue; - if (!emitter.Current.useWorldSpace) continue; - emitter.Current.gameObject.AddComponent(); - emitter.Current.transform.parent = null; - } - emitter.Dispose(); - Destroy(gameObject); //destroy rocket on collision - } - - void SetupAudio() - { - audioSource = gameObject.AddComponent(); - audioSource.loop = true; - audioSource.minDistance = 1; - audioSource.maxDistance = 2000; - audioSource.dopplerLevel = 0.5f; - audioSource.volume = 0.9f*BDArmorySettings.BDARMORY_WEAPONS_VOLUME; - audioSource.pitch = 1f; - audioSource.priority = 255; - audioSource.spatialBlend = 1; - - audioSource.clip = GameDatabase.Instance.GetAudioClip("BDArmory/Sounds/rocketLoop"); - - UpdateVolume(); - BDArmorySetup.OnVolumeChange += UpdateVolume; - } - - void UpdateVolume() - { - if (audioSource) - { - audioSource.volume = BDArmorySettings.BDARMORY_WEAPONS_VOLUME; - } - } - } -} \ No newline at end of file From a2cb0f5143f64745fc9055f622632c0ee3a8a2b6 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Mon, 9 Jul 2018 20:28:44 -0500 Subject: [PATCH 19/72] version bump --- BDArmory/Properties/AssemblyInfo.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BDArmory/Properties/AssemblyInfo.cs b/BDArmory/Properties/AssemblyInfo.cs index 2e20042ab..c654c2df8 100644 --- a/BDArmory/Properties/AssemblyInfo.cs +++ b/BDArmory/Properties/AssemblyInfo.cs @@ -18,8 +18,8 @@ // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. -[assembly: AssemblyVersion("1.2.2.1")] -[assembly: AssemblyFileVersion("1.2.2.1")] +[assembly: AssemblyVersion("1.2.2.2")] +[assembly: AssemblyFileVersion("1.2.2.2")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. From 0724bb41978455eb48123ab54db8da54f7cee685 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Mon, 9 Jul 2018 20:43:57 -0500 Subject: [PATCH 20/72] Doctor Davinci EMP Code added --- BDArmory/BDArmory.csproj | 1 + BDArmory/Modules/ModuleDrainEC.cs | 172 ++++++++++++++++++++++++++++++ BDArmory/Modules/ModuleEMP.cs | 71 ++++++------ 3 files changed, 213 insertions(+), 31 deletions(-) create mode 100644 BDArmory/Modules/ModuleDrainEC.cs diff --git a/BDArmory/BDArmory.csproj b/BDArmory/BDArmory.csproj index cb48c8e85..fe730c861 100644 --- a/BDArmory/BDArmory.csproj +++ b/BDArmory/BDArmory.csproj @@ -73,6 +73,7 @@ + diff --git a/BDArmory/Modules/ModuleDrainEC.cs b/BDArmory/Modules/ModuleDrainEC.cs new file mode 100644 index 000000000..2d791c3ff --- /dev/null +++ b/BDArmory/Modules/ModuleDrainEC.cs @@ -0,0 +1,172 @@ +using System.Linq; + +namespace BDArmory.Modules +{ + public class ModuleDrainEC : PartModule + { + public bool armed = true; + private bool setup = true; + private int minCrew = 0; + + public override void OnStart(StartState state) + { + if (HighLogic.LoadedSceneIsFlight) + { + part.force_activate(); + vessel.OnFlyByWire += ThrottleControl; + part.OnJustAboutToBeDestroyed += EnableVessel; + } + base.OnStart(state); + } + + public void Update() + { + if (HighLogic.LoadedSceneIsFlight) + { + if (armed) + { + DisableVessel(); + } + else + { + EnableVessel(); + } + } + } + + void ThrottleControl(FlightCtrlState s) + { + s.mainThrottle = 0; + } + + private void EnableVessel() + { + foreach (var p in vessel.parts) + { + var command = p.FindModuleImplementing(); + + if (command != null) + { + command.minimumCrew = minCrew; + } + + foreach (ModuleEnginesFX engineFX in p.Modules) + { + engineFX.allowRestart = true; + } + + foreach (ModuleEngines engine in p.Modules) + { + engine.allowRestart = true; + } + } + + Destroy(this); + } + + private void DisableVessel() + { + vessel.OnFlyByWire -= ThrottleControl; + vessel.OnFlyByWire += ThrottleControl; + + var wmPart = part.FindModuleImplementing(); + + if (wmPart != null) + { + if (wmPart.guardMode) + { + wmPart.guardMode = false; + } + + if (wmPart.AI.pilotEnabled) + { + wmPart.AI.TogglePilot(); + } + } + + foreach (var p in vessel.parts) + { + PartResource r = p.Resources.Where(pr => pr.resourceName == "ElectricCharge").FirstOrDefault(); + if (r != null) + { + p.RequestResource("ElectricCharge", r.amount); + } + + var camera = p.FindModuleImplementing(); + var radar = p.FindModuleImplementing(); + var spaceRadar = p.FindModuleImplementing(); + + if (radar != null) + { + if (radar.radarEnabled) + { + radar.DisableRadar(); + } + } + + if (spaceRadar != null) + { + if (spaceRadar.radarEnabled) + { + spaceRadar.DisableRadar(); + } + } + + if (camera != null) + { + if (camera.cameraEnabled) + { + camera.DisableCamera(); + } + } + + if (setup) + { + setup = false; + + var command = p.FindModuleImplementing(); + var weapon = p.FindModuleImplementing(); + var turret = p.FindModuleImplementing(); + + if (turret != null) + { + turret.maxPitch = 0; + turret.yawRange = 0; + turret.yawRangeLimit = 0; + } + + if (weapon != null) + { + weapon.onlyFireInRange = true; + weapon.engageRangeMax = 0; + weapon.engageRangeMin = 0; + weapon.engageSLW = false; + weapon.engageMissile = false; + weapon.engageGround = false; + weapon.engageAir = false; + } + + if (command != null) + { + minCrew = command.minimumCrew; + command.minimumCrew = 100; + } + + foreach (ModuleEnginesFX engineFX in p.Modules) + { + engineFX.allowRestart = false; + engineFX.Shutdown(); + engineFX.ShutdownAction(new KSPActionParam(KSPActionGroup.None, KSPActionType.Deactivate)); + } + + foreach (ModuleEngines engine in p.Modules) + { + engine.allowRestart = false; + engine.Shutdown(); + engine.ShutdownAction(new KSPActionParam(KSPActionGroup.None, KSPActionType.Deactivate)); + } + } + } + } + } +} \ No newline at end of file diff --git a/BDArmory/Modules/ModuleEMP.cs b/BDArmory/Modules/ModuleEMP.cs index 8dcfc4e9b..6c0098a90 100644 --- a/BDArmory/Modules/ModuleEMP.cs +++ b/BDArmory/Modules/ModuleEMP.cs @@ -1,43 +1,52 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Text; -using BDArmory.Core; -using BDArmory.Core.Extension; - - -using KSP.UI.Screens; -using UniLinq; -using UnityEngine; -using BDArmory.Core.Utils; - -namespace BDArmory + +namespace BDArmory.Modules { public class ModuleEMP : PartModule { - [KSPField] - public float empRange; - [KSPField] - public bool isEMPed = false; + [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = false, guiName = "EMP Blast Radius"), + UI_Label(affectSymCounterparts = UI_Scene.All, controlEnabled = true, scene = UI_Scene.All)] + public float proximity = 5000; - public override void OnUpdate() + public override void OnStart(StartState state) { - if (!HighLogic.LoadedSceneIsFlight) + if (HighLogic.LoadedSceneIsFlight) { - return; + part.force_activate(); + part.OnJustAboutToBeDestroyed += DetonateEMPRoutine; } - //Timer code for effect? - - } - - void CheckEMP() - { - + base.OnStart(state); } - void ApplyEMP() + public void DetonateEMPRoutine() { - + foreach (Vessel v in FlightGlobals.Vessels) + { + if (!v.HoldPhysics) + { + double targetDistance = Vector3d.Distance(this.vessel.GetWorldPos3D(), v.GetWorldPos3D()); + + if (targetDistance <= proximity) + { + var count = 0; + + foreach (Part p in v.parts) + { + var wmPart = p.FindModuleImplementing(); + + if (wmPart != null) + { + count = 1; + p.AddModule("ModuleDrainEC"); + } + } + + if (count == 0) + { + v.rootPart.AddModule("ModuleDrainEC"); + } + } + } + } } } -} +} \ No newline at end of file From c07250d9a372cb64338971b8ab1fb939431846b6 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Mon, 9 Jul 2018 20:46:11 -0500 Subject: [PATCH 21/72] adding hellfire emp for testing --- .../Parts/hellfireMissile/HellfireEMP.cfg | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 BDArmory/Distribution/GameData/BDArmory/Parts/hellfireMissile/HellfireEMP.cfg diff --git a/BDArmory/Distribution/GameData/BDArmory/Parts/hellfireMissile/HellfireEMP.cfg b/BDArmory/Distribution/GameData/BDArmory/Parts/hellfireMissile/HellfireEMP.cfg new file mode 100644 index 000000000..864543746 --- /dev/null +++ b/BDArmory/Distribution/GameData/BDArmory/Parts/hellfireMissile/HellfireEMP.cfg @@ -0,0 +1,102 @@ +PART +{ +name = HellfireEMP +module = Part +author = BahamutoD / Darren9 / V8Jester + +// --- asset parameters --- +MODEL + { + model = BDArmory/Parts/hellfireMissile/model + texture = texture, BDArmory/Parts/hellfireMissile/texture + } +rescaleFactor = 1 + +// --- node definitions --- + +node_attach = 0.0, 0.089, 0, 0, 1, 0, 0 +node_stack_top = 0.0, 0.089, 0, 0, 1, 0, 0 + +// --- editor parameters --- +TechRequired = precisionEngineering +entryCost = 2100 +cost = 650 +category = Control +subcategory = 0 +title = AGM-114 Hellfire Missile EMP +manufacturer = BDAc +description = Small, quick, laser guided homing missile. +// attachment rules: stack, srfAttach, allowStack, allowSrfAttach, allowCollision +attachRules = 1,1,0,0,1 + +// --- standard part parameters --- +mass = 0.004 +dragModelType = default +maximum_drag = 0.01 +minimum_drag = 0.01 +angularDrag = 2 +crashTolerance = 5 +maxTemp = 3600 + +DRAG_CUBE +{ + cube = Default,0.02697,0.007588,0.1543,0.02701,0.007579,0.1556,0.02699,0.007581,0.1556,0.02697,0.007588,0.1543,0.002363,0.004685,0.4645,0.002363,0.006749,0.1308, -1.118E-08,1.118E-08,-0.004143, 0.1225,0.122,0.62 +} + +MODULE +{ + name = MissileLauncher + + shortName = AGM-114 + + thrust = 0.3 //KN thrust during boost phase + cruiseThrust = 0 //thrust during cruise phase + dropTime = 0 //how many seconds after release until engine ignites + boostTime = 9 //seconds of boost phase + cruiseTime = 0 //seconds of cruise phase + + guidanceActive = true //missile has guidanceActive + maxTurnRateDPS = 45 //degrees per second + + decoupleSpeed = 10 + decoupleForward = true + + + missileType = missile + homingType = AGM + targetingType = laser + maxOffBoresight = 180 + lockedSensorFOV = 7 + optimumAirspeed = 450 + DetonationDistance = 0.1 + agmDescentRatio = 1.1 + + maxAoA = 45 + + aero = true + liftArea = 0.0002 + steerMult = 0.2 + maxTorque = 1 + torqueRampUp = 25 + aeroSteerDamping = 2.5 + + minStaticLaunchRange = 200 + maxStaticLaunchRange = 6000 + + audioClipPath = BDArmory/Sounds/rocketLoop + exhaustPrefabPath = BDArmory/Models/exhaust/smallExhaust + boostExhaustPrefabPath = BDArmory/Models/exhaust/mediumExhaust +} +MODULE + { + name = BDExplosivePart + tntMass = 5 + } + +MODULE + { + name = ModuleEMP + proximity = 5000 + } + +} \ No newline at end of file From b8e828267fa520c5ad78bf255bd31d87787d4f12 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Mon, 9 Jul 2018 21:02:54 -0500 Subject: [PATCH 22/72] version bump --- BDArmory/BDArmory.csproj | 2 +- BDArmory/Properties/AssemblyInfo.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/BDArmory/BDArmory.csproj b/BDArmory/BDArmory.csproj index fe730c861..85dbecbff 100644 --- a/BDArmory/BDArmory.csproj +++ b/BDArmory/BDArmory.csproj @@ -629,7 +629,7 @@ copy /Y "$(TargetDir)"BDArmory*.pdb "%25KSP_DIR%25\GameData\%25ModName%25\Plugin @echo deleting previous build ... if exist "%25DIST_DIR%25\%25ModName%25*.zip" del "%25DIST_DIR%25\%25ModName%25*.zip" @echo packaging new build... -call "%25ZA_DIR%25\7za.exe" a -tzip -r "%25DIST_DIR%25\%25ModName%25.@(VersionNumber)_%25DATE:~4,2%25%25DATE:~7,2%25%25DATE:~10,4%25.zip" "$(ProjectDir)Distribution\*.*" +call "%25ZA_DIR%25\7za.exe" a -tzip -r "%25DIST_DIR%25\%25ModName%25.@(VersionNumber)_%25DATE:~4,2%25%25DATE:~7,2%25%25DATE:~10,4%25%25time:~0,2%25%25time:~3,2%25.zip" "$(ProjectDir)Distribution\*.*" @echo Deploy $(ProjectDir) Distribution files to test env: %25KSP_DIR%25\GameData... @echo copying:"$(ProjectDir)Distribution\GameData" to "%25KSP_DIR%25\GameData" diff --git a/BDArmory/Properties/AssemblyInfo.cs b/BDArmory/Properties/AssemblyInfo.cs index c654c2df8..115b89012 100644 --- a/BDArmory/Properties/AssemblyInfo.cs +++ b/BDArmory/Properties/AssemblyInfo.cs @@ -18,8 +18,8 @@ // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. -[assembly: AssemblyVersion("1.2.2.2")] -[assembly: AssemblyFileVersion("1.2.2.2")] +[assembly: AssemblyVersion("1.2.2.3")] +[assembly: AssemblyFileVersion("1.2.2.3")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. From 6c6fa00668dcb38c95f1d8dec9945e5b44f11c79 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Wed, 11 Jul 2018 17:34:37 -0500 Subject: [PATCH 23/72] bullet updates and merge down from support --- .../GameData/BDArmory/BulletDefs/BD_Bullets.cfg | 10 +++++----- .../GameData/BDArmory/Parts/gau-8/gau8.cfg | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg b/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg index eb34c92ed..c8f9927b8 100644 --- a/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg @@ -320,7 +320,7 @@ BULLET { name = 30x173Bullet caliber = 30 - bulletVelocity = 1180 + bulletVelocity = 1109 bulletMass = 0.3880 //HE Bullet Values explosive = False @@ -337,11 +337,11 @@ BULLET { name = 30x173HEBullet caliber = 30 - bulletVelocity = 1180 + bulletVelocity = 1109 bulletMass = 0.3880 //HE Bullet Values explosive = True - tntMass = 0.3104 + tntMass = 0.254 blastPower = 2 blastHeat = 3.7 blastRadius = 2.5 @@ -646,7 +646,7 @@ BULLET { name = 120mmBulletHE caliber = 120 - bulletVelocity = 850 + bulletVelocity = 800 bulletMass = 19.6 //HE Bullet Values explosive = True @@ -664,7 +664,7 @@ BULLET name = 120mmBulletSabot caliber = 120 bulletVelocity = 1750 - bulletMass = 19.6 + bulletMass = 9 //HE Bullet Values explosive = False tntMass = 0 diff --git a/BDArmory/Distribution/GameData/BDArmory/Parts/gau-8/gau8.cfg b/BDArmory/Distribution/GameData/BDArmory/Parts/gau-8/gau8.cfg index f98379bc6..8112a3231 100644 --- a/BDArmory/Distribution/GameData/BDArmory/Parts/gau-8/gau8.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/Parts/gau-8/gau8.cfg @@ -54,7 +54,7 @@ PART fireAnimName = fireAnim spinDownAnimation = true - roundsPerMinute = 4200 + roundsPerMinute = 3900 maxDeviation = 0.45 maxEffectiveDistance = 4000 maxTargetingRange = 5000 From 875210a87f6a225bb7d7d757a0f52eea08149db3 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Wed, 11 Jul 2018 17:35:25 -0500 Subject: [PATCH 24/72] restore changes before wip --- BDArmory.Core/Extension/PartExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BDArmory.Core/Extension/PartExtensions.cs b/BDArmory.Core/Extension/PartExtensions.cs index dee0d2294..c4ed5f3b3 100644 --- a/BDArmory.Core/Extension/PartExtensions.cs +++ b/BDArmory.Core/Extension/PartExtensions.cs @@ -368,7 +368,7 @@ public static float DamageReduction(float armor, float damage,bool isMissile,flo } - if(!isMissile && !(penetrationfactor >= 1f)) + if (!isMissile && !(penetrationfactor >= 1f)) { if (BDAMath.Between(armor, 100f, 200f)) { From 80e25bb80962f309cfb01daf844c5f21ba7ef7e3 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Wed, 11 Jul 2018 17:55:03 -0500 Subject: [PATCH 25/72] fixes for emp --- BDArmory/Modules/ModuleDrainEC.cs | 108 +++++++++++++++++++----------- BDArmory/Modules/ModuleEMP.cs | 5 +- 2 files changed, 71 insertions(+), 42 deletions(-) diff --git a/BDArmory/Modules/ModuleDrainEC.cs b/BDArmory/Modules/ModuleDrainEC.cs index 2d791c3ff..377b66ac3 100644 --- a/BDArmory/Modules/ModuleDrainEC.cs +++ b/BDArmory/Modules/ModuleDrainEC.cs @@ -1,6 +1,8 @@ -using System.Linq; +using BDArmory.Modules; +using System.Diagnostics; +using System.Linq; -namespace BDArmory.Modules +namespace EMP { public class ModuleDrainEC : PartModule { @@ -66,67 +68,68 @@ private void EnableVessel() private void DisableVessel() { + UnityEngine.Debug.Log("MODULE DRAIN EC ------------- Disable Vessel Start"); vessel.OnFlyByWire -= ThrottleControl; vessel.OnFlyByWire += ThrottleControl; - var wmPart = part.FindModuleImplementing(); + UnityEngine.Debug.Log("MODULE DRAIN EC ------------- Disable Vessel Checking Vessel Parts"); - if (wmPart != null) + foreach (Part p in vessel.parts) { - if (wmPart.guardMode) - { - wmPart.guardMode = false; - } + UnityEngine.Debug.Log("MODULE DRAIN EC ------------- Disable Vessel Draining EC"); - if (wmPart.AI.pilotEnabled) - { - wmPart.AI.TogglePilot(); - } - } - - foreach (var p in vessel.parts) - { PartResource r = p.Resources.Where(pr => pr.resourceName == "ElectricCharge").FirstOrDefault(); if (r != null) { - p.RequestResource("ElectricCharge", r.amount); - } - - var camera = p.FindModuleImplementing(); - var radar = p.FindModuleImplementing(); - var spaceRadar = p.FindModuleImplementing(); - - if (radar != null) - { - if (radar.radarEnabled) + if (r.amount >= 0) { - radar.DisableRadar(); + p.RequestResource("ElectricCharge", r.amount); } } - if (spaceRadar != null) + if (setup) { - if (spaceRadar.radarEnabled) + UnityEngine.Debug.Log("MODULE DRAIN EC ------------- Disable Vessel Setup"); + + setup = false; + + var camera = p.FindModuleImplementing(); + var radar = p.FindModuleImplementing(); + var spaceRadar = p.FindModuleImplementing(); + UnityEngine.Debug.Log("MODULE DRAIN EC ------------- Disable Vessel Seeking Radar"); + + if (radar != null) { - spaceRadar.DisableRadar(); + if (radar.radarEnabled) + { + radar.DisableRadar(); + } } - } - if (camera != null) - { - if (camera.cameraEnabled) + UnityEngine.Debug.Log("MODULE DRAIN EC ------------- Disable Vessel Seeking Space Radar"); + + if (spaceRadar != null) { - camera.DisableCamera(); + if (spaceRadar.radarEnabled) + { + spaceRadar.DisableRadar(); + } } - } - if (setup) - { - setup = false; + UnityEngine.Debug.Log("MODULE DRAIN EC ------------- Disable Vessel Seeking Camera"); + + if (camera != null) + { + if (camera.cameraEnabled) + { + camera.DisableCamera(); + } + } var command = p.FindModuleImplementing(); var weapon = p.FindModuleImplementing(); var turret = p.FindModuleImplementing(); + UnityEngine.Debug.Log("MODULE DRAIN EC ------------- Disable Vessel Seeking Turret"); if (turret != null) { @@ -134,6 +137,7 @@ private void DisableVessel() turret.yawRange = 0; turret.yawRangeLimit = 0; } + UnityEngine.Debug.Log("MODULE DRAIN EC ------------- Disable Vessel Seeking Weapon"); if (weapon != null) { @@ -145,13 +149,37 @@ private void DisableVessel() weapon.engageGround = false; weapon.engageAir = false; } + UnityEngine.Debug.Log("MODULE DRAIN EC ------------- Disable Vessel Seeking Command"); if (command != null) { minCrew = command.minimumCrew; command.minimumCrew = 100; } + /* + var wmPart = part.FindModuleImplementing(); + UnityEngine.Debug.Log("MODULE DRAIN EC ------------- Disable Vessel Find Weapon Manager"); + if (wmPart != null) + { + UnityEngine.Debug.Log("MODULE DRAIN EC ------------- Disable Vessel Found Weapon Manager"); + + if (wmPart.guardMode) + { + UnityEngine.Debug.Log("MODULE DRAIN EC ------------- Disable Vessel Guard Mode Off"); + + wmPart.guardMode = false; + } + + if (wmPart.AI.pilotEnabled) + { + UnityEngine.Debug.Log("MODULE DRAIN EC ------------- Disable Vessel Pilot AI Off"); + + wmPart.AI.TogglePilot(); + } + } + + /* foreach (ModuleEnginesFX engineFX in p.Modules) { engineFX.allowRestart = false; @@ -164,7 +192,7 @@ private void DisableVessel() engine.allowRestart = false; engine.Shutdown(); engine.ShutdownAction(new KSPActionParam(KSPActionGroup.None, KSPActionType.Deactivate)); - } + }*/ } } } diff --git a/BDArmory/Modules/ModuleEMP.cs b/BDArmory/Modules/ModuleEMP.cs index 6c0098a90..af2da4e04 100644 --- a/BDArmory/Modules/ModuleEMP.cs +++ b/BDArmory/Modules/ModuleEMP.cs @@ -1,5 +1,6 @@ - -namespace BDArmory.Modules +using BDArmory.Modules; + +namespace EMP { public class ModuleEMP : PartModule { From b5b14d281a12f4d63ace75b88532e4831eddcaad Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Sun, 15 Jul 2018 02:50:39 +0200 Subject: [PATCH 26/72] HP overhaul --- BDArmory.Core/Extension/PartExtensions.cs | 23 +++++++++++------- BDArmory.Core/Module/HitpointTracker.cs | 29 +++++++++++++---------- 2 files changed, 32 insertions(+), 20 deletions(-) diff --git a/BDArmory.Core/Extension/PartExtensions.cs b/BDArmory.Core/Extension/PartExtensions.cs index dee0d2294..fdb41745a 100644 --- a/BDArmory.Core/Extension/PartExtensions.cs +++ b/BDArmory.Core/Extension/PartExtensions.cs @@ -276,24 +276,31 @@ public static bool IsMissile(this Part part) public static float GetArea(this Part part) { - var boundsSize = PartGeometryUtil.MergeBounds(part.GetRendererBounds(), part.transform).size; - float sfcAreaCalc = 2f * (boundsSize.x * boundsSize.y) + 2f * (boundsSize.y * boundsSize.z) + 2f * (boundsSize.x * boundsSize.z); - //Debug.Log("[BDArmory]: Surface Area1: " + part.surfaceAreas.magnitude); - //Debug.Log("[BDArmory]: Surface Area2: " + sfcAreaCalc); + float sfcAreaCalc = 2f * (part.prefabSize.x * part.prefabSize.y) + 2f * (part.prefabSize.y * part.prefabSize.z) + 2f * (part.prefabSize.x * part.prefabSize.z); + if (sfcAreaCalc == 0) + { + sfcAreaCalc = 2f * (part.HighlightRenderer[0].bounds.size.x * part.HighlightRenderer[0].bounds.size.y) + 2f * (part.HighlightRenderer[0].bounds.size.y * part.HighlightRenderer[0].bounds.size.z) + 2f * (part.HighlightRenderer[0].bounds.size.x * part.HighlightRenderer[0].bounds.size.z); + } + + Debug.Log("Part name = " + part.name + "Area ="+ sfcAreaCalc); return sfcAreaCalc; } public static float GetAverageBoundSize(this Part part) { - var boundsSize = PartGeometryUtil.MergeBounds(part.GetRendererBounds(), part.transform).size; - return (boundsSize.x + boundsSize.y + boundsSize.z) / 3f; + return (part.prefabSize.x + part.prefabSize.y + part.prefabSize.z) / 3f; } public static float GetVolume(this Part part) { - var boundsSize = PartGeometryUtil.MergeBounds(part.GetRendererBounds(), part.transform).size; - return boundsSize.x * boundsSize.y * boundsSize.z; + var volume = part.prefabSize.x * part.prefabSize.y * part.prefabSize.z; + if (volume == 0) + { + volume = part.HighlightRenderer[0].bounds.size.x * part.HighlightRenderer[0].bounds.size.y * part.HighlightRenderer[0].bounds.size.z; + } + Debug.Log("Part name = " + part.name + "volume =" + volume); + return volume; } public static float GetDensity (this Part part) diff --git a/BDArmory.Core/Module/HitpointTracker.cs b/BDArmory.Core/Module/HitpointTracker.cs index 1fbe8af04..e2e2958c9 100644 --- a/BDArmory.Core/Module/HitpointTracker.cs +++ b/BDArmory.Core/Module/HitpointTracker.cs @@ -42,7 +42,11 @@ public class HitpointTracker : PartModule private bool _setupRun = false; private bool _firstSetup = true; - protected virtual void Setup() + private const float mk1CockpitArea = 7.292964f; + private const int HpRounding = 250; + + + public void Setup() { if (_setupRun) { @@ -56,6 +60,8 @@ public override void OnLoad(ConfigNode node) { base.OnLoad(node); + if (!HighLogic.LoadedSceneIsEditor && !HighLogic.LoadedSceneIsFlight) return; + if (part.partInfo == null) { // Loading of the prefab from the part config @@ -73,7 +79,7 @@ public override void OnLoad(ConfigNode node) } } - protected virtual void SetupPrefab() + public void SetupPrefab() { if (part != null) { @@ -129,16 +135,16 @@ public override void OnStart(StartState state) } } - private void ShipModified(ShipConstruct data) + public void ShipModified(ShipConstruct data) { SetupPrefab(); } void OnGUI() { - if (HighLogic.LoadedSceneIsEditor && _firstSetup) + if (HighLogic.LoadedSceneIsEditor) { - //SetupPrefab(); + SetupPrefab(); } } @@ -158,7 +164,7 @@ public override void OnUpdate() #region Hitpoints Functions - private float CalculateTotalHitpoints() + public float CalculateTotalHitpoints() { float hitpoints; @@ -168,17 +174,16 @@ private float CalculateTotalHitpoints() var density = part.GetDensity(); //2. Incresing density based on crash tolerance - density += Mathf.Clamp(part.crashTolerance, 10f, 30f); + //density += Mathf.Clamp(part.crashTolerance, 10f, 30f); //12 square meters is the standard size of MK1 fuselage using it as a base - var areaExcess = Mathf.Max(part.GetArea() - 12f, 0); - var areaCalculation = Mathf.Min(12f, part.GetArea()) + Mathf.Pow(areaExcess, (1f / 3f)); + var areaCalculation = part.GetArea() / mk1CockpitArea; //3. final calculations hitpoints = areaCalculation * density * hitpointMultiplier; - hitpoints = Mathf.Round(hitpoints/500) * 500; + hitpoints = Mathf.Round(hitpoints/ HpRounding) * HpRounding; - if (hitpoints <= 0) hitpoints = 500; + if (hitpoints <= 0) hitpoints = HpRounding; } else { @@ -193,7 +198,7 @@ private float CalculateTotalHitpoints() } - if (hitpoints <= 0) hitpoints = 500; + if (hitpoints <= 0) hitpoints = HpRounding; return hitpoints; } From c8f4d18ed3b18d1680917ab1dbb30fa449696ed6 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Sun, 15 Jul 2018 18:57:50 -0500 Subject: [PATCH 27/72] wip merge upstream --- BDArmory.Core/Extension/PartExtensions.cs | 62 +++++++--- BDArmory.Core/Module/HitpointTracker.cs | 19 ++- .../BDArmory/BulletDefs/BD_Bullets.cfg | 34 +++++ .../000000_HitpointModule_PartFixes.cfg | 24 ++-- .../GameData/BDArmory/MMPatches/Armor_CVE.cfg | 9 +- .../GameData/BDArmory/MMPatches/BDA_Armor.cfg | 4 +- .../BDArmory/MMPatches/BDA_TweakScale.cfg | 9 ++ .../MMPatches/Explode_Mode_Squad_Tanks.cfg | 116 ++++++------------ .../GameData/BDArmory/settings.cfg | 24 ++-- 9 files changed, 170 insertions(+), 131 deletions(-) diff --git a/BDArmory.Core/Extension/PartExtensions.cs b/BDArmory.Core/Extension/PartExtensions.cs index c4ed5f3b3..cbe42f401 100644 --- a/BDArmory.Core/Extension/PartExtensions.cs +++ b/BDArmory.Core/Extension/PartExtensions.cs @@ -93,7 +93,7 @@ public static void AddBallisticDamage(this Part p, float damage_ = ((0.5f * (mass * Mathf.Pow(impactVelocity, 2))) * (BDArmorySettings.DMG_MULTIPLIER / 100) * bulletDmgMult - * 1e-4f); + * 1e-4f * BDArmorySettings.BALLISTIC_DMG_FACTOR); ////////////////////////////////////////////////////////// // Armor Reduction factors @@ -274,10 +274,21 @@ public static bool IsMissile(this Part part) part.Modules.Contains("BDModularGuidance"); } - public static float GetArea(this Part part) + public static float GetArea(this Part part, bool isprefab = false, Part prefab = null) { - var boundsSize = PartGeometryUtil.MergeBounds(part.GetRendererBounds(), part.transform).size; + //var boundsSize = PartGeometryUtil.MergeBounds(part.GetRendererBounds(), part.transform).size; + var boundsSize = new Vector3(0, 0, 0); + if (isprefab) + { + boundsSize = GetBoundsSize(prefab); + } + else + { + boundsSize = GetBoundsSize(part); + } + float sfcAreaCalc = 2f * (boundsSize.x * boundsSize.y) + 2f * (boundsSize.y * boundsSize.z) + 2f * (boundsSize.x * boundsSize.z); + //Debug.Log("[BDArmory]: Surface Area1: " + part.surfaceAreas.magnitude); //Debug.Log("[BDArmory]: Surface Area2: " + sfcAreaCalc); @@ -349,7 +360,8 @@ public static bool HasFuel(this Part part) } public static float DamageReduction(float armor, float damage,bool isMissile,float caliber = 0, float penetrationfactor = 0) - { + { + float _damageReduction; if (isMissile) { @@ -370,20 +382,37 @@ public static float DamageReduction(float armor, float damage,bool isMissile,flo if (!isMissile && !(penetrationfactor >= 1f)) { - if (BDAMath.Between(armor, 100f, 200f)) - { - damage *= 0.300f; - } - else if (BDAMath.Between(armor, 200f, 400f)) - { - damage *= 0.250f; - } - else if (BDAMath.Between(armor, 400f, 500f)) + //if (BDAMath.Between(armor, 100f, 200f)) + //{ + // damage *= 0.300f; + //} + //else if (BDAMath.Between(armor, 200f, 400f)) + //{ + // damage *= 0.250f; + //} + //else if (BDAMath.Between(armor, 400f, 500f)) + //{ + // damage *= 0.200f; + //} + + + //y=(98.34817*x)/(97.85935+x) + + _damageReduction = (113 * armor) / (154 + armor); + + + if (BDArmorySettings.DRAW_DEBUG_LABELS) { - damage *= 0.200f; + Debug.Log("[BDArmory]: Damage Before Reduction : " + Math.Round(damage, 2) / 100); + Debug.Log("[BDArmory]: Damage Reduction : " + Math.Round(_damageReduction, 2)/100); + Debug.Log("[BDArmory]: Damage After Armor : " + Math.Round(damage *= (_damageReduction / 100f))); } + + damage *= (_damageReduction / 100f); } + + return damage; } @@ -401,5 +430,10 @@ public static void CheckDamageFX(Part part) } } + + public static Vector3 GetBoundsSize(Part part) + { + return PartGeometryUtil.MergeBounds(part.GetRendererBounds(), part.transform).size; + } } } \ No newline at end of file diff --git a/BDArmory.Core/Module/HitpointTracker.cs b/BDArmory.Core/Module/HitpointTracker.cs index 1fbe8af04..1c08fb675 100644 --- a/BDArmory.Core/Module/HitpointTracker.cs +++ b/BDArmory.Core/Module/HitpointTracker.cs @@ -165,14 +165,23 @@ private float CalculateTotalHitpoints() if (!part.IsMissile()) { //1. Density of the dry mass of the part. - var density = part.GetDensity(); + var density = part.GetDensity(); + + + Debug.Log("[BDArmory]: Hitpoint Calc | Density : " + density); //2. Incresing density based on crash tolerance density += Mathf.Clamp(part.crashTolerance, 10f, 30f); + Debug.Log("[BDArmory]: Hitpoint Calc | Density + CrashTolerance : " + density ); + //12 square meters is the standard size of MK1 fuselage using it as a base - var areaExcess = Mathf.Max(part.GetArea() - 12f, 0); - var areaCalculation = Mathf.Min(12f, part.GetArea()) + Mathf.Pow(areaExcess, (1f / 3f)); + var areaExcess = Mathf.Max(part.GetArea(true,_prefabPart) - 12f, 0); + var areaCalculation = Mathf.Min(12f, part.GetArea(true, _prefabPart)) + Mathf.Pow(areaExcess, (1f / 3f)); + + //areaCalculation = (float)part.exposedArea; + + Debug.Log("[BDArmory]: Hitpoin Calc | AreaCalc : " + areaCalculation); //3. final calculations hitpoints = areaCalculation * density * hitpointMultiplier; @@ -191,9 +200,11 @@ private float CalculateTotalHitpoints() { hitpoints = maxHitPoints; } - if (hitpoints <= 0) hitpoints = 500; + + Debug.Log("[BDArmory]: Hitpoint Calc Ran : " + hitpoints); + return hitpoints; } diff --git a/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg b/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg index c8f9927b8..39556ecaf 100644 --- a/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg @@ -693,6 +693,40 @@ BULLET } +BULLET +{ + name = 125mmBulletHE + caliber = 125 + bulletVelocity = 915 + bulletMass = 18.4 + //HE Bullet Values + explosive = True + tntMass = 8.5 + blastPower = 25 + blastHeat = 30 + blastRadius = 30 + apBulletMod = 6 + bulletDragTypeName = AnalyticEstimate + +} + +BULLET +{ + name = 125mmBulletSabot + caliber = 125 + bulletVelocity = 2050 + bulletMass = 9.52 + //HE Bullet Values + explosive = False + tntMass = 0 + blastPower = 0 + blastHeat = 0 + blastRadius = 0 + apBulletMod = 20 + bulletDragTypeName = AnalyticEstimate + +} + BULLET { name = 130Bullet diff --git a/BDArmory/Distribution/GameData/BDArmory/MMPatches/000000_HitpointModule_PartFixes.cfg b/BDArmory/Distribution/GameData/BDArmory/MMPatches/000000_HitpointModule_PartFixes.cfg index 7d78369bf..6952397eb 100644 --- a/BDArmory/Distribution/GameData/BDArmory/MMPatches/000000_HitpointModule_PartFixes.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/MMPatches/000000_HitpointModule_PartFixes.cfg @@ -4,9 +4,8 @@ @PART[turboJet] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 2000 ExplodeMode = Never @@ -16,9 +15,8 @@ @PART[elevon*] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 500 ExplodeMode = Never @@ -29,9 +27,8 @@ @PART[B9.Aero.Wing.Procedural.TypeB] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 500 ExplodeMode = Never @@ -41,9 +38,8 @@ @PART[winglet3] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 650 ExplodeMode = Never @@ -53,9 +49,8 @@ @PART[tailfin] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 750 ExplodeMode = Never @@ -65,9 +60,8 @@ @PART[AdvancedCanard] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 750 ExplodeMode = Never @@ -77,9 +71,8 @@ @PART[CanardController] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 750 ExplodeMode = Never @@ -89,9 +82,8 @@ @PART[nacelleBody] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 750 ExplodeMode = Never diff --git a/BDArmory/Distribution/GameData/BDArmory/MMPatches/Armor_CVE.cfg b/BDArmory/Distribution/GameData/BDArmory/MMPatches/Armor_CVE.cfg index 79cf72f70..37a11cace 100644 --- a/BDArmory/Distribution/GameData/BDArmory/MMPatches/Armor_CVE.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/MMPatches/Armor_CVE.cfg @@ -1,8 +1,7 @@ @PART[EHInimitzRadar] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 50 maxHitPoints = 8000 ExplodeMode = Never @@ -12,9 +11,8 @@ @PART[EHInimitz] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 300000 ExplodeMode = Never @@ -24,9 +22,8 @@ @PART[ehiNimitzBridge] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 100000 ExplodeMode = Never diff --git a/BDArmory/Distribution/GameData/BDArmory/MMPatches/BDA_Armor.cfg b/BDArmory/Distribution/GameData/BDArmory/MMPatches/BDA_Armor.cfg index c943a8170..6093d2004 100644 --- a/BDArmory/Distribution/GameData/BDArmory/MMPatches/BDA_Armor.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/MMPatches/BDA_Armor.cfg @@ -1,8 +1,8 @@ @PART[BD*Armor] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker + maxHitPoints = 8000 ArmorThickness = 150 } } diff --git a/BDArmory/Distribution/GameData/BDArmory/MMPatches/BDA_TweakScale.cfg b/BDArmory/Distribution/GameData/BDArmory/MMPatches/BDA_TweakScale.cfg index c07d31a02..9df9455de 100644 --- a/BDArmory/Distribution/GameData/BDArmory/MMPatches/BDA_TweakScale.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/MMPatches/BDA_TweakScale.cfg @@ -6,3 +6,12 @@ defaultScale = 2.5 } } + +@PART[awacsRadar] +{ + %MODULE[TweakScale] + { + %name = TweakScale + %type = free + } +} \ No newline at end of file diff --git a/BDArmory/Distribution/GameData/BDArmory/MMPatches/Explode_Mode_Squad_Tanks.cfg b/BDArmory/Distribution/GameData/BDArmory/MMPatches/Explode_Mode_Squad_Tanks.cfg index c44cd940d..16c022609 100644 --- a/BDArmory/Distribution/GameData/BDArmory/MMPatches/Explode_Mode_Squad_Tanks.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/MMPatches/Explode_Mode_Squad_Tanks.cfg @@ -2,98 +2,87 @@ @PART[fuelTank] // FL-T400 Fuel Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[fuelTank_long] // FL-T800 Fuel Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[fuelTank1-2] // Rockomax X200-32 Fuel Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[fuelTank2-2] // Rockomax X200-16 Fuel Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[fuelTank3-2] // Rockomax Jumbo-64 Fuel Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[fuelTank4-2] // Rockomax X200-8 Fuel Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[fuelTankSmall] // FL-T200 Fuel Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[fuelTankSmallFlat] // FL-T100 Fuel Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[miniFuelTank] // Oscar-B Fuel Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[MK1Fuselage] // Mk1 Fuselage - Jet Fuel { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[miniFuselage] // Mk0 Liquid Fuel Fuselage { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @@ -101,63 +90,56 @@ // ========== MK3-Parts ======== @PART[mk3FuselageLF_25] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk3FuselageLF_50] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk3FuselageMONO] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk3FuselageLFO_25] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk3FuselageLFO_50] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk3FuselageLF_100] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk3FuselageLFO_100] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @@ -165,95 +147,84 @@ @PART[adapterMk3-Mk2] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[adapterMk3-Size2] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[adapterMk3-Size2Slant] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[adapterSize3-Mk3] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[adapterSize2-Mk2] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[adapterSize2-Size1] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[adapterSize2-Size1Slant] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[adapterEngines] // Mk3 Engine Mount { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[Size3LargeTank] // Kerbodyne S3-14400 Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[Size3MediumTank] // Kerbodyne S3-7200 Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[Size3SmallTank] // Kerbodyne S3-3600 Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @@ -261,80 +232,71 @@ @PART[Size3to2Adapter] // Kerbodyne ADTP-2-3 { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic - }} + } } @PART[mk2_1m_Bicoupler] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk2_1m_AdapterLong] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk2SpacePlaneAdapter] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk2Fuselage] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk2FuselageLongLFO] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk2FuselageShortLiquid] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk2FuselageShortLFO] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk2FuselageShortMono] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } diff --git a/BDArmory/Distribution/GameData/BDArmory/settings.cfg b/BDArmory/Distribution/GameData/BDArmory/settings.cfg index 70cc16192..24d7db569 100644 --- a/BDArmory/Distribution/GameData/BDArmory/settings.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/settings.cfg @@ -1,14 +1,16 @@ BDASettings { INSTAKILL = False + INFINITE_AMMO = False BULLET_HITS = True + EJECT_SHELLS = True + SHELL_COLLISIONS = True + RECOIL_FACTOR = 0.75 PHYSICS_RANGE = 200000 MAX_BULLET_RANGE = 8000 MAX_GUARD_VISUAL_RANGE = 200000 MAX_ACTIVE_RADAR_RANGE = 200000 MAX_ENGAGEMENT_RANGE = 200000 - EJECT_SHELLS = True - INFINITE_AMMO = False DRAW_DEBUG_LINES = False DRAW_AIMERS = True AIM_ASSIST = True @@ -29,20 +31,18 @@ BDASettings GLOBAL_LIFT_MULTIPLIER = 0.25 GLOBAL_DRAG_MULTIPLIER = 6 IVA_LOWPASS_FREQ = 2500 - PEACE_MODE = False - SHELL_COLLISIONS = True - HITPOINT_MULTIPLIER = 2.0 - RECOIL_FACTOR = 0.75 + PEACE_MODE = False + MAX_FIRES_PER_VESSEL = 10 + FIRELIFETIME_IN_SECONDS = 90 + PERFORMANCE_LOGGING = false + IGNORE_TERRAIN_CHECK = false + HITPOINT_MULTIPLIER = 3.0 DMG_MULTIPLIER = 100 - BALLISTIC_DMG_FACTOR = 1 + BALLISTIC_DMG_FACTOR = 1.55 EXP_DMG_MOD_BALLISTIC = 1.125 EXP_DMG_MOD_MISSILE = 6.75 EXP_IMP_MOD = 0.125 - ADVANCED_EDIT = true - MAX_FIRES_PER_VESSEL = 10 - FIRELIFETIME_IN_SECONDS = 90 - PERFORMANCE_LOGGING = false - IGNORE_TERRAIN_CHECK = false + ADVANCED_EDIT = true } BDAInputSettings { From 79aba98013a71ccb8ebc23d86cf9f963fa0b9041 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Sun, 15 Jul 2018 19:02:39 -0500 Subject: [PATCH 28/72] abrams test turrets, curvedata --- .../BDArmory/Parts/m1Abrams/m1Abrams_he.cfg | 123 ++++++++++++++++++ .../Parts/m1Abrams/m1Abrams_sabot.cfg | 123 ++++++++++++++++++ DamageCurves/ArmorCurve.txt | 18 +++ 3 files changed, 264 insertions(+) create mode 100644 BDArmory/Distribution/GameData/BDArmory/Parts/m1Abrams/m1Abrams_he.cfg create mode 100644 BDArmory/Distribution/GameData/BDArmory/Parts/m1Abrams/m1Abrams_sabot.cfg create mode 100644 DamageCurves/ArmorCurve.txt diff --git a/BDArmory/Distribution/GameData/BDArmory/Parts/m1Abrams/m1Abrams_he.cfg b/BDArmory/Distribution/GameData/BDArmory/Parts/m1Abrams/m1Abrams_he.cfg new file mode 100644 index 000000000..43d2f120a --- /dev/null +++ b/BDArmory/Distribution/GameData/BDArmory/Parts/m1Abrams/m1Abrams_he.cfg @@ -0,0 +1,123 @@ +PART +{ +// Kerbal Space Program - Part Config +// +// + +// --- general parameters --- +name = bahaM1Abrams +module = Part +author = BahamutoD + +// --- asset parameters --- +mesh = model.mu +rescaleFactor = 1 + + +// --- node definitions --- +node_attach = 0.0, -0.178, 0, 0, -1, 0, 0 + +// --- editor parameters --- +TechRequired = precisionEngineering +entryCost = 2100 +cost = 3500 +category = none +subcategory = 0 +title = M1 Abrams Cannon - HE +manufacturer = Bahamuto Dynamics +description = A 120mm cannon on an armored turret. CannonShells +// attachment rules: stack, srfAttach, allowStack, allowSrfAttach, allowCollision +attachRules = 0,1,0,0,1 + +// --- standard part parameters --- +mass = 2 +dragModelType = default +maximum_drag = 0.2 +minimum_drag = 0.2 +angularDrag = 2 +crashTolerance = 125 +maxTemp = 3600 + +stagingIcon = SOLID_BOOSTER + +MODULE +{ + name = ModuleTurret + + yawTransformName = aimRotate + pitchTransformName = aimPitch + + pitchSpeedDPS = 60 + yawSpeedDPS = 40 + + minPitch = -4 + maxPitch = 27 + yawRange = 360 + + smoothRotation = true + smoothMultiplier = 10 + + audioPath = BDArmory/Sounds/hydraulicLoop + maxAudioPitch = 0.42 + minAudioPitch = 0.15 + maxVolume = 0.60 +} + +MODULE +{ + name = ModuleWeapon + + fireTransformName = fireTransform + + hasDeployAnim = false + + hasFireAnimation = true + fireAnimName = fireAnim + spinDownAnimation = false + + roundsPerMinute = 10 + maxDeviation = 0.2 + maxTargetingRange = 8000 + maxEffectiveDistance = 8000 + + ammoName = CannonShells + bulletType = 120mmBulletHE + requestResourceAmount = 1 + + hasRecoil = true + onlyFireInRange = true + bulletDrop = true + + weaponType = ballistic + + projectileColor = 255, 90, 0, 190 + + tracerStartWidth = 0.27 + tracerEndWidth = 0.20 + tracerLength = 0 + tracerDeltaFactor = 3.75 + tracerLuminance = 2 + + maxHeat = 3600 + heatPerShot = 60 + heatLoss = 740 + + fireSoundPath = BDArmory/Parts/m1Abrams/sounds/shot + overheatSoundPath = BDArmory/Parts/50CalTurret/sounds/turretOverheat + oneShotSound = true + showReloadMeter = true + reloadAudioPath = BDArmory/Parts/m1Abrams/sounds/reload + +} + + + + +RESOURCE +{ + name = CannonShells + amount = 20 + maxAmount = 20 +} + +} diff --git a/BDArmory/Distribution/GameData/BDArmory/Parts/m1Abrams/m1Abrams_sabot.cfg b/BDArmory/Distribution/GameData/BDArmory/Parts/m1Abrams/m1Abrams_sabot.cfg new file mode 100644 index 000000000..45171ce86 --- /dev/null +++ b/BDArmory/Distribution/GameData/BDArmory/Parts/m1Abrams/m1Abrams_sabot.cfg @@ -0,0 +1,123 @@ +PART +{ +// Kerbal Space Program - Part Config +// +// + +// --- general parameters --- +name = bahaM1Abrams +module = Part +author = BahamutoD + +// --- asset parameters --- +mesh = model.mu +rescaleFactor = 1 + + +// --- node definitions --- +node_attach = 0.0, -0.178, 0, 0, -1, 0, 0 + +// --- editor parameters --- +TechRequired = precisionEngineering +entryCost = 2100 +cost = 3500 +category = none +subcategory = 0 +title = M1 Abrams Cannon - Sabot +manufacturer = Bahamuto Dynamics +description = A 120mm cannon on an armored turret. CannonShells +// attachment rules: stack, srfAttach, allowStack, allowSrfAttach, allowCollision +attachRules = 0,1,0,0,1 + +// --- standard part parameters --- +mass = 2 +dragModelType = default +maximum_drag = 0.2 +minimum_drag = 0.2 +angularDrag = 2 +crashTolerance = 125 +maxTemp = 3600 + +stagingIcon = SOLID_BOOSTER + +MODULE +{ + name = ModuleTurret + + yawTransformName = aimRotate + pitchTransformName = aimPitch + + pitchSpeedDPS = 60 + yawSpeedDPS = 40 + + minPitch = -4 + maxPitch = 27 + yawRange = 360 + + smoothRotation = true + smoothMultiplier = 10 + + audioPath = BDArmory/Sounds/hydraulicLoop + maxAudioPitch = 0.42 + minAudioPitch = 0.15 + maxVolume = 0.60 +} + +MODULE +{ + name = ModuleWeapon + + fireTransformName = fireTransform + + hasDeployAnim = false + + hasFireAnimation = true + fireAnimName = fireAnim + spinDownAnimation = false + + roundsPerMinute = 10 + maxDeviation = 0.2 + maxTargetingRange = 8000 + maxEffectiveDistance = 8000 + + ammoName = CannonShells + bulletType = 120mmBulletSabot + requestResourceAmount = 1 + + hasRecoil = true + onlyFireInRange = true + bulletDrop = true + + weaponType = ballistic + + projectileColor = 255, 90, 0, 190 + + tracerStartWidth = 0.27 + tracerEndWidth = 0.20 + tracerLength = 0 + tracerDeltaFactor = 3.75 + tracerLuminance = 2 + + maxHeat = 3600 + heatPerShot = 60 + heatLoss = 740 + + fireSoundPath = BDArmory/Parts/m1Abrams/sounds/shot + overheatSoundPath = BDArmory/Parts/50CalTurret/sounds/turretOverheat + oneShotSound = true + showReloadMeter = true + reloadAudioPath = BDArmory/Parts/m1Abrams/sounds/reload + +} + + + + +RESOURCE +{ + name = CannonShells + amount = 20 + maxAmount = 20 +} + +} diff --git a/DamageCurves/ArmorCurve.txt b/DamageCurves/ArmorCurve.txt new file mode 100644 index 000000000..6b81a3eec --- /dev/null +++ b/DamageCurves/ArmorCurve.txt @@ -0,0 +1,18 @@ + 25 5 + 50 10 + 75 35 + 100 50 + 125 55 + 150 65 + 175 68 + 200 70 + 250 73 + 300 75 + 350 76 + 400 77 + 450 80 + 500 85 + +y\ =\ \ 80.58079\ +\frac{\ \left(-0.18818185\ -\ 80.5\right)}{1+\ \left(\frac{x}{\left(90\right)}\right)^{2.5}} + +y=(113*x)/(154+x) \ No newline at end of file From 7ae7b873ec6f1313e20c27767539df566d692d16 Mon Sep 17 00:00:00 2001 From: Gedas Date: Tue, 17 Jul 2018 00:28:43 +0300 Subject: [PATCH 29/72] full throttle when no power is available but desired speed is >0 --- BDArmory/Control/BDAirspeedControl.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BDArmory/Control/BDAirspeedControl.cs b/BDArmory/Control/BDAirspeedControl.cs index 9b4f965cc..776ed4ca0 100644 --- a/BDArmory/Control/BDAirspeedControl.cs +++ b/BDArmory/Control/BDAirspeedControl.cs @@ -87,7 +87,7 @@ void SetAcceleration(float accel, FlightCtrlState s) if (engineAccel == 0) { - s.mainThrottle = 0; + s.mainThrottle = accel > 0 ? 1 : 0; return; } From 2ef50f183c6e6a96a27afcd3f9f3a2a732a6b725 Mon Sep 17 00:00:00 2001 From: PapaJoesSoup Date: Mon, 16 Jul 2018 14:50:18 -0700 Subject: [PATCH 30/72] Repair BDArmory Project file to allow build and compile. remove references to packages\Microsoft.Net.Compilers.2.8.0. --- BDArmory/BDArmory.csproj | 8 -------- 1 file changed, 8 deletions(-) diff --git a/BDArmory/BDArmory.csproj b/BDArmory/BDArmory.csproj index 06b5ed980..9f6f44900 100644 --- a/BDArmory/BDArmory.csproj +++ b/BDArmory/BDArmory.csproj @@ -1,6 +1,5 @@  - Debug AnyCPU @@ -419,7 +418,6 @@ - @@ -662,10 +660,4 @@ xcopy /E /Y "$(ProjectDir)Distribution\GameData" "%25KSP_DIR%25\GameData" - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file From 9ba8bf5fc7dc791eabf28a9a06562db87b1a2919 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Tue, 17 Jul 2018 21:08:39 -0500 Subject: [PATCH 31/72] tweakscale redist experiment --- BDArmory.Core/BDArmory.Core.csproj | 3 +++ BDArmory.Core/Module/HitpointTracker.cs | 27 ++++++++++++++----------- BDArmory.Core/Utils/BulletPhysics.cs | 1 - BDArmory.Core/Utils/DebugUtils.cs | 8 +------- BDArmory.Core/Utils/LayerMask.cs | 7 +------ 5 files changed, 20 insertions(+), 26 deletions(-) diff --git a/BDArmory.Core/BDArmory.Core.csproj b/BDArmory.Core/BDArmory.Core.csproj index fab4a2e04..9b683afe4 100644 --- a/BDArmory.Core/BDArmory.Core.csproj +++ b/BDArmory.Core/BDArmory.Core.csproj @@ -63,6 +63,9 @@ ..\..\_LocalDev\KSPRefs\Assembly-CSharp-firstpass.dll + + ..\BDArmory\Distribution\GameData\BDArmory\Plugins\Scale_Redist.dll + ..\..\_LocalDev\KSPRefs\UnityEngine.dll diff --git a/BDArmory.Core/Module/HitpointTracker.cs b/BDArmory.Core/Module/HitpointTracker.cs index f46cdea38..59c527273 100644 --- a/BDArmory.Core/Module/HitpointTracker.cs +++ b/BDArmory.Core/Module/HitpointTracker.cs @@ -1,5 +1,6 @@ using BDArmory.Core.Extension; using UnityEngine; +using TweakScale; namespace BDArmory.Core.Module { @@ -11,6 +12,9 @@ public class HitpointTracker : PartModule UI_ProgressBar(affectSymCounterparts = UI_Scene.None,controlEnabled = false,scene = UI_Scene.All,maxValue = 100000,minValue = 0,requireFullControl = false)] public float Hitpoints; + [KSPField] + bool hasPrefabRun = false; + [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Armor Thickness"), UI_FloatRange(minValue = 1f, maxValue = 500f, stepIncrement = 5f, scene = UI_Scene.All)] public float Armor = 10f; @@ -77,7 +81,7 @@ public override void OnLoad(ConfigNode node) else enabled = false; } - } + } public void SetupPrefab() { @@ -112,11 +116,12 @@ public void SetupPrefab() if (!ArmorSet) overrideArmorSetFromConfig(); previousHitpoints = Hitpoints; + hasPrefabRun = true; } else { - Debug.Log("[BDArmory]: HitpointTracker::OnStart part is null"); + Debug.Log("[BDArmory]: HitpointTracker::OnStart part is null"); } } @@ -136,16 +141,16 @@ public override void OnStart(StartState state) } public void ShipModified(ShipConstruct data) - { + { SetupPrefab(); } - + void OnGUI() { - if (HighLogic.LoadedSceneIsEditor) - { - SetupPrefab(); - } + //if (HighLogic.LoadedSceneIsEditor) + //{ + // SetupPrefab(); + //} } public override void OnUpdate() @@ -171,19 +176,17 @@ public float CalculateTotalHitpoints() if (!part.IsMissile()) { //1. Density of the dry mass of the part. - var density = part.GetDensity(); - + var density = part.GetDensity(); Debug.Log("[BDArmory]: Hitpoint Calc | Density : " + density); //2. Incresing density based on crash tolerance //density += Mathf.Clamp(part.crashTolerance, 10f, 30f); - Debug.Log("[BDArmory]: Hitpoint Calc | Density + CrashTolerance : " + density ); - //12 square meters is the standard size of MK1 fuselage using it as a base var areaCalculation = part.GetArea() / mk1CockpitArea; + //3. final calculations hitpoints = areaCalculation * density * hitpointMultiplier; hitpoints = Mathf.Round(hitpoints/ HpRounding) * HpRounding; diff --git a/BDArmory.Core/Utils/BulletPhysics.cs b/BDArmory.Core/Utils/BulletPhysics.cs index f039a7839..a043edf3c 100644 --- a/BDArmory.Core/Utils/BulletPhysics.cs +++ b/BDArmory.Core/Utils/BulletPhysics.cs @@ -1,5 +1,4 @@ using UnityEngine; -using System.Collections; namespace BDArmory.Core.Utils { diff --git a/BDArmory.Core/Utils/DebugUtils.cs b/BDArmory.Core/Utils/DebugUtils.cs index c1d713102..4aa048c9b 100644 --- a/BDArmory.Core/Utils/DebugUtils.cs +++ b/BDArmory.Core/Utils/DebugUtils.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using UnityEngine; - -namespace BDArmory.Core.Utils +namespace BDArmory.Core.Utils { class DebugUtils { diff --git a/BDArmory.Core/Utils/LayerMask.cs b/BDArmory.Core/Utils/LayerMask.cs index 960ed8471..765fab644 100644 --- a/BDArmory.Core/Utils/LayerMask.cs +++ b/BDArmory.Core/Utils/LayerMask.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace BDArmory.Core.Utils +namespace BDArmory.Core.Utils { class LayerMask { From c43a39cddc21f66169cc89df59bacdbadd96e3d6 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Tue, 17 Jul 2018 21:09:31 -0500 Subject: [PATCH 32/72] Issue #543 Wingcommander min spread --- BDArmory/Modules/ModuleWingCommander.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BDArmory/Modules/ModuleWingCommander.cs b/BDArmory/Modules/ModuleWingCommander.cs index 44a13352f..b649d3fde 100644 --- a/BDArmory/Modules/ModuleWingCommander.cs +++ b/BDArmory/Modules/ModuleWingCommander.cs @@ -364,7 +364,7 @@ void WingmenWindow(int windowID) GUI.HorizontalSlider( new Rect(margin + (buttonWidth/3), buttonEndY + margin + (commandButtonLine*(buttonHeight + buttonGap)), 2*buttonWidth/3, 20), - spread, 20f, 200f, BDArmorySetup.BDGuiSkin.horizontalSlider, BDArmorySetup.BDGuiSkin.horizontalSliderThumb); + spread, 1f, 200f, BDArmorySetup.BDGuiSkin.horizontalSlider, BDArmorySetup.BDGuiSkin.horizontalSliderThumb); commandButtonLine++; GUI.Label( new Rect(margin, buttonEndY + margin + (commandButtonLine*(buttonHeight + buttonGap)), buttonWidth/3, 20), From 7dbf546c81ecc31f4d0e644e803fb3213f115830 Mon Sep 17 00:00:00 2001 From: "U-hades\\dlane" Date: Thu, 19 Jul 2018 23:22:35 -0500 Subject: [PATCH 33/72] wip hp tweakscale logic --- BDArmory.Core/BDArmory.Core.csproj | 3 -- BDArmory.Core/Module/HitpointTracker.cs | 46 +++++++++++++++++++------ 2 files changed, 36 insertions(+), 13 deletions(-) diff --git a/BDArmory.Core/BDArmory.Core.csproj b/BDArmory.Core/BDArmory.Core.csproj index 9b683afe4..fab4a2e04 100644 --- a/BDArmory.Core/BDArmory.Core.csproj +++ b/BDArmory.Core/BDArmory.Core.csproj @@ -63,9 +63,6 @@ ..\..\_LocalDev\KSPRefs\Assembly-CSharp-firstpass.dll - - ..\BDArmory\Distribution\GameData\BDArmory\Plugins\Scale_Redist.dll - ..\..\_LocalDev\KSPRefs\UnityEngine.dll diff --git a/BDArmory.Core/Module/HitpointTracker.cs b/BDArmory.Core/Module/HitpointTracker.cs index 59c527273..dfc2849c3 100644 --- a/BDArmory.Core/Module/HitpointTracker.cs +++ b/BDArmory.Core/Module/HitpointTracker.cs @@ -1,6 +1,5 @@ using BDArmory.Core.Extension; using UnityEngine; -using TweakScale; namespace BDArmory.Core.Module { @@ -48,15 +47,15 @@ public class HitpointTracker : PartModule private const float mk1CockpitArea = 7.292964f; private const int HpRounding = 250; - - + + public void Setup() { if (_setupRun) { return; } - _prefabPart = part.partInfo.partPrefab; + //_prefabPart = part.partInfo.partPrefab; _setupRun = true; } @@ -81,15 +80,18 @@ public override void OnLoad(ConfigNode node) else enabled = false; } + } public void SetupPrefab() { + _prefabPart = part.partInfo.partPrefab; + if (part != null) { var maxHitPoints_ = CalculateTotalHitpoints(); - if (previousHitpoints == maxHitPoints_) return; + //if (previousHitpoints == maxHitPoints_) return; //Add Hitpoints UI_ProgressBar damageFieldFlight = (UI_ProgressBar)Fields["Hitpoints"].uiControlFlight; @@ -123,7 +125,7 @@ public void SetupPrefab() Debug.Log("[BDArmory]: HitpointTracker::OnStart part is null"); } - } + } public override void OnStart(StartState state) { @@ -137,7 +139,13 @@ public override void OnStart(StartState state) //Once started the max value of the field should be the initial one armorField.maxValue = Armor; part.RefreshAssociatedWindows(); - } + } + GameEvents.onEditorShipModified.Add(ShipModified); + } + + private void OnDestroy() + { + GameEvents.onEditorShipModified.Remove(ShipModified); } public void ShipModified(ShipConstruct data) @@ -164,11 +172,25 @@ public override void OnUpdate() { _firstSetup = false; SetupPrefab(); - } - } + } + + if (HighLogic.LoadedSceneIsEditor) + { + //if (_ScalingFactor.index >= 0f) + //{ + // var changed = _ScalingFactor.index != (isFreeScale ? tweakScale : ScaleFactors[tweakName]); + // if (changed) // user has changed the scale tweakable + // { + // //OnTweakScaleChanged(); + // } + //} + } + } #region Hitpoints Functions + + public float CalculateTotalHitpoints() { float hitpoints; @@ -178,7 +200,7 @@ public float CalculateTotalHitpoints() //1. Density of the dry mass of the part. var density = part.GetDensity(); - Debug.Log("[BDArmory]: Hitpoint Calc | Density : " + density); + Debug.Log("[BDArmory]: Hitpoint Calc | Density : " + Mathf.Round(density)); //2. Incresing density based on crash tolerance //density += Mathf.Clamp(part.crashTolerance, 10f, 30f); @@ -187,6 +209,10 @@ public float CalculateTotalHitpoints() var areaCalculation = part.GetArea() / mk1CockpitArea; + Debug.Log("[BDArmory]: Hitpoint Calc | areaCalc : " + Mathf.Round(areaCalculation)); + Debug.Log("[BDArmory]: Hitpoint Calc | ScaleFactor : "); + + //3. final calculations hitpoints = areaCalculation * density * hitpointMultiplier; hitpoints = Mathf.Round(hitpoints/ HpRounding) * HpRounding; From 84a7040fcb3146eba95771e28105708d24e8f935 Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Tue, 24 Jul 2018 00:19:00 +0200 Subject: [PATCH 34/72] wip HP overhaul --- BDArmory.Core/Extension/PartExtensions.cs | 23 +++---- BDArmory.Core/Module/HitpointTracker.cs | 74 ++++++++++++----------- 2 files changed, 47 insertions(+), 50 deletions(-) diff --git a/BDArmory.Core/Extension/PartExtensions.cs b/BDArmory.Core/Extension/PartExtensions.cs index 05da50bd0..804cff9e4 100644 --- a/BDArmory.Core/Extension/PartExtensions.cs +++ b/BDArmory.Core/Extension/PartExtensions.cs @@ -276,30 +276,23 @@ public static bool IsMissile(this Part part) public static float GetArea(this Part part, bool isprefab = false, Part prefab = null) { - float sfcAreaCalc = 2f * (part.prefabSize.x * part.prefabSize.y) + 2f * (part.prefabSize.y * part.prefabSize.z) + 2f * (part.prefabSize.x * part.prefabSize.z); - - if (sfcAreaCalc == 0) - { - sfcAreaCalc = 2f * (part.HighlightRenderer[0].bounds.size.x * part.HighlightRenderer[0].bounds.size.y) + 2f * (part.HighlightRenderer[0].bounds.size.y * part.HighlightRenderer[0].bounds.size.z) + 2f * (part.HighlightRenderer[0].bounds.size.x * part.HighlightRenderer[0].bounds.size.z); - } - - Debug.Log("Part name = " + part.name + "Area ="+ sfcAreaCalc); + var size = part.GetComponentInChildren().mesh.bounds.size; + float sfcAreaCalc = 2f * (size.x * size.y) + 2f * (size.y * size.z) + 2f * (size.x * size.z); + return sfcAreaCalc; } public static float GetAverageBoundSize(this Part part) { - return (part.prefabSize.x + part.prefabSize.y + part.prefabSize.z) / 3f; + var size = part.GetComponentInChildren().mesh.bounds.size; + return (size.x + size.y + size.z) / 3f; } public static float GetVolume(this Part part) { - var volume = part.prefabSize.x * part.prefabSize.y * part.prefabSize.z; - if (volume == 0) - { - volume = part.HighlightRenderer[0].bounds.size.x * part.HighlightRenderer[0].bounds.size.y * part.HighlightRenderer[0].bounds.size.z; - } - Debug.Log("Part name = " + part.name + "volume =" + volume); + var size = part.GetComponentInChildren().mesh.bounds.size; + var volume = size.x * size.y * size.z; + return volume; } diff --git a/BDArmory.Core/Module/HitpointTracker.cs b/BDArmory.Core/Module/HitpointTracker.cs index dfc2849c3..aa141a20b 100644 --- a/BDArmory.Core/Module/HitpointTracker.cs +++ b/BDArmory.Core/Module/HitpointTracker.cs @@ -8,7 +8,7 @@ public class HitpointTracker : PartModule #region KSP Fields [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Hitpoints"), - UI_ProgressBar(affectSymCounterparts = UI_Scene.None,controlEnabled = false,scene = UI_Scene.All,maxValue = 100000,minValue = 0,requireFullControl = false)] + UI_ProgressBar(affectSymCounterparts = UI_Scene.None, controlEnabled = false, scene = UI_Scene.All, maxValue = 100000, minValue = 0, requireFullControl = false)] public float Hitpoints; [KSPField] @@ -47,8 +47,8 @@ public class HitpointTracker : PartModule private const float mk1CockpitArea = 7.292964f; private const int HpRounding = 250; - - + + public void Setup() { if (_setupRun) @@ -91,7 +91,7 @@ public void SetupPrefab() { var maxHitPoints_ = CalculateTotalHitpoints(); - //if (previousHitpoints == maxHitPoints_) return; + if (previousHitpoints == maxHitPoints_) return; //Add Hitpoints UI_ProgressBar damageFieldFlight = (UI_ProgressBar)Fields["Hitpoints"].uiControlFlight; @@ -115,17 +115,17 @@ public void SetupPrefab() part.RefreshAssociatedWindows(); - if (!ArmorSet) overrideArmorSetFromConfig(); - - previousHitpoints = Hitpoints; + if (!ArmorSet) overrideArmorSetFromConfig(); + + previousHitpoints = maxHitPoints_; hasPrefabRun = true; } else { - Debug.Log("[BDArmory]: HitpointTracker::OnStart part is null"); + Debug.Log("[BDArmory]: HitpointTracker::OnStart part is null"); } - } + } public override void OnStart(StartState state) { @@ -149,10 +149,10 @@ private void OnDestroy() } public void ShipModified(ShipConstruct data) - { + { SetupPrefab(); } - + void OnGUI() { //if (HighLogic.LoadedSceneIsEditor) @@ -161,8 +161,8 @@ void OnGUI() //} } - public override void OnUpdate() - { + public void Update() + { if (!HighLogic.LoadedSceneIsFlight || !FlightGlobals.ready || Hitpoints == 0f) { return; @@ -172,7 +172,7 @@ public override void OnUpdate() { _firstSetup = false; SetupPrefab(); - } + } if (HighLogic.LoadedSceneIsEditor) { @@ -189,7 +189,7 @@ public override void OnUpdate() #region Hitpoints Functions - + public float CalculateTotalHitpoints() { @@ -198,26 +198,30 @@ public float CalculateTotalHitpoints() if (!part.IsMissile()) { //1. Density of the dry mass of the part. - var density = part.GetDensity(); + var density = part.GetDensity(); - Debug.Log("[BDArmory]: Hitpoint Calc | Density : " + Mathf.Round(density)); + Debug.Log("[BDArmory]: Hitpoint Calc | Mesh : " + part.GetComponentInChildren().mesh.bounds.size); + var tweakScaleModule = part.Modules["TweakScale"]; - //2. Incresing density based on crash tolerance - //density += Mathf.Clamp(part.crashTolerance, 10f, 30f); + if (tweakScaleModule != null) + { + Debug.Log("[BDArmory]: Hitpoint Calc | scale : " + tweakScaleModule.Fields["currentScale"].GetValue(tweakScaleModule) / tweakScaleModule.Fields["defaultScale"].GetValue(tweakScaleModule)); + } - //12 square meters is the standard size of MK1 fuselage using it as a base + Debug.Log("[BDArmory]: Hitpoint Calc | Density : " + Mathf.Round(density)); + + //Structural mass is the area in m2 * 2 cm of thickness * material density - var areaCalculation = part.GetArea() / mk1CockpitArea; + var structuralMass = part.GetArea() * 0.02f * density; - Debug.Log("[BDArmory]: Hitpoint Calc | areaCalc : " + Mathf.Round(areaCalculation)); - Debug.Log("[BDArmory]: Hitpoint Calc | ScaleFactor : "); + Debug.Log("[BDArmory]: Hitpoint Calc | structuralMass : " + Mathf.Round(structuralMass)); //3. final calculations - hitpoints = areaCalculation * density * hitpointMultiplier; - hitpoints = Mathf.Round(hitpoints/ HpRounding) * HpRounding; + hitpoints = structuralMass * 10 * hitpointMultiplier; + hitpoints = Mathf.Round(hitpoints / HpRounding) * HpRounding; - if (hitpoints <= 0) hitpoints = HpRounding; + if (hitpoints <= 0) hitpoints = HpRounding; } else { @@ -230,16 +234,16 @@ public float CalculateTotalHitpoints() { hitpoints = maxHitPoints; } - + if (hitpoints <= 0) hitpoints = HpRounding; return hitpoints; } public void DestroyPart() { - if(part.mass <= 2f) part.explosionPotential *= 0.85f; + if (part.mass <= 2f) part.explosionPotential *= 0.85f; - PartExploderSystem.AddPartToExplode(part); + PartExploderSystem.AddPartToExplode(part); } public float GetMaxArmor() @@ -250,7 +254,7 @@ public float GetMaxArmor() public float GetMaxHitpoints() { - UI_ProgressBar hitpointField = (UI_ProgressBar) Fields["Hitpoints"].uiControlEditor; + UI_ProgressBar hitpointField = (UI_ProgressBar)Fields["Hitpoints"].uiControlEditor; return hitpointField.maxValue; } @@ -263,7 +267,7 @@ public void SetDamage(float partdamage) { Hitpoints -= partdamage; - if(Hitpoints <= 0) + if (Hitpoints <= 0) { DestroyPart(); } @@ -290,7 +294,7 @@ public void AddDamageToKerbal(KerbalEVA kerbal, float damage) if (Hitpoints <= 0) { // oh the humanity! - PartExploderSystem.AddPartToExplode(kerbal.part); + PartExploderSystem.AddPartToExplode(kerbal.part); } } @@ -305,14 +309,14 @@ public void ReduceArmor(float massToReduce) public void overrideArmorSetFromConfig(float thickness = 0) { - ArmorSet = true; + ArmorSet = true; if (ArmorThickness != 0) { Armor = ArmorThickness; - } + } } #endregion } -} +} \ No newline at end of file From 0c59df3a92cd2da9a9a542f78239b962f0211669 Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Tue, 24 Jul 2018 18:13:52 +0200 Subject: [PATCH 35/72] WIP hitpoints overhaul - almost there --- BDArmory.Core/Extension/PartExtensions.cs | 20 ++++++++-- BDArmory.Core/Module/HitpointTracker.cs | 47 +++++++---------------- 2 files changed, 29 insertions(+), 38 deletions(-) diff --git a/BDArmory.Core/Extension/PartExtensions.cs b/BDArmory.Core/Extension/PartExtensions.cs index 804cff9e4..8b218a09b 100644 --- a/BDArmory.Core/Extension/PartExtensions.cs +++ b/BDArmory.Core/Extension/PartExtensions.cs @@ -276,7 +276,7 @@ public static bool IsMissile(this Part part) public static float GetArea(this Part part, bool isprefab = false, Part prefab = null) { - var size = part.GetComponentInChildren().mesh.bounds.size; + var size = part.GetSize(); float sfcAreaCalc = 2f * (size.x * size.y) + 2f * (size.y * size.z) + 2f * (size.x * size.z); return sfcAreaCalc; @@ -284,18 +284,30 @@ public static float GetArea(this Part part, bool isprefab = false, Part prefab = public static float GetAverageBoundSize(this Part part) { - var size = part.GetComponentInChildren().mesh.bounds.size; + var size = part.GetSize(); return (size.x + size.y + size.z) / 3f; } public static float GetVolume(this Part part) { - var size = part.GetComponentInChildren().mesh.bounds.size; + var size = part.GetSize(); var volume = size.x * size.y * size.z; - return volume; } + public static Vector3 GetSize(this Part part) + { + var tweakScaleModule = part.Modules["TweakScale"]; + + float scaleMultiplier = 1f; + if (tweakScaleModule != null) + { + scaleMultiplier = tweakScaleModule.Fields["currentScale"].GetValue(tweakScaleModule) / + tweakScaleModule.Fields["defaultScale"].GetValue(tweakScaleModule); + } + return part.GetComponentInChildren().mesh.bounds.size * scaleMultiplier; + } + public static float GetDensity (this Part part) { return (part.mass * 1000) / part.GetVolume(); diff --git a/BDArmory.Core/Module/HitpointTracker.cs b/BDArmory.Core/Module/HitpointTracker.cs index aa141a20b..293bf4756 100644 --- a/BDArmory.Core/Module/HitpointTracker.cs +++ b/BDArmory.Core/Module/HitpointTracker.cs @@ -41,11 +41,9 @@ public class HitpointTracker : PartModule private readonly float hitpointMultiplier = BDArmorySettings.HITPOINT_MULTIPLIER; private float previousHitpoints; - private Part _prefabPart; private bool _setupRun = false; private bool _firstSetup = true; - - private const float mk1CockpitArea = 7.292964f; + private bool _updateHitpoints = false; private const int HpRounding = 250; @@ -68,8 +66,7 @@ public override void OnLoad(ConfigNode node) if (part.partInfo == null) { // Loading of the prefab from the part config - _prefabPart = part; - SetupPrefab(); + _updateHitpoints = true; } else @@ -85,8 +82,6 @@ public override void OnLoad(ConfigNode node) public void SetupPrefab() { - _prefabPart = part.partInfo.partPrefab; - if (part != null) { var maxHitPoints_ = CalculateTotalHitpoints(); @@ -112,7 +107,6 @@ public void SetupPrefab() UI_FloatRange armorFieldEditor = (UI_FloatRange)Fields["Armor"].uiControlEditor; armorFieldEditor.maxValue = 500f; armorFieldEditor.minValue = 10f; - part.RefreshAssociatedWindows(); if (!ArmorSet) overrideArmorSetFromConfig(); @@ -131,7 +125,7 @@ public override void OnStart(StartState state) { isEnabled = true; - if (part != null) SetupPrefab(); + if (part != null) _updateHitpoints = true; if (HighLogic.LoadedSceneIsFlight) { @@ -150,15 +144,16 @@ private void OnDestroy() public void ShipModified(ShipConstruct data) { - SetupPrefab(); + _updateHitpoints = true; } void OnGUI() { - //if (HighLogic.LoadedSceneIsEditor) - //{ - // SetupPrefab(); - //} + if (_updateHitpoints) + { + SetupPrefab(); + _updateHitpoints = false; + } } public void Update() @@ -171,19 +166,7 @@ public void Update() if (part != null && _firstSetup) { _firstSetup = false; - SetupPrefab(); - } - - if (HighLogic.LoadedSceneIsEditor) - { - //if (_ScalingFactor.index >= 0f) - //{ - // var changed = _ScalingFactor.index != (isFreeScale ? tweakScale : ScaleFactors[tweakName]); - // if (changed) // user has changed the scale tweakable - // { - // //OnTweakScaleChanged(); - // } - //} + _updateHitpoints = true; } } @@ -200,13 +183,9 @@ public float CalculateTotalHitpoints() //1. Density of the dry mass of the part. var density = part.GetDensity(); - Debug.Log("[BDArmory]: Hitpoint Calc | Mesh : " + part.GetComponentInChildren().mesh.bounds.size); - var tweakScaleModule = part.Modules["TweakScale"]; - - if (tweakScaleModule != null) - { - Debug.Log("[BDArmory]: Hitpoint Calc | scale : " + tweakScaleModule.Fields["currentScale"].GetValue(tweakScaleModule) / tweakScaleModule.Fields["defaultScale"].GetValue(tweakScaleModule)); - } + Debug.Log("[BDArmory]: Hitpoint Calc | Size : " + part.GetSize()); + Debug.Log("[BDArmory]: Hitpoint Calc | mass : " + part.mass); + Debug.Log("[BDArmory]: Hitpoint Calc | volume : " + part.GetVolume()); Debug.Log("[BDArmory]: Hitpoint Calc | Density : " + Mathf.Round(density)); From f52bed66444ce508aa2e89477d9da63853c1eb30 Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Wed, 25 Jul 2018 21:19:30 +0200 Subject: [PATCH 36/72] WIP HP overhaul --- BDArmory.Core/Extension/PartExtensions.cs | 12 ++-- BDArmory.Core/Module/HitpointTracker.cs | 70 ++++++++--------------- 2 files changed, 33 insertions(+), 49 deletions(-) diff --git a/BDArmory.Core/Extension/PartExtensions.cs b/BDArmory.Core/Extension/PartExtensions.cs index 8b218a09b..d2d345e9a 100644 --- a/BDArmory.Core/Extension/PartExtensions.cs +++ b/BDArmory.Core/Extension/PartExtensions.cs @@ -308,10 +308,14 @@ public static Vector3 GetSize(this Part part) return part.GetComponentInChildren().mesh.bounds.size * scaleMultiplier; } - public static float GetDensity (this Part part) - { - return (part.mass * 1000) / part.GetVolume(); - } + //public static float GetDensity(this Part part) + //{ + // float structuralMassPercentage = part.mass / (part.mass + part.resourceMass); + + // float structuralVolume = part.GetVolume() * structuralMassPercentage; + + // return ((part.mass * 1000) / structuralVolume); + //} public static bool IsAero(this Part part) { diff --git a/BDArmory.Core/Module/HitpointTracker.cs b/BDArmory.Core/Module/HitpointTracker.cs index 293bf4756..ec62241f8 100644 --- a/BDArmory.Core/Module/HitpointTracker.cs +++ b/BDArmory.Core/Module/HitpointTracker.cs @@ -41,22 +41,12 @@ public class HitpointTracker : PartModule private readonly float hitpointMultiplier = BDArmorySettings.HITPOINT_MULTIPLIER; private float previousHitpoints; - private bool _setupRun = false; private bool _firstSetup = true; private bool _updateHitpoints = false; - private const int HpRounding = 250; + private bool _forceUpdateHitpointsUI = false; + private const int HpRounding = 100; - public void Setup() - { - if (_setupRun) - { - return; - } - //_prefabPart = part.partInfo.partPrefab; - _setupRun = true; - } - public override void OnLoad(ConfigNode node) { base.OnLoad(node); @@ -73,7 +63,9 @@ public override void OnLoad(ConfigNode node) { // Loading of the part from a saved craft if (HighLogic.LoadedSceneIsEditor) - Setup(); + { + _updateHitpoints = true; + } else enabled = false; } @@ -86,7 +78,7 @@ public void SetupPrefab() { var maxHitPoints_ = CalculateTotalHitpoints(); - if (previousHitpoints == maxHitPoints_) return; + if (!_forceUpdateHitpointsUI && previousHitpoints == maxHitPoints_) return; //Add Hitpoints UI_ProgressBar damageFieldFlight = (UI_ProgressBar)Fields["Hitpoints"].uiControlFlight; @@ -137,6 +129,8 @@ public override void OnStart(StartState state) GameEvents.onEditorShipModified.Add(ShipModified); } + + private void OnDestroy() { GameEvents.onEditorShipModified.Remove(ShipModified); @@ -146,58 +140,44 @@ public void ShipModified(ShipConstruct data) { _updateHitpoints = true; } - - void OnGUI() + public override void OnUpdate() { - if (_updateHitpoints) - { - SetupPrefab(); - _updateHitpoints = false; - } + + RefreshHitPoints(); } public void Update() { - if (!HighLogic.LoadedSceneIsFlight || !FlightGlobals.ready || Hitpoints == 0f) - { - return; - } - if (part != null && _firstSetup) + RefreshHitPoints(); + } + + private void RefreshHitPoints() + { + + if (_updateHitpoints) { - _firstSetup = false; - _updateHitpoints = true; + SetupPrefab(); + _updateHitpoints = false; + _forceUpdateHitpointsUI = false; } } #region Hitpoints Functions - - public float CalculateTotalHitpoints() { float hitpoints; if (!part.IsMissile()) { - //1. Density of the dry mass of the part. - var density = part.GetDensity(); - - Debug.Log("[BDArmory]: Hitpoint Calc | Size : " + part.GetSize()); - Debug.Log("[BDArmory]: Hitpoint Calc | mass : " + part.mass); - Debug.Log("[BDArmory]: Hitpoint Calc | volume : " + part.GetVolume()); - - Debug.Log("[BDArmory]: Hitpoint Calc | Density : " + Mathf.Round(density)); - - //Structural mass is the area in m2 * 2 cm of thickness * material density - - var structuralMass = part.GetArea() * 0.02f * density; - - Debug.Log("[BDArmory]: Hitpoint Calc | structuralMass : " + Mathf.Round(structuralMass)); + var density = 5325; //aluminum steel 50/50 alloy (density in kg/m3) + //Structural mass is the area in m2 * imaginary thickness for balance * material density + var structuralMass = part.GetArea() * 0.01f * density; //3. final calculations - hitpoints = structuralMass * 10 * hitpointMultiplier; + hitpoints = 0.25f* structuralMass * hitpointMultiplier; hitpoints = Mathf.Round(hitpoints / HpRounding) * HpRounding; if (hitpoints <= 0) hitpoints = HpRounding; From d536bc4abaf752e0cb82510bc14bca96cb05be92 Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Fri, 27 Jul 2018 23:58:27 +0200 Subject: [PATCH 37/72] HP overhaul --- BDArmory.Core/Extension/PartExtensions.cs | 18 ++++++++---------- BDArmory.Core/Module/HitpointTracker.cs | 20 ++++++++++++++------ 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/BDArmory.Core/Extension/PartExtensions.cs b/BDArmory.Core/Extension/PartExtensions.cs index d2d345e9a..ba4c6e1be 100644 --- a/BDArmory.Core/Extension/PartExtensions.cs +++ b/BDArmory.Core/Extension/PartExtensions.cs @@ -298,24 +298,22 @@ public static float GetVolume(this Part part) public static Vector3 GetSize(this Part part) { var tweakScaleModule = part.Modules["TweakScale"]; - + part.GetComponentInChildren().mesh.RecalculateBounds(); + var size = part.GetComponentInChildren().mesh.bounds.size; float scaleMultiplier = 1f; if (tweakScaleModule != null) { scaleMultiplier = tweakScaleModule.Fields["currentScale"].GetValue(tweakScaleModule) / tweakScaleModule.Fields["defaultScale"].GetValue(tweakScaleModule); } - return part.GetComponentInChildren().mesh.bounds.size * scaleMultiplier; + + return size * scaleMultiplier; } - //public static float GetDensity(this Part part) - //{ - // float structuralMassPercentage = part.mass / (part.mass + part.resourceMass); - - // float structuralVolume = part.GetVolume() * structuralMassPercentage; - - // return ((part.mass * 1000) / structuralVolume); - //} + public static float GetDensity(this Part part) + { + return (part.mass * 1000f) / (part.GetVolume()*0.476f); + } public static bool IsAero(this Part part) { diff --git a/BDArmory.Core/Module/HitpointTracker.cs b/BDArmory.Core/Module/HitpointTracker.cs index ec62241f8..63dede1f2 100644 --- a/BDArmory.Core/Module/HitpointTracker.cs +++ b/BDArmory.Core/Module/HitpointTracker.cs @@ -133,7 +133,7 @@ public override void OnStart(StartState state) private void OnDestroy() { - GameEvents.onEditorShipModified.Remove(ShipModified); + GameEvents.onEditorShipModified.Remove(ShipModified); } public void ShipModified(ShipConstruct data) @@ -171,13 +171,21 @@ public float CalculateTotalHitpoints() if (!part.IsMissile()) { - var density = 5325; //aluminum steel 50/50 alloy (density in kg/m3) - - //Structural mass is the area in m2 * imaginary thickness for balance * material density - var structuralMass = part.GetArea() * 0.01f * density; + var averageSize = part.GetAverageBoundSize(); + var sphereRadius = averageSize * 0.5f; + var sphereSurface = 4 * Mathf.PI * sphereRadius * sphereRadius; + var structuralVolume = sphereSurface * 0.1f; + + var density = (part.mass * 1000f) / structuralVolume; + density = Mathf.Clamp(density, 1000, 10000); + //Debug.Log("[BDArmory]: Hitpoint Calc" + part.name + " | structuralVolume : " + structuralVolume); + //Debug.Log("[BDArmory]: Hitpoint Calc"+part.name+" | Density : " + density); + + var structuralMass = density * structuralVolume; + //Debug.Log("[BDArmory]: Hitpoint Calc" + part.name + " | structuralMass : " + structuralMass); //3. final calculations - hitpoints = 0.25f* structuralMass * hitpointMultiplier; + hitpoints = structuralMass * hitpointMultiplier *0.33f; hitpoints = Mathf.Round(hitpoints / HpRounding) * HpRounding; if (hitpoints <= 0) hitpoints = HpRounding; From a91c7258db145d5b154181ee15e33858c5b3e7b6 Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Sun, 29 Jul 2018 00:30:42 +0200 Subject: [PATCH 38/72] patching B9 PWings --- BDArmory.Core/Extension/PartExtensions.cs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/BDArmory.Core/Extension/PartExtensions.cs b/BDArmory.Core/Extension/PartExtensions.cs index ba4c6e1be..5094cf07d 100644 --- a/BDArmory.Core/Extension/PartExtensions.cs +++ b/BDArmory.Core/Extension/PartExtensions.cs @@ -285,6 +285,9 @@ public static float GetArea(this Part part, bool isprefab = false, Part prefab = public static float GetAverageBoundSize(this Part part) { var size = part.GetSize(); + + + return (size.x + size.y + size.z) / 3f; } @@ -298,21 +301,22 @@ public static float GetVolume(this Part part) public static Vector3 GetSize(this Part part) { var tweakScaleModule = part.Modules["TweakScale"]; - part.GetComponentInChildren().mesh.RecalculateBounds(); + var size = part.GetComponentInChildren().mesh.bounds.size; + + if (part.name.Contains("B9.Aero.Wing.Procedural")) + { + size = size * 0.1f; + } + float scaleMultiplier = 1f; if (tweakScaleModule != null) { scaleMultiplier = tweakScaleModule.Fields["currentScale"].GetValue(tweakScaleModule) / tweakScaleModule.Fields["defaultScale"].GetValue(tweakScaleModule); } - - return size * scaleMultiplier; - } - public static float GetDensity(this Part part) - { - return (part.mass * 1000f) / (part.GetVolume()*0.476f); + return size * scaleMultiplier; } public static bool IsAero(this Part part) From 22618490605cf4759cad3e1f427e831373b312d8 Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Mon, 30 Jul 2018 19:22:31 +0200 Subject: [PATCH 39/72] Including new smoke model and HighExplosive resource --- BDArmory/BDArmory.csproj | 1 + .../BDArmory/Models/CMSmoke/cmSmokeModel.mu | Bin 634 -> 607 bytes .../BDArmory/Models/CMSmoke/smokeCm.png | Bin 18656 -> 18973 bytes .../BDArmory/Resources/HighExplosive.cfg | 14 ++++++++++++++ 4 files changed, 15 insertions(+) create mode 100644 BDArmory/Distribution/GameData/BDArmory/Resources/HighExplosive.cfg diff --git a/BDArmory/BDArmory.csproj b/BDArmory/BDArmory.csproj index 9f6f44900..c4a0e6ffd 100644 --- a/BDArmory/BDArmory.csproj +++ b/BDArmory/BDArmory.csproj @@ -384,6 +384,7 @@ + diff --git a/BDArmory/Distribution/GameData/BDArmory/Models/CMSmoke/cmSmokeModel.mu b/BDArmory/Distribution/GameData/BDArmory/Models/CMSmoke/cmSmokeModel.mu index dd7d1e9b60aac859f3a97fcf28889abc45b4c663..a1d178d1809fe8af29f3271f3e45996049465199 100644 GIT binary patch literal 607 zcmeyb#mK>@uuOu-&Jv9ZU zkhvh$5XA03^mQLh3_&9_gABqjKpv=)ksYiYRVA{u$ZW>5XU^CH)jL82KR7aiOaL2z zoj7~O#|{aD^fCbXwv3E6Hhb*8c5edX$b2Skbrk+_Z*lua4;A5f-uvfv$j+Mg zemRhj9n6|3iBk?@214Hg2M`R^QELRE=uEixOV80aPk2L=WOM+SxkP7zE%7Bj>M>?FeAvuAv4 zL25uWBjd8As`fCvX>PtsuvqQGlFG;}e$YEuB82+&Q7|#)gDD52_pdXM}RFavTlUl6rm{X9EsNj^7nwOHA z!U9yu6(5qBSK^$XlV1enF(mYI+QaaL^Zxc6@xF5$~B-=9ZX} y3JKW;dy)81pxH&`i6yB;Zu#kMiOD7TMX+G!0crxdmAe>}zMOOQ3i8rH<^TXedvF^7 diff --git a/BDArmory/Distribution/GameData/BDArmory/Models/CMSmoke/smokeCm.png b/BDArmory/Distribution/GameData/BDArmory/Models/CMSmoke/smokeCm.png index b32789d342ee02034634110a948ce15f81d6f342..b72274d1a1f1f1edab0055470d0bf0c04480c44c 100644 GIT binary patch literal 18973 zcmV)2K+M01P)h{uBdozV7$ssXRE{1aBhgl@u!Spzc*!nORv`*Y4~c>{Z`Hv%j|=V4aQ6R=~TycYVdb zyR%!}yLYcTIXzhkPtWc5Zl^Qs&;Ib)ihn#FulUpR(Z?TEcRssQ?QHE-ckkbg;G=`1 zs+v{R-A8w;qrIcB^;iAORaLuNyB8i@gZ^N}znCl<|BYKWs^5I_o62&tj?Lj_HJ*$k z%!J*3w@I(#-h+G9urqAJp4ILq!3!L#rN1EY_tD=y41CW3-#wbXQj5N4fLB7-cQ5hx z4DbS)b~_g+(mn6bLk~#%1=+vx(HE`z#)JAjfNui>E&cUv6#tzmvr}4wj> zpnCtk_cso%AFK?M!;N9%zxU^R)8n(_$?rb-T{1}3>-JX4TP#+*E3owXz3{Kk^;Z(T zWzRY?-g0$sxA^U??N|`{;DZmWXyl(KlP3*v^#A?e|9!5^?C3u^IdLhcSw;HifBxtB zFMjb0qc(r}i(gjL$u#oc`|@6O_|9Q991Ytz>mUE&xc|XVKbXP<$!RrJEul8SQ0c)= z$zhP((e@kmS2gX%{8cM{3zdn;4#baTvJXG_PzKn%{?7FzcvQK2Wp@L|c6j*n_{rl5 z)&bwCVITeMqg)y^U3GYP*kPsdT;dlqIQ&85?hgh7>$8ktfbHFF877&bs^&37l&nOY zM^s9Y#myTxWsvln?%5)vDdo*MzAFsSrT2Frmc$rA{7pXBl1F=cds{7ZZ83i9Z5ZIu zqer>c91QUA{=;N|$i`B!{&T(vA8uU?0WiYo@cLm8?8CqLP|8mK+sgW`#*XAsvm(@M|=B9fauL8+U!>$A#`IVqtU3nct3_=+9Lbxzl{`U5HSL2%E{`O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S(DH@e;&n5T_1*kwb>1$(c;Pr`=dK_L6(+mW+yWQ!E>w z`p5BjoYBtn&gFPreUBJvjQbqZj1%pX`PFITdU$zG`mY`IrU4Mcz;fv_zv_8jY#fRp zab#$0fM5p*1Vv+PlL#|@aT}{#0uIOG-M!asLN$pONt%C_bb>5D?k*AxO%TLzP_0NL z2xJ5%%0O9*V=PsjXU!>av&<{*7`!fh?Ff}#G%ptgFT=R0?YZr_jQMJ=Hw^%55k1xM z&zA=C!>u32>0pWMaz$>A zsTn)$h>JpJNEjI(%ukQX76kr=P%u8j%HJ5ux0kgoyRNH=tHm9M#>guHxzzg?(nQ2p z{PRr!Aghu<2*Ngi5bsC=8`0tukFqfrL5RHn#yo;mG7uASoCkC0)OStzRpF(Nf6E@r zPi?efDvD3!a~a{PPsQx0j|)WsfbxT&7TdS31YRbuj&wHX=L?hA%b2g@a%K~Bdfm1D z7gge$1VENuGAbK{uV8TR9W&<#8U5wURz>7lqqhbDs_*NXOo+=4GxKUoHeW0GbNO1i zt_6W>70)yFJ~mwHD9pv1)4JOK8*&8QGVfFxd0+6)@K?3J4FF`_qKEmSK9C}=n&M>G z9NoQ+&rz=chJ?pN!&7OibPBJ^%J`*S_8Sj#=DkGuk>+AN-Z(#a#VDJSz_qXO!=a{r3VulYrMU zhX^gVXH!OHkFObD=Fm*rbT{+A*1fjrsqSly`i2KUt_{4_^QB6@Hiy5P=XU`BR~lc< zxg{&Rfwk5j@zBt7ckfENH|P-{Fh6_$*ELQLs|zT&jA4b5B0Qh0>`I)W!5dhC5%?~5sM*#dV`25UP{s@3) zlIDjI@FM_z7<_(aD}MyQGfDHq2>1~IKMX!Uvz7l30^+yU-oj4w00000NkvXXu0mjf DrNzsv diff --git a/BDArmory/Distribution/GameData/BDArmory/Resources/HighExplosive.cfg b/BDArmory/Distribution/GameData/BDArmory/Resources/HighExplosive.cfg new file mode 100644 index 000000000..35a519d43 --- /dev/null +++ b/BDArmory/Distribution/GameData/BDArmory/Resources/HighExplosive.cfg @@ -0,0 +1,14 @@ +RESOURCE_DEFINITION +{ + name = HighExplosive + displayName = High Explosive + abbreviation = HE + density = 0.00025 + unitCost = 1.5 + hsp = 920 + isTweakable = true + isVisible = true + flowMode = ALL_VESSEL + transfer = PUMP + volume = 1 +} \ No newline at end of file From 570e018be2879aec33ad075318817dd9af2dcaae Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Sat, 4 Aug 2018 20:01:26 +0200 Subject: [PATCH 40/72] Min speed guidance and time between stages --- BDArmory/Modules/BDModularGuidance.cs | 52 ++++++++++++++++++++++++--- 1 file changed, 48 insertions(+), 4 deletions(-) diff --git a/BDArmory/Modules/BDModularGuidance.cs b/BDArmory/Modules/BDModularGuidance.cs index e3be08c79..9cd212169 100644 --- a/BDArmory/Modules/BDModularGuidance.cs +++ b/BDArmory/Modules/BDModularGuidance.cs @@ -55,7 +55,7 @@ public class BDModularGuidance : MissileBase [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Steer Limiter"), UI_FloatRange(minValue = .1f, maxValue = 1f, stepIncrement = .05f, scene = UI_Scene.Editor, affectSymCounterparts = UI_Scene.All)] public float MaxSteer = 1; - [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Stages Number"), UI_FloatRange(minValue = 1f, maxValue = 5f, stepIncrement = 1f, scene = UI_Scene.Editor, affectSymCounterparts = UI_Scene.All)] + [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Stages Number"), UI_FloatRange(minValue = 1f, maxValue = 9f, stepIncrement = 1f, scene = UI_Scene.Editor, affectSymCounterparts = UI_Scene.All)] public float StagesNumber = 1; [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Stage to Trigger On Proximity"), UI_FloatRange(minValue = 0f, maxValue = 6f, stepIncrement = 1f, scene = UI_Scene.Editor, affectSymCounterparts = UI_Scene.All)] @@ -71,11 +71,20 @@ public class BDModularGuidance : MissileBase public bool RollCorrection = false; + [KSPField(isPersistant = true, guiActive = false, guiActiveEditor = true, guiName = "Time Between Stages"), + UI_FloatRange(minValue = 0f, maxValue = 5f, stepIncrement = 0.5f, scene = UI_Scene.Editor)] + public float timeBetweenStages = 1f; + + [KSPField(isPersistant = true, guiActive = false, guiActiveEditor = true, guiName = "Min Speed before guidance"), + UI_FloatRange(minValue = 0f, maxValue = 1000f, stepIncrement = 50f, scene = UI_Scene.Editor)] + public float MinSpeedGuidance = 200f; + private Vector3 initialMissileRollPlane; private Vector3 initialMissileForward; private float rollError; + private bool _minSpeedAchieved = false; #endregion public TransformAxisVectors ForwardTransformAxis { get; set; } @@ -131,7 +140,11 @@ private void RefreshGuidanceMode() Fields["BallisticOverShootFactor"].guiActive = GuidanceMode == GuidanceModes.AGMBallistic; Fields["BallisticOverShootFactor"].guiActiveEditor = GuidanceMode == GuidanceModes.AGMBallistic; } - + if (Fields["SoftAscent"] != null) + { + Fields["SoftAscent"].guiActive = GuidanceMode == GuidanceModes.AGMBallistic; + Fields["SoftAscent"].guiActiveEditor = GuidanceMode == GuidanceModes.AGMBallistic; + } Misc.Misc.RefreshAssociatedWindows(part); } public override void OnFixedUpdate() @@ -160,11 +173,26 @@ private void CheckNextStage() { if (ShouldExecuteNextStage()) { - ExecuteNextStage(); - + if (!nextStageCountdownStart) + { + this.nextStageCountdownStart = true; + this.stageCutOfftime = Time.time; + } + else + { + if ((Time.time - stageCutOfftime) >= timeBetweenStages) + { + ExecuteNextStage(); + nextStageCountdownStart = false; + } + } } } + public bool nextStageCountdownStart { get; set; } = false; + + public float stageCutOfftime { get; set; } = 0f; + private void CheckDelayedFired() { if (_missileIgnited) return; @@ -609,6 +637,21 @@ public void GuidanceSteer(FlightCtrlState s) debugString.Length = 0; if (guidanceActive && MissileReferenceTransform != null && _velocityTransform != null) { + + if (vessel.Velocity().magnitude < MinSpeedGuidance) + { + if (!_minSpeedAchieved) + { + s.mainThrottle = 1; + return; + } + } + else + { + _minSpeedAchieved = true; + } + + Vector3 newTargetPosition = new Vector3(); if (GuidanceIndex == 1) { @@ -640,6 +683,7 @@ public void GuidanceSteer(FlightCtrlState s) float steerYaw = SteerMult * targetDirection.x - SteerDamping * -localAngVel.z; float steerPitch = SteerMult * targetDirection.y - SteerDamping * -localAngVel.x; + s.yaw = Mathf.Clamp(steerYaw, -MaxSteer, MaxSteer); s.pitch = Mathf.Clamp(steerPitch, -MaxSteer, MaxSteer); From 94467972dc6e97d4edaa8ed8214d664006c25933 Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Mon, 10 Sep 2018 17:34:44 +0200 Subject: [PATCH 41/72] removing duplicates --- BDArmory/BDArmory.csproj | 2 -- 1 file changed, 2 deletions(-) diff --git a/BDArmory/BDArmory.csproj b/BDArmory/BDArmory.csproj index 131952133..9116a69d9 100644 --- a/BDArmory/BDArmory.csproj +++ b/BDArmory/BDArmory.csproj @@ -74,7 +74,6 @@ - @@ -83,7 +82,6 @@ - From af9d3cb9c0e4b3a81c2a2c1e0a459e0abffa723c Mon Sep 17 00:00:00 2001 From: Gedas Date: Mon, 10 Sep 2018 19:12:02 +0300 Subject: [PATCH 42/72] update pitchKi slider to have saner values, add pilot aiming debug lines --- .gitignore | 1 + BDArmory/Modules/BDModulePilotAI.cs | 11 ++++++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 8bf3ce07b..540ca1d49 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ BDArmory Ignore ####################################### BDArmory/BDArmory.csproj.user +_LocalDev BahaTurret/.vs BahaTurret/obj diff --git a/BDArmory/Modules/BDModulePilotAI.cs b/BDArmory/Modules/BDModulePilotAI.cs index 07c528e51..18e9b4d0a 100644 --- a/BDArmory/Modules/BDModulePilotAI.cs +++ b/BDArmory/Modules/BDModulePilotAI.cs @@ -72,8 +72,8 @@ Transform velocityTransform //make a combat steer mult and idle steer mult [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Pitch Ki"), - UI_FloatRange(minValue = 0f, maxValue = 20f, stepIncrement = .1f, scene = UI_Scene.All)] - public float pitchKiAdjust = 5; + UI_FloatRange(minValue = 0.05f, maxValue = 2f, stepIncrement = .01f, scene = UI_Scene.All)] + public float pitchKiAdjust = 0.2f; [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Steer Limiter"), @@ -120,7 +120,7 @@ Transform velocityTransform { nameof(defaultAltitude), 100000f }, { nameof(minAltitude), 30000f }, { nameof(steerMult), 200f }, - { nameof(pitchKiAdjust), 400f }, + { nameof(pitchKiAdjust), 200f }, { nameof(steerDamping), 100f }, { nameof(maxSpeed), 3000f }, { nameof(takeOffSpeed), 2000f }, @@ -802,6 +802,7 @@ float GetSteerLimiterForSpeedAndPower() } Vector3 prevTargetDir; + Vector3 debugPos; bool useVelRollTarget; void FlyToPosition(FlightCtrlState s, Vector3 targetPosition) { @@ -885,6 +886,7 @@ void FlyToPosition(FlightCtrlState s, Vector3 targetPosition) targetDirectionYaw = targetDirection; } + debugPos = vessel.transform.position + (targetPosition - vesselTransform.position) * 5000; pitchError = VectorUtils.SignedAngle(Vector3.up, Vector3.ProjectOnPlane(targetDirection, Vector3.right), Vector3.back); yawError = VectorUtils.SignedAngle(Vector3.up, Vector3.ProjectOnPlane(targetDirectionYaw, Vector3.forward), Vector3.right); @@ -1781,6 +1783,9 @@ protected override void OnGUI() BDGUIUtils.DrawLineBetweenWorldPositions(vesselTransform.position, debugFollowPosition, 2, Color.red); } + BDGUIUtils.DrawLineBetweenWorldPositions(vesselTransform.position, debugPos, 5, Color.red); + BDGUIUtils.DrawLineBetweenWorldPositions(vesselTransform.position, vesselTransform.position + vesselTransform.up * 5000, 3, Color.white); + BDGUIUtils.DrawLineBetweenWorldPositions(vesselTransform.position, vesselTransform.position + rollTarget, 2, Color.blue); BDGUIUtils.DrawLineBetweenWorldPositions(vesselTransform.position + (0.05f * vesselTransform.right), vesselTransform.position + (0.05f * vesselTransform.right) + angVelRollTarget, 2, Color.green); } From 8efb1cf06cd31e5d03772e895d266926c10a7ce3 Mon Sep 17 00:00:00 2001 From: Gedas Date: Tue, 11 Sep 2018 00:38:28 +0300 Subject: [PATCH 43/72] add yaw integral as well --- BDArmory/Modules/BDModulePilotAI.cs | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/BDArmory/Modules/BDModulePilotAI.cs b/BDArmory/Modules/BDModulePilotAI.cs index 18e9b4d0a..321f3f2eb 100644 --- a/BDArmory/Modules/BDModulePilotAI.cs +++ b/BDArmory/Modules/BDModulePilotAI.cs @@ -71,9 +71,9 @@ Transform velocityTransform public float steerMult = 6; //make a combat steer mult and idle steer mult - [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Pitch Ki"), - UI_FloatRange(minValue = 0.05f, maxValue = 2f, stepIncrement = .01f, scene = UI_Scene.All)] - public float pitchKiAdjust = 0.2f; + [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Ki factor"), + UI_FloatRange(minValue = 0.01f, maxValue = 1f, stepIncrement = 0.01f, scene = UI_Scene.All)] + public float steerKiAdjust = 0.05f; [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Steer Limiter"), @@ -120,7 +120,7 @@ Transform velocityTransform { nameof(defaultAltitude), 100000f }, { nameof(minAltitude), 30000f }, { nameof(steerMult), 200f }, - { nameof(pitchKiAdjust), 200f }, + { nameof(steerKiAdjust), 20f }, { nameof(steerDamping), 100f }, { nameof(maxSpeed), 3000f }, { nameof(takeOffSpeed), 2000f }, @@ -161,6 +161,7 @@ Transform velocityTransform //Controller Integral float pitchIntegral; + float yawIntegral; //instantaneous turn radius and possible acceleration from lift //properties can be used so that other AI modules can read this for future maneuverability comparisons between craft @@ -947,19 +948,24 @@ void FlyToPosition(FlightCtrlState s, Vector3 targetPosition) pitchError = pitchError * Mathf.Clamp01((21 - Mathf.Exp(Mathf.Abs(rollError) / 30)) / 20); } - float steerPitch = (0.015f * steerMult * pitchError) - (steerDamping * -localAngVel.x); - float steerYaw = (0.005f * steerMult * yawError) - (steerDamping * 0.2f * -localAngVel.z); + float steerPitch = (0.015f * steerMult * pitchError) - (steerDamping * -localAngVel.x * (1 + steerKiAdjust)); + float steerYaw = (0.005f * steerMult * yawError) - (steerDamping * 0.2f * -localAngVel.z * (1 + steerKiAdjust)); pitchIntegral += pitchError; + yawIntegral += yawError; steerPitch *= dynamicAdjustment; steerYaw *= dynamicAdjustment; - float pitchKi = 0.1f * (pitchKiAdjust/5); //This is what should be allowed to be tweaked by the player, just like the steerMult, it is very low right now + float pitchKi = 0.1f * (steerKiAdjust/5); //This is what should be allowed to be tweaked by the player, just like the steerMult, it is very low right now pitchIntegral = Mathf.Clamp(pitchIntegral, -0.2f / (pitchKi * dynamicAdjustment), 0.2f / (pitchKi * dynamicAdjustment)); //0.2f is the limit of the integral variable, making it bigger increases overshoot steerPitch += pitchIntegral * pitchKi * dynamicAdjustment; //Adds the integral component to the mix - float roll = Mathf.Clamp(steerRoll, -maxSteer, maxSteer); + float yawKi = 0.1f * (steerKiAdjust / 15); + yawIntegral = Mathf.Clamp(yawIntegral, -0.2f / (yawKi * dynamicAdjustment), 0.2f / (yawKi * dynamicAdjustment)); + steerYaw += yawIntegral * yawKi * dynamicAdjustment; + + float roll = Mathf.Clamp(steerRoll, -maxSteer, maxSteer); s.roll = roll; s.yaw = Mathf.Clamp(steerYaw, -finalMaxSteer, finalMaxSteer); s.pitch = Mathf.Clamp(steerPitch, Mathf.Min(-finalMaxSteer, -0.2f), finalMaxSteer); From 9611fcffb37152784be65f9d0a07cb6478ce35ae Mon Sep 17 00:00:00 2001 From: Gedas Date: Tue, 11 Sep 2018 00:38:46 +0300 Subject: [PATCH 44/72] add advanced tweakable to set orbit direction --- BDArmory/Modules/BDModulePilotAI.cs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/BDArmory/Modules/BDModulePilotAI.cs b/BDArmory/Modules/BDModulePilotAI.cs index 321f3f2eb..7b167936c 100644 --- a/BDArmory/Modules/BDModulePilotAI.cs +++ b/BDArmory/Modules/BDModulePilotAI.cs @@ -110,7 +110,11 @@ Transform velocityTransform float maxAllowedCosAoA; float lastAllowedAoA; - [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Unclamp tuning ", advancedTweakable = true), + [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Orbit ", advancedTweakable = true), + UI_Toggle(enabledText = "Clockwise", disabledText = "Counterclockwise", scene = UI_Scene.All),] + public bool ClockwiseOrbit = true; + + [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Unclamp tuning ", advancedTweakable = true), UI_Toggle(enabledText = "Unclamped", disabledText = "Clamped", scene = UI_Scene.All),] public bool UpToEleven = false; bool toEleven = false; @@ -500,7 +504,7 @@ void UpdateAI(FlightCtrlState s) if(!extending) { currentStatus = "Orbiting"; - FlyOrbit(s, assignedPositionGeo, 2000, idleSpeed, true); + FlyOrbit(s, assignedPositionGeo, 2000, idleSpeed, ClockwiseOrbit); } } @@ -1662,12 +1666,12 @@ void UpdateCommand(FlightCtrlState s) else if(command == PilotCommands.FlyTo) { currentStatus = "Fly To"; - FlyOrbit(s, assignedPositionGeo, 2500, idleSpeed, true); + FlyOrbit(s, assignedPositionGeo, 2500, idleSpeed, ClockwiseOrbit); } else if(command == PilotCommands.Attack) { currentStatus = "Attack"; - FlyOrbit(s, assignedPositionGeo, 4500, maxSpeed, true); + FlyOrbit(s, assignedPositionGeo, 4500, maxSpeed, ClockwiseOrbit); } } From 34de42e05c657b15ccf40eb4a4b441a1a5a9432d Mon Sep 17 00:00:00 2001 From: Gedas Date: Tue, 11 Sep 2018 02:28:10 +0300 Subject: [PATCH 45/72] include bombs in missilesAway calculation --- BDArmory/Modules/MissileFire.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/BDArmory/Modules/MissileFire.cs b/BDArmory/Modules/MissileFire.cs index 5f6f4418b..11c2c3b29 100644 --- a/BDArmory/Modules/MissileFire.cs +++ b/BDArmory/Modules/MissileFire.cs @@ -902,8 +902,10 @@ private void CalculateMissilesAway() if(missileBase.SourceVessel != this.vessel) continue; - if (missileBase.guidanceActive == true && !missileBase.HasMissed && - missileBase.MissileState != MissileBase.MissileStates.PostThrust) + if ((missileBase.guidanceActive == false + && !missileBase.HasMissed + && missileBase.MissileState != MissileBase.MissileStates.PostThrust) + || missileBase.GetWeaponClass() == WeaponClasses.Bomb) { tempMissilesAway++; } From 9952700f2ab77fdd654dff28f8d855b8174b3c55 Mon Sep 17 00:00:00 2001 From: Gedas Date: Tue, 11 Sep 2018 02:55:01 +0300 Subject: [PATCH 46/72] add a roll check for bomb release --- BDArmory/Modules/MissileFire.cs | 3 ++- BDArmory/Modules/ModuleWeapon.cs | 4 ---- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/BDArmory/Modules/MissileFire.cs b/BDArmory/Modules/MissileFire.cs index 11c2c3b29..dc4f98269 100644 --- a/BDArmory/Modules/MissileFire.cs +++ b/BDArmory/Modules/MissileFire.cs @@ -1578,7 +1578,8 @@ IEnumerator GuardBombRoutine() hasSetCargoBays = true; } - if (targetDist > radius) + if (targetDist > radius + || Vector3.Dot(VectorUtils.GetUpDirection(vessel.CoM), vessel.transform.forward) > 0) // roll check { if (targetDist < Mathf.Max(radius * 2, 800f) && Vector3.Dot(guardTarget.CoM - bombAimerPosition, guardTarget.CoM - transform.position) < 0) diff --git a/BDArmory/Modules/ModuleWeapon.cs b/BDArmory/Modules/ModuleWeapon.cs index 000ac8cd2..49ee34d6c 100644 --- a/BDArmory/Modules/ModuleWeapon.cs +++ b/BDArmory/Modules/ModuleWeapon.cs @@ -20,10 +20,6 @@ public class ModuleWeapon : EngageableWeapon, IBDWeapon { #region Declarations - #region Variables - - #endregion - public static ObjectPool bulletPool; public static ObjectPool shellPool; From 0fd93fbe3722f7698aabbd4afbb4e789ed69ead4 Mon Sep 17 00:00:00 2001 From: Gedas Date: Tue, 11 Sep 2018 11:20:25 +0300 Subject: [PATCH 47/72] fix autofire angles for turrets --- BDArmory/Modules/MissileFire.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/BDArmory/Modules/MissileFire.cs b/BDArmory/Modules/MissileFire.cs index dc4f98269..d6b3c1787 100644 --- a/BDArmory/Modules/MissileFire.cs +++ b/BDArmory/Modules/MissileFire.cs @@ -3942,7 +3942,10 @@ void GuardMode() if (weapon.Current.part.partInfo.title != selectedWeapon.GetPart().partInfo.title) continue; weapon.Current.EnableWeapon(); weapon.Current.aiControlled = true; - weapon.Current.maxAutoFireCosAngle = vessel.LandedOrSplashed ? 0.9993908f : 0.9975641f; //2 : 4 degrees + if (weapon.Current.yawRange >= 5 && (weapon.Current.maxPitch - weapon.Current.minPitch) >= 5) + weapon.Current.maxAutoFireCosAngle = Mathf.Cos(weapon.Current.maxDeviation / 2 * Mathf.Deg2Rad); + else + weapon.Current.maxAutoFireCosAngle = vessel.LandedOrSplashed ? 0.9993908f : 0.9975641f; //2 : 4 degrees } weapon.Dispose(); } From ae79d3223dce71413b1034582d3bed7a07b29b6a Mon Sep 17 00:00:00 2001 From: Gedas Date: Tue, 11 Sep 2018 11:20:44 +0300 Subject: [PATCH 48/72] Fix aiming calculations to take place at the same time as firing --- BDArmory/Modules/ModuleWeapon.cs | 108 ++++++++++++++++--------------- 1 file changed, 57 insertions(+), 51 deletions(-) diff --git a/BDArmory/Modules/ModuleWeapon.cs b/BDArmory/Modules/ModuleWeapon.cs index 49ee34d6c..b4df3ba1f 100644 --- a/BDArmory/Modules/ModuleWeapon.cs +++ b/BDArmory/Modules/ModuleWeapon.cs @@ -248,7 +248,7 @@ public string GetMissileType() [KSPField] public float roundsPerMinute = 850; //rate of fire [KSPField] - public float maxDeviation = 1; //max inaccuracy deviation in degrees + public float maxDeviation = 1; //inaccuracy standard deviation in degrees [KSPField] public float maxEffectiveDistance = 2500; //used by AI to select appropriate weapon [KSPField] @@ -791,9 +791,6 @@ void FixedUpdate() if (weaponState == WeaponStates.Enabled && (TimeWarp.WarpMode != TimeWarp.Modes.HIGH || TimeWarp.CurrentRate == 1)) { - UpdateTargetVessel(); - updateAcceleration(targetVelocity); - relativeVelocity = targetVelocity - vessel.rb_velocity; //Aim(); StartCoroutine(AimAndFireAtEndOfFrame()); @@ -823,50 +820,6 @@ void FixedUpdate() } audioSource.Stop(); } - - - //autofiring with AI - if (targetAcquired && aiControlled) - { - Transform fireTransform = fireTransforms[0]; - Vector3 targetRelPos = (finalAimTarget) - fireTransform.position; - Vector3 aimDirection = fireTransform.forward; - float targetCosAngle = Vector3.Dot(aimDirection, targetRelPos.normalized); - - Vector3 targetDiffVec = finalAimTarget - lastFinalAimTarget; - Vector3 projectedTargetPos = targetDiffVec; - //projectedTargetPos /= TimeWarp.fixedDeltaTime; - //projectedTargetPos *= TimeWarp.fixedDeltaTime; - projectedTargetPos *= 2; //project where the target will be in 2 timesteps - projectedTargetPos += finalAimTarget; - - targetDiffVec.Normalize(); - Vector3 lastTargetRelPos = (lastFinalAimTarget) - fireTransform.position; - - if (BDATargetManager.CheckSafeToFireGuns(weaponManager, aimDirection, 1000, 0.999848f) && - //~1 degree of unsafe angle - (targetCosAngle >= maxAutoFireCosAngle || //check if directly on target - (Vector3.Dot(targetDiffVec, targetRelPos) * Vector3.Dot(targetDiffVec, lastTargetRelPos) < 0 && - targetCosAngle > 0))) //check if target will pass this point soon - { - autoFire = true; - } - else - { - autoFire = false; - } - } - else - { - autoFire = false; - } - - //disable autofire after burst length - if (autoFire && Time.time - autoFireTimer > autoFireLength) - { - autoFire = false; - legacyTargetVessel = null; - } } lastFinalAimTarget = finalAimTarget; } @@ -971,8 +924,11 @@ private void Fire() } float timeGap = (60 / roundsPerMinute) * TimeWarp.CurrentRate; - if (Time.time - timeFired > timeGap && !isOverheated && !pointingAtSelf && !Misc.Misc.CheckMouseIsOnGui() && - WMgrAuthorized()) + if (Time.time - timeFired > timeGap + && !isOverheated + && !pointingAtSelf + && (aiControlled || !Misc.Misc.CheckMouseIsOnGui()) + && WMgrAuthorized()) { bool effectsShot = false; //Transform[] fireTransforms = part.FindModelTransforms("fireTransform"); @@ -1712,13 +1668,63 @@ void Aim() } } + void CheckAIAutofire() + { + //autofiring with AI + if (targetAcquired && aiControlled) + { + Transform fireTransform = fireTransforms[0]; + Vector3 targetRelPos = (finalAimTarget) - fireTransform.position; + Vector3 aimDirection = fireTransform.forward; + float targetCosAngle = Vector3.Dot(aimDirection, targetRelPos.normalized); + + Vector3 targetDiffVec = finalAimTarget - lastFinalAimTarget; + Vector3 projectedTargetPos = targetDiffVec; + //projectedTargetPos /= TimeWarp.fixedDeltaTime; + //projectedTargetPos *= TimeWarp.fixedDeltaTime; + projectedTargetPos *= 2; //project where the target will be in 2 timesteps + projectedTargetPos += finalAimTarget; + + targetDiffVec.Normalize(); + Vector3 lastTargetRelPos = (lastFinalAimTarget) - fireTransform.position; + + if (BDATargetManager.CheckSafeToFireGuns(weaponManager, aimDirection, 1000, 0.999848f) //~1 degree of unsafe angle + && targetCosAngle >= maxAutoFireCosAngle) //check if directly on target + { + autoFire = true; + Debug.Log($"target cos angle {Vector3.Dot(aimDirection, targetRelPos.normalized)}, target angle "); + } + else + { + autoFire = false; + } + } + else + { + autoFire = false; + } + + //disable autofire after burst length + if (autoFire && Time.time - autoFireTimer > autoFireLength) + { + autoFire = false; + legacyTargetVessel = null; + } + } + IEnumerator AimAndFireAtEndOfFrame() { + if (eWeaponType != WeaponTypes.Laser) yield return new WaitForEndOfFrame(); + + UpdateTargetVessel(); + updateAcceleration(targetVelocity); + relativeVelocity = targetVelocity - vessel.rb_velocity; + RunTrajectorySimulation(); Aim(); CheckWeaponSafety(); + CheckAIAutofire(); - if (eWeaponType != WeaponTypes.Laser) yield return new WaitForEndOfFrame(); if (finalFire) { if (eWeaponType == WeaponTypes.Laser) From aa94cb6fbfabb9f11180257ce16900dfe410a3ed Mon Sep 17 00:00:00 2001 From: Gedas Date: Tue, 11 Sep 2018 23:00:47 +0300 Subject: [PATCH 49/72] update orbit parameters --- BDArmory/Modules/BDModulePilotAI.cs | 4 ++-- BDArmory/Modules/BDModuleSurfaceAI.cs | 17 ++++++++++++++--- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/BDArmory/Modules/BDModulePilotAI.cs b/BDArmory/Modules/BDModulePilotAI.cs index 7b167936c..a550284a0 100644 --- a/BDArmory/Modules/BDModulePilotAI.cs +++ b/BDArmory/Modules/BDModulePilotAI.cs @@ -71,7 +71,7 @@ Transform velocityTransform public float steerMult = 6; //make a combat steer mult and idle steer mult - [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Ki factor"), + [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Steer Ki"), UI_FloatRange(minValue = 0.01f, maxValue = 1f, stepIncrement = 0.01f, scene = UI_Scene.All)] public float steerKiAdjust = 0.05f; @@ -111,7 +111,7 @@ Transform velocityTransform float lastAllowedAoA; [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Orbit ", advancedTweakable = true), - UI_Toggle(enabledText = "Clockwise", disabledText = "Counterclockwise", scene = UI_Scene.All),] + UI_Toggle(enabledText = "Starboard (CW)", disabledText = "Port (CCW)", scene = UI_Scene.All),] public bool ClockwiseOrbit = true; [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Unclamp tuning ", advancedTweakable = true), diff --git a/BDArmory/Modules/BDModuleSurfaceAI.cs b/BDArmory/Modules/BDModuleSurfaceAI.cs index e6ecb9703..2c8fc29cd 100644 --- a/BDArmory/Modules/BDModuleSurfaceAI.cs +++ b/BDArmory/Modules/BDModuleSurfaceAI.cs @@ -29,7 +29,6 @@ public class BDModuleSurfaceAI : BDGenericAIBase, IBDAIControl float weaveDirection = 1; const float weaveLimit = 15; const float weaveFactor = 6.5f; - int sideSlipDirection = 0; Vector3 upDir; @@ -115,6 +114,14 @@ public AIUtils.VehicleMovementType SurfaceType UI_FloatRange(minValue = 0f, maxValue = 100f, stepIncrement = 1f, scene = UI_Scene.All),] public float AvoidMass = 0f; + [KSPField(isPersistant = true, guiActiveEditor = true, guiName = "Preferred broadside direction", advancedTweakable = true), + UI_ChooseOption(options = new string[3] { "Starboard", "Whatever", "Port" }, scene = UI_Scene.All),] + public string OrbitDirectionName = "Whatever"; + readonly string[] orbitDirections = new string[3] { "Starboard", "Whatever", "Port" }; + + [KSPField(isPersistant = true)] + int sideSlipDirection = 0; + [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Goes up to ", advancedTweakable = true), UI_Toggle(enabledText = "eleven", disabledText = "ten", scene = UI_Scene.All), ] public bool UpToEleven = false; @@ -181,8 +188,12 @@ public override void ActivatePilot() } motorControl.Activate(); - if (BroadsideAttack) - sideSlipDirection = UnityEngine.Random.Range(0, 2) > 1 ? 1 : -1; + if (BroadsideAttack && sideSlipDirection == 0) + { + sideSlipDirection = orbitDirections.IndexOf(OrbitDirectionName); + if (sideSlipDirection == 0) + sideSlipDirection = UnityEngine.Random.Range(0, 2) > 1 ? 1 : -1; + } leftPath = true; extendingTarget = null; From 4d6b5b2287fe7dca48fdec5d9066ba87cdfa4e41 Mon Sep 17 00:00:00 2001 From: Gedas Date: Tue, 11 Sep 2018 23:40:15 +0300 Subject: [PATCH 50/72] attempt to fix missiles/bombs away calculation --- BDArmory/Modules/BDModularGuidance.cs | 31 +++++++++++++-------------- BDArmory/Modules/MissileFire.cs | 5 +---- BDArmory/Modules/MissileLauncher.cs | 2 +- 3 files changed, 17 insertions(+), 21 deletions(-) diff --git a/BDArmory/Modules/BDModularGuidance.cs b/BDArmory/Modules/BDModularGuidance.cs index 9cd212169..88179489c 100644 --- a/BDArmory/Modules/BDModularGuidance.cs +++ b/BDArmory/Modules/BDModularGuidance.cs @@ -653,24 +653,23 @@ public void GuidanceSteer(FlightCtrlState s) Vector3 newTargetPosition = new Vector3(); - if (GuidanceIndex == 1) + switch (GuidanceIndex) { - newTargetPosition = AAMGuidance(); - CheckMiss(newTargetPosition); - - } - else if (GuidanceIndex == 2) - { - newTargetPosition = AGMGuidance(); - } - else if (GuidanceIndex == 3) - { - newTargetPosition = CruiseGuidance(); - } - else if (GuidanceIndex == 4) - { - newTargetPosition = BallisticGuidance(); + case 1: + newTargetPosition = AAMGuidance(); + break; + case 2: + newTargetPosition = AGMGuidance(); + break; + case 3: + newTargetPosition = CruiseGuidance(); + break; + case 4: + newTargetPosition = BallisticGuidance(); + break; } + CheckMiss(newTargetPosition); + //Updating aero surfaces if (TimeIndex > dropTime + 0.5f) diff --git a/BDArmory/Modules/MissileFire.cs b/BDArmory/Modules/MissileFire.cs index d6b3c1787..f04492079 100644 --- a/BDArmory/Modules/MissileFire.cs +++ b/BDArmory/Modules/MissileFire.cs @@ -902,10 +902,7 @@ private void CalculateMissilesAway() if(missileBase.SourceVessel != this.vessel) continue; - if ((missileBase.guidanceActive == false - && !missileBase.HasMissed - && missileBase.MissileState != MissileBase.MissileStates.PostThrust) - || missileBase.GetWeaponClass() == WeaponClasses.Bomb) + if (!missileBase.HasMissed) { tempMissilesAway++; } diff --git a/BDArmory/Modules/MissileLauncher.cs b/BDArmory/Modules/MissileLauncher.cs index 13071bc8e..bccddaa83 100644 --- a/BDArmory/Modules/MissileLauncher.cs +++ b/BDArmory/Modules/MissileLauncher.cs @@ -875,7 +875,7 @@ public override void OnFixedUpdate() private void CheckMiss() { float sqrDist = ((TargetPosition + (TargetVelocity * Time.fixedDeltaTime)) - (transform.position + (part.rb.velocity * Time.fixedDeltaTime))).sqrMagnitude; - if (sqrDist < 160000 || (MissileState == MissileStates.PostThrust && (GuidanceMode == GuidanceModes.AAMLead || GuidanceMode == GuidanceModes.AAMPure))) + if (sqrDist < 160000 || MissileState == MissileStates.PostThrust) { checkMiss = true; } From b91390fb9c0f6084124a20550c615ed2c3f786db Mon Sep 17 00:00:00 2001 From: Gedas Date: Tue, 11 Sep 2018 23:59:38 +0300 Subject: [PATCH 51/72] cluster bomb krakensbane fix --- BDArmory/Modules/ClusterBomb.cs | 99 ++++++++++++++------------------- 1 file changed, 41 insertions(+), 58 deletions(-) diff --git a/BDArmory/Modules/ClusterBomb.cs b/BDArmory/Modules/ClusterBomb.cs index 041a14f60..d7734fb64 100644 --- a/BDArmory/Modules/ClusterBomb.cs +++ b/BDArmory/Modules/ClusterBomb.cs @@ -121,13 +121,12 @@ void DeploySubmunitions() Vector3 direction = (sub.Current.transform.position - part.transform.position).normalized; Rigidbody subRB = sub.Current.GetComponent(); subRB.isKinematic = false; - subRB.velocity = part.rb.velocity + + subRB.velocity = part.rb.velocity + Krakensbane.GetFrameVelocityV3f() + (UnityEngine.Random.Range(submunitionMaxSpeed/10, submunitionMaxSpeed)*direction); Submunition subScript = sub.Current.AddComponent(); subScript.enabled = true; subScript.deployed = true; - subScript.sourceVessel = missileLauncher.SourceVessel; subScript.blastForce = missileLauncher.GetTntMass(); subScript.blastHeat = missileLauncher.blastHeat; subScript.blastRadius = missileLauncher.GetBlastRadius(); @@ -143,12 +142,11 @@ void DeploySubmunitions() Vector3 direction = (fairing.Current.transform.position - part.transform.position).normalized; Rigidbody fRB = fairing.Current.GetComponent(); fRB.isKinematic = false; - fRB.velocity = part.rb.velocity + ((submunitionMaxSpeed + 2)*direction); + fRB.velocity = part.rb.velocity + Krakensbane.GetFrameVelocityV3f() + ((submunitionMaxSpeed + 2)*direction); fairing.Current.AddComponent(); fairing.Current.GetComponent().drag = 0.2f; ClusterBombFairing fairingScript = fairing.Current.AddComponent(); fairingScript.deployed = true; - fairingScript.sourceVessel = vessel; } fairing.Dispose(); @@ -177,10 +175,8 @@ public class Submunition : MonoBehaviour public float blastHeat; public string subExplModelPath; public string subExplSoundPath; - public Vessel sourceVessel; Vector3 currPosition; Vector3 prevPosition; - Vector3 relativePos; float startTime; @@ -189,7 +185,6 @@ public class Submunition : MonoBehaviour void Start() { startTime = Time.time; - relativePos = transform.position - sourceVessel.transform.position; currPosition = transform.position; prevPosition = transform.position; rb = GetComponent(); @@ -206,59 +201,53 @@ void FixedUpdate() { if (deployed) { - if (deployed) + if (Time.time - startTime > 30) { - if (Time.time - startTime > 30) + Destroy(gameObject); + return; + } + + //floating origin and velocity offloading corrections + if (!FloatingOrigin.Offset.IsZero() || !Krakensbane.GetFrameVelocity().IsZero()) + { + transform.position -= FloatingOrigin.OffsetNonKrakensbane; + prevPosition -= FloatingOrigin.OffsetNonKrakensbane; + } + + currPosition = transform.position; + float dist = (currPosition - prevPosition).magnitude; + Ray ray = new Ray(prevPosition, currPosition - prevPosition); + RaycastHit hit; + + if (Physics.Raycast(ray, out hit, dist, 9076737)) + { + Part hitPart = null; + try { - Destroy(gameObject); - return; + hitPart = hit.collider.gameObject.GetComponentInParent(); } - - //floatingOrigin fix - if (sourceVessel != null && - ((transform.position - sourceVessel.transform.position) - relativePos).sqrMagnitude > 800 * 800) + catch (NullReferenceException) { - transform.position = sourceVessel.transform.position + relativePos + - (rb.velocity * Time.fixedDeltaTime); + Debug.Log("[BDArmory]:NullReferenceException for Submunition Hit"); + return; } - if (sourceVessel != null) relativePos = transform.position - sourceVessel.transform.position; - // - - currPosition = transform.position; - float dist = (currPosition - prevPosition).magnitude; - Ray ray = new Ray(prevPosition, currPosition - prevPosition); - RaycastHit hit; - if (Physics.Raycast(ray, out hit, dist, 9076737)) + if (hitPart != null || CheckBuildingHit(hit)) { - Part hitPart = null; - try - { - hitPart = hit.collider.gameObject.GetComponentInParent(); - } - catch (NullReferenceException) - { - Debug.Log("[BDArmory]:NullReferenceException for Submunition Hit"); - return; - } - - if (hitPart?.vessel == sourceVessel) return; - - if (hitPart != null || CheckBuildingHit(hit)) - { - Detonate(hit.point); - } - else if (hitPart == null) - { - Detonate(currPosition); - } - + Detonate(hit.point); } - else if (FlightGlobals.getAltitudeAtPos(currPosition) <= 0) + else if (hitPart == null) { Detonate(currPosition); } + } + else if (FlightGlobals.getAltitudeAtPos(currPosition) <= 0) + { + Detonate(currPosition); + } + + prevPosition = transform.position; } } @@ -290,10 +279,8 @@ public class ClusterBombFairing : MonoBehaviour { public bool deployed; - public Vessel sourceVessel; Vector3 currPosition; Vector3 prevPosition; - Vector3 relativePos; float startTime; Rigidbody rb; @@ -303,7 +290,6 @@ void Start() startTime = Time.time; currPosition = transform.position; prevPosition = transform.position; - relativePos = transform.position - sourceVessel.transform.position; rb = GetComponent(); } @@ -311,15 +297,12 @@ void FixedUpdate() { if (deployed) { - //floatingOrigin fix - if (sourceVessel != null && - ((transform.position - sourceVessel.transform.position) - relativePos).sqrMagnitude > 800*800) + //floating origin and velocity offloading corrections + if (!FloatingOrigin.Offset.IsZero() || !Krakensbane.GetFrameVelocity().IsZero()) { - transform.position = sourceVessel.transform.position + relativePos + - (rb.velocity*Time.fixedDeltaTime); + transform.position -= FloatingOrigin.OffsetNonKrakensbane; + prevPosition -= FloatingOrigin.OffsetNonKrakensbane; } - if (sourceVessel != null) relativePos = transform.position - sourceVessel.transform.position; - // currPosition = transform.position; float dist = (currPosition - prevPosition).magnitude; From 8e9f7f756bff0fababfb40786827dadd022acbdb Mon Sep 17 00:00:00 2001 From: Gedas Date: Wed, 12 Sep 2018 00:43:16 +0300 Subject: [PATCH 52/72] rocket launcher krakensbane correction --- BDArmory/Modules/RocketLauncher.cs | 37 +++++------------------------- 1 file changed, 6 insertions(+), 31 deletions(-) diff --git a/BDArmory/Modules/RocketLauncher.cs b/BDArmory/Modules/RocketLauncher.cs index ce0db45e6..bfb4112a2 100644 --- a/BDArmory/Modules/RocketLauncher.cs +++ b/BDArmory/Modules/RocketLauncher.cs @@ -571,12 +571,7 @@ public void FireRocket() rocket.thrust = thrust; rocket.thrustTime = thrustTime; rocket.randomThrustDeviation = thrustDeviation; - if (BDArmorySettings.ALLOW_LEGACY_TARGETING && vessel.targetObject != null) - { - rocket.targetVessel = vessel.targetObject.GetVessel(); - } - rocket.sourceVessel = vessel; rocketObj.SetActive(true); rocketObj.transform.SetParent(currentRocketTfm.parent); rocket.parentRB = part.rb; @@ -803,9 +798,6 @@ public override string GetInfo() public class Rocket : MonoBehaviour { public Transform spawnTransform; - public Vessel targetVessel; - public Vessel sourceVessel; - public Vector3 startVelocity; public float mass; public float thrust; public float thrustTime; @@ -825,9 +817,6 @@ public class Rocket : MonoBehaviour Vector3 prevPosition; Vector3 currPosition; - - Vector3 relativePos; - float stayTime = 0.04f; float lifeTime = 10; @@ -886,14 +875,12 @@ void Start() void FixedUpdate() { - //floatingOrigin fix - if (sourceVessel != null && - (transform.position - sourceVessel.transform.position - relativePos).sqrMagnitude > 800*800) + //floating origin and velocity offloading corrections + if (!FloatingOrigin.Offset.IsZero() || !Krakensbane.GetFrameVelocity().IsZero()) { - transform.position = sourceVessel.transform.position + relativePos + (rb.velocity*Time.fixedDeltaTime); + transform.position -= FloatingOrigin.OffsetNonKrakensbane; + prevPosition -= FloatingOrigin.OffsetNonKrakensbane; } - if (sourceVessel != null) relativePos = transform.position - sourceVessel.transform.position; - // if (Time.time - startTime < stayTime && transform.parent != null) @@ -906,10 +893,9 @@ void FixedUpdate() { if (transform.parent != null && parentRB) { - startVelocity = parentRB.velocity; transform.parent = null; rb.isKinematic = false; - rb.velocity = startVelocity; + rb.velocity = parentRB.velocity + Krakensbane.GetFrameVelocityV3f(); } } @@ -1008,11 +994,7 @@ void FixedUpdate() { } - - if (hitPart == null || (hitPart != null && hitPart.vessel != sourceVessel)) - { - Detonate(hit.point); - } + Detonate(hit.point); } else if (FlightGlobals.getAltitudeAtPos(transform.position) < 0) { @@ -1030,13 +1012,6 @@ void FixedUpdate() { Detonate(transform.position); } - - //proxy detonation - if (targetVessel != null && - (transform.position - targetVessel.transform.position).sqrMagnitude < 0.5f*blastRadius*blastRadius) - { - Detonate(transform.position); - } } void Update() From 63b38d9c5fbb9dbe797188f94566b351e3790083 Mon Sep 17 00:00:00 2001 From: Gedas Date: Wed, 12 Sep 2018 00:52:58 +0300 Subject: [PATCH 53/72] only shoot turrets when dead-on, since turrets achieve it easily --- BDArmory/Modules/MissileFire.cs | 2 +- BDArmory/Modules/ModuleWeapon.cs | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/BDArmory/Modules/MissileFire.cs b/BDArmory/Modules/MissileFire.cs index f04492079..eb2c9bb6c 100644 --- a/BDArmory/Modules/MissileFire.cs +++ b/BDArmory/Modules/MissileFire.cs @@ -3940,7 +3940,7 @@ void GuardMode() weapon.Current.EnableWeapon(); weapon.Current.aiControlled = true; if (weapon.Current.yawRange >= 5 && (weapon.Current.maxPitch - weapon.Current.minPitch) >= 5) - weapon.Current.maxAutoFireCosAngle = Mathf.Cos(weapon.Current.maxDeviation / 2 * Mathf.Deg2Rad); + weapon.Current.maxAutoFireCosAngle = 1; else weapon.Current.maxAutoFireCosAngle = vessel.LandedOrSplashed ? 0.9993908f : 0.9975641f; //2 : 4 degrees } diff --git a/BDArmory/Modules/ModuleWeapon.cs b/BDArmory/Modules/ModuleWeapon.cs index b4df3ba1f..b9248ec29 100644 --- a/BDArmory/Modules/ModuleWeapon.cs +++ b/BDArmory/Modules/ModuleWeapon.cs @@ -1692,7 +1692,6 @@ void CheckAIAutofire() && targetCosAngle >= maxAutoFireCosAngle) //check if directly on target { autoFire = true; - Debug.Log($"target cos angle {Vector3.Dot(aimDirection, targetRelPos.normalized)}, target angle "); } else { From 6ca478b239c5d5c7b03730f5e769d3fcca7e1541 Mon Sep 17 00:00:00 2001 From: Gedas Date: Wed, 12 Sep 2018 01:02:33 +0300 Subject: [PATCH 54/72] Stop explosions moving across the ground. --- BDArmory/FX/ExplosionFX.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/BDArmory/FX/ExplosionFX.cs b/BDArmory/FX/ExplosionFX.cs index 93cfcb2c1..40073dcb7 100644 --- a/BDArmory/FX/ExplosionFX.cs +++ b/BDArmory/FX/ExplosionFX.cs @@ -248,6 +248,12 @@ public void Update() public void FixedUpdate() { + //floating origin and velocity offloading corrections + if (!FloatingOrigin.Offset.IsZero() || !Krakensbane.GetFrameVelocity().IsZero()) + { + transform.position -= FloatingOrigin.OffsetNonKrakensbane; + } + while (ExplosionEvents.Count > 0 && ExplosionEvents.Peek().TimeToImpact <= TimeIndex) { BlastHitEvent eventToExecute = ExplosionEvents.Dequeue(); From 1aab460c165caf4ffad7a13d586f23662a023009 Mon Sep 17 00:00:00 2001 From: Gedas Date: Wed, 12 Sep 2018 01:22:04 +0300 Subject: [PATCH 55/72] bring back rockets not hitting the launcher --- BDArmory/Modules/RocketLauncher.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/BDArmory/Modules/RocketLauncher.cs b/BDArmory/Modules/RocketLauncher.cs index bfb4112a2..c1f796f17 100644 --- a/BDArmory/Modules/RocketLauncher.cs +++ b/BDArmory/Modules/RocketLauncher.cs @@ -572,6 +572,7 @@ public void FireRocket() rocket.thrustTime = thrustTime; rocket.randomThrustDeviation = thrustDeviation; + rocket.sourceVessel = vessel; rocketObj.SetActive(true); rocketObj.transform.SetParent(currentRocketTfm.parent); rocket.parentRB = part.rb; @@ -798,6 +799,7 @@ public override string GetInfo() public class Rocket : MonoBehaviour { public Transform spawnTransform; + public Vessel sourceVessel; public float mass; public float thrust; public float thrustTime; @@ -994,7 +996,11 @@ void FixedUpdate() { } - Detonate(hit.point); + + if (hitPart == null || (hitPart != null && hitPart.vessel != sourceVessel)) + { + Detonate(hit.point); + } } else if (FlightGlobals.getAltitudeAtPos(transform.position) < 0) { From ebbd1292c3c3f3508562053a425dd57d177b7264 Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Wed, 12 Sep 2018 22:59:41 +0200 Subject: [PATCH 56/72] fixing detonation on collission #566 --- BDArmory/Modules/MissileBase.cs | 194 +++++++++++--------------------- 1 file changed, 64 insertions(+), 130 deletions(-) diff --git a/BDArmory/Modules/MissileBase.cs b/BDArmory/Modules/MissileBase.cs index 06cc04bd2..7acebd68e 100644 --- a/BDArmory/Modules/MissileBase.cs +++ b/BDArmory/Modules/MissileBase.cs @@ -230,7 +230,7 @@ public float Throttle private float _throttle = 1f; private float _originalDistance = float.MinValue; private Vector3 _startPoint; - + Vector3 previousPos; public string GetSubLabel() { @@ -918,119 +918,7 @@ public void CheckDetonationState() { //Guard clauses if (!TargetAcquired) return; - //skip check of user set to zero, rely on OnCollisionEnter if missile speed is below mach 1 (340 m/s) - //otherwise use an autocalculated value based off the missiles surface speed to determine the - //detonation offset in order to prevent phasing through a part and exploding inside - if (DetonationDistance == 0) - { - if (this.vessel.srfSpeed <= 340) - { - return; - } - else - { - if (autoDetCalc) - { - _DetonationOffset = (float)((this.vessel.srfSpeed / 600) * 0.1); - - if (_DetonationOffset <= 0.1f) - { - _DetonationOffset = 0.1f; - } - } - else - { - _DetonationOffset = DetonationOffset; - } - - var targetDistancePerFrame = TargetVelocity * Time.deltaTime; - var missileDistancePerFrame = vessel.Velocity() * Time.deltaTime; - - var futureTargetPosition = (TargetPosition + targetDistancePerFrame); - var futureMissilePosition = (vessel.CoM + missileDistancePerFrame); - - switch (DetonationDistanceState) - { - case DetonationDistanceStates.NotSafe: - //Lets check if we are at a safe distance from the source vessel - Ray raySourceVessel = new Ray(futureMissilePosition, SourceVessel.CoM + SourceVessel.Velocity() * Time.deltaTime); - - var hits = Physics.RaycastAll(raySourceVessel, GetBlastRadius() * 2, 557057).AsEnumerable(); - - using (var hitsEnu = hits.GetEnumerator()) - { - while (hitsEnu.MoveNext()) - { - RaycastHit hit = hitsEnu.Current; - - try - { - var hitPart = hit.collider.gameObject.GetComponentInParent(); - - if (hitPart?.vessel == SourceVessel) - { - //We found a hit to the vessel - return; - } - } - catch - { - // ignored - } - } - } - - //We are safe and we can continue with the next state - DetonationDistanceState = DetonationDistanceStates.Cruising; - break; - case DetonationDistanceStates.Cruising: - - if (Vector3.Distance(futureMissilePosition, futureTargetPosition) < GetBlastRadius() * 10) - { - //We are now close enough to start checking the detonation distance - DetonationDistanceState = DetonationDistanceStates.CheckingProximity; - } - break; - case DetonationDistanceStates.CheckingProximity: - - float optimalDistance = (float)(_DetonationOffset + missileDistancePerFrame.magnitude); - - using (var hitsEnu = Physics.OverlapSphere(vessel.CoM, optimalDistance, 557057).AsEnumerable().GetEnumerator()) - { - while (hitsEnu.MoveNext()) - { - if (hitsEnu.Current == null) continue; - - try - { - Part partHit = hitsEnu.Current.GetComponentInParent(); - - if (partHit?.vessel == vessel) continue; - - Debug.Log("[BDArmory]: Missile proximity sphere hit | Distance overlap = " + optimalDistance + "| Part name = " + partHit.name); - - //We found a hit a different vessel than ours - DetonationDistanceState = DetonationDistanceStates.Detonate; - return; - } - catch - { - // ignored - } - } - } - - break; - } - if (BDArmorySettings.DRAW_DEBUG_LABELS) - { - Debug.Log("[BDArmory]: DetonationDistanceState = : " + DetonationDistanceState); - } - } - } - else - { var targetDistancePerFrame = TargetVelocity * Time.deltaTime; var missileDistancePerFrame = vessel.Velocity() * Time.deltaTime; @@ -1081,32 +969,78 @@ public void CheckDetonationState() break; case DetonationDistanceStates.CheckingProximity: - float optimalDistance = (float)(DetonationDistance + missileDistancePerFrame.magnitude); - - using (var hitsEnu = Physics.OverlapSphere(vessel.CoM, optimalDistance, 557057).AsEnumerable().GetEnumerator()) + if (DetonationDistance == 0) { - while (hitsEnu.MoveNext()) + if (weaponClass == WeaponClasses.Bomb) return; + + if (TimeIndex > 1f && vessel.srfSpeed > part.crashTolerance) { - if (hitsEnu.Current == null) continue; + //Vector3 floatingorigin_current = FloatingOrigin.Offset; + + Ray rayFuturePosition = new Ray(vessel.CoM, futureMissilePosition); - try - { - Part partHit = hitsEnu.Current.GetComponentInParent(); + var hitsFuture = Physics.RaycastAll(rayFuturePosition, (float) missileDistancePerFrame.magnitude, 557057).AsEnumerable(); - if (partHit?.vessel == vessel) continue; + using (var hitsEnu = hitsFuture.GetEnumerator()) + { + while (hitsEnu.MoveNext()) + { + RaycastHit hit = hitsEnu.Current; - Debug.Log("[BDArmory]: Missile proximity sphere hit | Distance overlap = " + optimalDistance + "| Part name = " + partHit.name); + try + { + var hitPart = hit.collider.gameObject.GetComponentInParent(); - //We found a hit a different vessel than ours - DetonationDistanceState = DetonationDistanceStates.Detonate; - return; + if (hitPart?.vessel != SourceVessel) + { + //We found a hit to other vessel + vessel.transform.position = hit.point; + DetonationDistanceState = DetonationDistanceStates.Detonate; + return; + } + } + catch + { + // ignored + } + } } - catch + } + + previousPos = part.transform.position; + + } + else + { + float optimalDistance = (float)(DetonationDistance + missileDistancePerFrame.magnitude); + + using (var hitsEnu = Physics.OverlapSphere(vessel.CoM, optimalDistance, 557057).AsEnumerable().GetEnumerator()) + { + while (hitsEnu.MoveNext()) { - // ignored + if (hitsEnu.Current == null) continue; + + try + { + Part partHit = hitsEnu.Current.GetComponentInParent(); + + if (partHit?.vessel == vessel) continue; + + Debug.Log("[BDArmory]: Missile proximity sphere hit | Distance overlap = " + optimalDistance + "| Part name = " + partHit.name); + + //We found a hit a different vessel than ours + DetonationDistanceState = DetonationDistanceStates.Detonate; + return; + } + catch + { + // ignored + } } } - } + } + + break; } @@ -1115,7 +1049,7 @@ public void CheckDetonationState() { Debug.Log("[BDArmory]: DetonationDistanceState = : " + DetonationDistanceState); } - } + } protected void SetInitialDetonationDistance() From a212d2844377d58d3f7cece6d5afe4bf5fe42053 Mon Sep 17 00:00:00 2001 From: Gedas Date: Fri, 14 Sep 2018 03:08:49 +0300 Subject: [PATCH 57/72] fix bullet distribution --- BDArmory/Misc/VectorUtils.cs | 28 ++++++++++------------------ BDArmory/Modules/ModuleWeapon.cs | 4 ++-- 2 files changed, 12 insertions(+), 20 deletions(-) diff --git a/BDArmory/Misc/VectorUtils.cs b/BDArmory/Misc/VectorUtils.cs index 047e41cca..fa722ecd1 100644 --- a/BDArmory/Misc/VectorUtils.cs +++ b/BDArmory/Misc/VectorUtils.cs @@ -5,6 +5,8 @@ namespace BDArmory.Misc { public static class VectorUtils { + private static System.Random RandomGen = new System.Random(); + /// Right compared to fromDirection, make sure it's not orthogonal to toDirection, or you'll get unstable signs public static float SignedAngle(Vector3 fromDirection, Vector3 toDirection, Vector3 referenceRight) { @@ -89,27 +91,17 @@ public static Vector3 GaussianDirectionDeviation(Vector3 direction, float standa } /// Random float distributed with an approximated standard normal distribution - /// https://www.johndcook.com/blog/csharp_phi/ + /// https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform /// Note a standard normal variable is technically unbounded public static float Gaussian() { - const float a1 = 0.254829592f; - const float a2 = -0.284496736f; - const float a3 = 1.421413741f; - const float a4 = -1.453152027f; - const float a5 = 1.061405429f; - const float p = 0.3275911f; - const float invsqrt2 = 0.70710678118654752440084436210485f; - - float x = UnityEngine.Random.Range(-invsqrt2, invsqrt2); - int sign = Math.Sign(x); - x = Mathf.Abs(x); - - // A&S formula 7.1.26 - float t = 1f / (1f + p * x); - float y = 1f - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * Mathf.Exp(-x * x); - - return 0.5f * (1f + sign * y); + // Technically this will raise an exception if the first random produces a zero + try { + return Mathf.Sqrt(-2 * Mathf.Log(UnityEngine.Random.value)) * Mathf.Cos(Mathf.PI * UnityEngine.Random.value); + } + catch (Exception) { // I have no idea what exception Mathf.Log raises when it gets a zero + return 0; + } } /// diff --git a/BDArmory/Modules/ModuleWeapon.cs b/BDArmory/Modules/ModuleWeapon.cs index b9248ec29..a709f0c4f 100644 --- a/BDArmory/Modules/ModuleWeapon.cs +++ b/BDArmory/Modules/ModuleWeapon.cs @@ -248,7 +248,7 @@ public string GetMissileType() [KSPField] public float roundsPerMinute = 850; //rate of fire [KSPField] - public float maxDeviation = 1; //inaccuracy standard deviation in degrees + public float maxDeviation = 1; //inaccuracy two standard deviations in degrees (two because backwards compatibility :) [KSPField] public float maxEffectiveDistance = 2500; //used by AI to select appropriate weapon [KSPField] @@ -1072,7 +1072,7 @@ private void Fire() timeFired = Time.time; Vector3 firedVelocity = - VectorUtils.GaussianDirectionDeviation(fireTransform.forward, maxDeviation) * bulletVelocity; + VectorUtils.GaussianDirectionDeviation(fireTransform.forward, maxDeviation / 2) * bulletVelocity; firedBullet.transform.position += (part.rb.velocity + Krakensbane.GetFrameVelocityV3f()) * Time.fixedDeltaTime; pBullet.currentVelocity = (part.rb.velocity + Krakensbane.GetFrameVelocityV3f()) + firedVelocity; // use the real velocity, w/o offloading From 87538b4cf701b9aec10de13643afc48b644aad0d Mon Sep 17 00:00:00 2001 From: Gedas Date: Fri, 14 Sep 2018 03:13:15 +0300 Subject: [PATCH 58/72] stop throwing "module not found" errors every time a part is damaged --- BDArmory.Core/Extension/PartExtensions.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BDArmory.Core/Extension/PartExtensions.cs b/BDArmory.Core/Extension/PartExtensions.cs index 5094cf07d..3dbd409fa 100644 --- a/BDArmory.Core/Extension/PartExtensions.cs +++ b/BDArmory.Core/Extension/PartExtensions.cs @@ -300,7 +300,6 @@ public static float GetVolume(this Part part) public static Vector3 GetSize(this Part part) { - var tweakScaleModule = part.Modules["TweakScale"]; var size = part.GetComponentInChildren().mesh.bounds.size; @@ -310,8 +309,9 @@ public static Vector3 GetSize(this Part part) } float scaleMultiplier = 1f; - if (tweakScaleModule != null) + if (part.Modules.Contains("TweakScale")) { + var tweakScaleModule = part.Modules["TweakScale"]; scaleMultiplier = tweakScaleModule.Fields["currentScale"].GetValue(tweakScaleModule) / tweakScaleModule.Fields["defaultScale"].GetValue(tweakScaleModule); } From cdebf9d2a6fc34a3f088725b61f295f0813eb17b Mon Sep 17 00:00:00 2001 From: Gedas Date: Fri, 14 Sep 2018 03:56:00 +0300 Subject: [PATCH 59/72] Permit firing between frames, show rpm multiplied by fire transforms --- BDArmory/Modules/ModuleWeapon.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/BDArmory/Modules/ModuleWeapon.cs b/BDArmory/Modules/ModuleWeapon.cs index a709f0c4f..f1df5c56f 100644 --- a/BDArmory/Modules/ModuleWeapon.cs +++ b/BDArmory/Modules/ModuleWeapon.cs @@ -932,6 +932,7 @@ private void Fire() { bool effectsShot = false; //Transform[] fireTransforms = part.FindModelTransforms("fireTransform"); + for (float iTime = Mathf.Min(Time.time - timeFired - timeGap, TimeWarp.fixedDeltaTime); iTime >= 0; iTime -= timeGap) for (int i = 0; i < fireTransforms.Length; i++) { //if ((BDArmorySettings.INFINITE_AMMO || part.RequestResource(ammoName, requestResourceAmount) > 0)) @@ -1065,17 +1066,18 @@ private void Fire() pBullet.ballisticCoefficient = bulletBallisticCoefficient; - pBullet.flightTimeElapsed = 0; + pBullet.flightTimeElapsed = iTime; // measure bullet lifetime in time rather than in distance, because distances get very relative in orbit pBullet.timeToLiveUntil = Mathf.Max(maxTargetingRange, maxEffectiveDistance) / bulletVelocity * 1.1f + Time.time; - timeFired = Time.time; + timeFired = Time.time - iTime; Vector3 firedVelocity = VectorUtils.GaussianDirectionDeviation(fireTransform.forward, maxDeviation / 2) * bulletVelocity; - firedBullet.transform.position += (part.rb.velocity + Krakensbane.GetFrameVelocityV3f()) * Time.fixedDeltaTime; pBullet.currentVelocity = (part.rb.velocity + Krakensbane.GetFrameVelocityV3f()) + firedVelocity; // use the real velocity, w/o offloading + firedBullet.transform.position += (part.rb.velocity + Krakensbane.GetFrameVelocityV3f()) * Time.fixedDeltaTime + + pBullet.currentVelocity * iTime; pBullet.sourceVessel = vessel; pBullet.bulletTexturePath = bulletTexturePath; @@ -2287,7 +2289,7 @@ public override string GetInfo() } else { - output.AppendLine($"Rounds Per Minute: {roundsPerMinute}"); + output.AppendLine($"Rounds Per Minute: {roundsPerMinute * (fireTransforms?.Length ?? 1)}"); output.AppendLine($"Ammunition: {ammoName}"); output.AppendLine($"Bullet type: {bulletType}"); output.AppendLine($"Bullet mass: {Math.Round(binfo.bulletMass,2)} kg"); From 254486fc433abea5d808afe4e5b2523da7fb097a Mon Sep 17 00:00:00 2001 From: TheDogKSP Date: Sun, 23 Sep 2018 13:57:28 +0200 Subject: [PATCH 60/72] fix csv export show all parts again --- BDArmory/Misc/BDAEditorCategory.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BDArmory/Misc/BDAEditorCategory.cs b/BDArmory/Misc/BDAEditorCategory.cs index f620aa513..3229bba86 100644 --- a/BDArmory/Misc/BDAEditorCategory.cs +++ b/BDArmory/Misc/BDAEditorCategory.cs @@ -124,14 +124,14 @@ void dumpParts() ); fileradars.WriteLine("NAME;TITLE;AUTHOR;MANUFACTURER;PART_MASS;PART_COST;PART_CRASHTOLERANCE;PART_MAXTEMP;radar_name;rwrThreatType;omnidirectional;directionalFieldOfView;boresightFOV;" + "scanRotationSpeed;lockRotationSpeed;lockRotationAngle;showDirectionWhileScan;multiLockFOV;lockAttemptFOV;canScan;canLock;canTrackWhileScan;canRecieveRadarData;" + - "DEPRECATED_minSignalThreshold;DEPRECATED_minLockedSignalThreshold;maxLocks;radarGroundClutterFactor;radarDetectionCurve;radarLockTrackCurve" + "maxLocks;radarGroundClutterFactor;radarDetectionCurve;radarLockTrackCurve" ); filejammers.WriteLine("NAME;TITLE;AUTHOR;MANUFACTURER;PART_MASS;PART_COST;PART_CRASHTOLERANCE;PART_MAXTEMP;alwaysOn;rcsReduction;rcsReducationFactor;lockbreaker;lockbreak_strength;jammerStrength"); Debug.Log("Dumping parts..."); // 3. iterate weapons and write out fields - foreach (var item in availableParts) + foreach (var item in PartLoader.LoadedPartsList) { weapon = null; From 44da02172b3124dcb3ca874ea0885b987f5bddcd Mon Sep 17 00:00:00 2001 From: Duck Date: Sun, 14 Oct 2018 19:36:15 +0800 Subject: [PATCH 61/72] Fix issue #580 The new BDAEditorCategory module just read the English version of part's manufacturer. Revert it to English version simply fixes the issue. --- .../GameData/BDArmory/Localization/localization-zh-cn.cfg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BDArmory/Distribution/GameData/BDArmory/Localization/localization-zh-cn.cfg b/BDArmory/Distribution/GameData/BDArmory/Localization/localization-zh-cn.cfg index 77484d22b..8c9d23f5d 100644 --- a/BDArmory/Distribution/GameData/BDArmory/Localization/localization-zh-cn.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/Localization/localization-zh-cn.cfg @@ -6,7 +6,7 @@ #loc_BDArmory_agent_title = 巴哈姆特动力 #loc_BDArmory_agent_description = 军用武器与弹药业界的领军品牌。该公司同事也和太空计划有长期合作关系,为其提供独特的工程解决方案。 - #loc_BDArmory_part_manufacturer = 巴哈姆特动力 + #loc_BDArmory_part_manufacturer = Bahamuto Dynamics //Vulcan Turret #loc_BDArmory_part_bahaGatlingGun_title = “火神”炮塔 From d22844063c7f2c09cf232bcdf01e1e9212763939 Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Mon, 15 Oct 2018 20:35:04 +0200 Subject: [PATCH 62/72] moving collsission checks to fixeddelta time --- BDArmory/Modules/BDModularGuidance.cs | 1 + BDArmory/Modules/MissileBase.cs | 26 ++++++++++++++------------ 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/BDArmory/Modules/BDModularGuidance.cs b/BDArmory/Modules/BDModularGuidance.cs index 88179489c..9423fae80 100644 --- a/BDArmory/Modules/BDModularGuidance.cs +++ b/BDArmory/Modules/BDModularGuidance.cs @@ -153,6 +153,7 @@ public override void OnFixedUpdate() if (HasFired && !HasExploded) { UpdateGuidance(); + CheckDetonationState(); CheckDetonationDistance(); CheckDelayedFired(); CheckNextStage(); diff --git a/BDArmory/Modules/MissileBase.cs b/BDArmory/Modules/MissileBase.cs index 7acebd68e..02d1bc7d8 100644 --- a/BDArmory/Modules/MissileBase.cs +++ b/BDArmory/Modules/MissileBase.cs @@ -919,17 +919,19 @@ public void CheckDetonationState() //Guard clauses if (!TargetAcquired) return; - var targetDistancePerFrame = TargetVelocity * Time.deltaTime; - var missileDistancePerFrame = vessel.Velocity() * Time.deltaTime; + var targetDistancePerFrame = TargetVelocity * Time.fixedDeltaTime; + var missileDistancePerFrame = vessel.Velocity() * Time.fixedDeltaTime; var futureTargetPosition = (TargetPosition + targetDistancePerFrame); var futureMissilePosition = (vessel.CoM + missileDistancePerFrame); + var relativeSpeed = (TargetVelocity - vessel.Velocity()).magnitude * Time.fixedDeltaTime; + switch (DetonationDistanceState) { case DetonationDistanceStates.NotSafe: //Lets check if we are at a safe distance from the source vessel - Ray raySourceVessel = new Ray(futureMissilePosition, SourceVessel.CoM + SourceVessel.Velocity() * Time.deltaTime); + Ray raySourceVessel = new Ray(futureMissilePosition, SourceVessel.CoM + SourceVessel.Velocity() * Time.fixedDeltaTime); var hits = Physics.RaycastAll(raySourceVessel, GetBlastRadius() * 2, 557057).AsEnumerable(); @@ -991,14 +993,14 @@ public void CheckDetonationState() { var hitPart = hit.collider.gameObject.GetComponentInParent(); - if (hitPart?.vessel != SourceVessel) - { - //We found a hit to other vessel - vessel.transform.position = hit.point; - DetonationDistanceState = DetonationDistanceStates.Detonate; - return; - } - } + if (hitPart?.vessel != SourceVessel) + { + //We found a hit to other vessel + vessel.transform.position = hit.point; + DetonationDistanceState = DetonationDistanceStates.Detonate; + return; + } + } catch { // ignored @@ -1012,7 +1014,7 @@ public void CheckDetonationState() } else { - float optimalDistance = (float)(DetonationDistance + missileDistancePerFrame.magnitude); + float optimalDistance = (float)(Math.Max(DetonationDistance, relativeSpeed)); using (var hitsEnu = Physics.OverlapSphere(vessel.CoM, optimalDistance, 557057).AsEnumerable().GetEnumerator()) { From e26547da4df34617ee8399d74a4529749c2b589b Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Sat, 20 Oct 2018 12:40:42 +0200 Subject: [PATCH 63/72] fixing issue with stageIcons in KSP 1.4.5 --- BDArmory/Modules/ModuleWeapon.cs | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/BDArmory/Modules/ModuleWeapon.cs b/BDArmory/Modules/ModuleWeapon.cs index f1df5c56f..36efe859a 100644 --- a/BDArmory/Modules/ModuleWeapon.cs +++ b/BDArmory/Modules/ModuleWeapon.cs @@ -522,11 +522,25 @@ IEnumerator FireHoldRoutine(KSPActionGroup group) #region KSP Events + public override void OnAwake() + { + base.OnAwake(); + + part.stagingIconAlwaysShown = true; + this.part.stackIconGrouping = StackIconGrouping.SAME_TYPE; + } + public override void OnStart(StartState state) { base.OnStart(state); - ParseWeaponType(); + part.stagingIconAlwaysShown = true; + this.part.stackIconGrouping = StackIconGrouping.SAME_TYPE; + + GameEvents.onVesselSwitching.Add(ReloadIconOnVesselSwitch); + + + ParseWeaponType(); // extension for feature_engagementenvelope InitializeEngagementRange(0, maxEffectiveDistance); @@ -687,6 +701,15 @@ public override void OnStart(StartState state) BDArmorySetup.OnVolumeChange += UpdateVolume; } + private void ReloadIconOnVesselSwitch(Vessel data0, Vessel data1) + { + if (part.vessel.isActiveVessel) + { + part.stagingIconAlwaysShown = true; + this.part.stackIconGrouping = StackIconGrouping.SAME_TYPE; + } + } + void OnDestroy() { BDArmorySetup.OnVolumeChange -= UpdateVolume; @@ -768,11 +791,6 @@ void FixedUpdate() return; } - if (part.stackIcon.StageIcon == null) - { - part.stackIcon.CreateIcon(); - } - if (vessel.isActiveVessel) { From eb30ab54d3cf5b1b18aa2bed2de63b60ec7342ed Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Sun, 21 Oct 2018 00:08:33 +0200 Subject: [PATCH 64/72] Improving performance of FX limiting the number of effects running in parallel and the time --- BDArmory/FX/BulletHitFX.cs | 11 ++++++++--- BDArmory/FX/ExplosionFX.cs | 8 +++++++- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/BDArmory/FX/BulletHitFX.cs b/BDArmory/FX/BulletHitFX.cs index 91a792a24..6d14d7a2f 100644 --- a/BDArmory/FX/BulletHitFX.cs +++ b/BDArmory/FX/BulletHitFX.cs @@ -20,7 +20,8 @@ public class BulletHitFX : MonoBehaviour public GameObject bulletHoleDecalPrefab; public static ObjectPool decalPool_small; public static ObjectPool decalPool_large; - public static Dictionary> PartsOnFire = new Dictionary>(); + public static Dictionary> PartsOnFire = new Dictionary>(); + public static Queue HitsLoaded = new Queue(); public static int MaxFiresPerVessel = 3; public static float FireLifeTimeInSeconds = 5f; @@ -124,6 +125,7 @@ private static bool CanFlamesBeAttached(Part hitPart) void Start() { + HitsLoaded.Enqueue(this); if (decalPool_large == null || decalPool_small == null) SetupShellPool(); @@ -192,8 +194,9 @@ void Update() pe.Dispose(); disabled = true; } - if (Time.time - startTime > 2f) + if (Time.time - startTime > 0.3f) { + HitsLoaded.Dequeue(); Destroy(gameObject); } } @@ -202,7 +205,9 @@ void Update() public static void CreateBulletHit(Part hitPart,Vector3 position, RaycastHit hit, Vector3 normalDirection, bool ricochet,float caliber,float penetrationfactor) { - + if (HitsLoaded.Count > 5) return; + + if (decalPool_large == null || decalPool_small == null) SetupShellPool(); diff --git a/BDArmory/FX/ExplosionFX.cs b/BDArmory/FX/ExplosionFX.cs index 40073dcb7..862fa9b6e 100644 --- a/BDArmory/FX/ExplosionFX.cs +++ b/BDArmory/FX/ExplosionFX.cs @@ -39,8 +39,11 @@ public class ExplosionFx : MonoBehaviour private float particlesMaxEnergy; + public static Queue ExplosionsLoaded = new Queue(); + private void Start() { + ExplosionsLoaded.Enqueue(this); StartTime = Time.time; MaxTime = (Range / ExplosionVelocity)*3f; CalculateBlastEvents(); @@ -234,13 +237,15 @@ public void Update() pe.Dispose(); } - if (ExplosionEvents.Count == 0 && TimeIndex > Math.Max(MaxTime, particlesMaxEnergy)) + if (ExplosionEvents.Count == 0 && TimeIndex > 2f*MaxTime) { if (BDArmorySettings.DRAW_DEBUG_LABELS) { Debug.Log( "[BDArmory]:Explosion Finished"); } + + ExplosionsLoaded.Dequeue(); Destroy(gameObject); return; } @@ -375,6 +380,7 @@ private void ExecutePartBlastEvent(PartBlastHitEvent eventToExecute) public static void CreateExplosion(Vector3 position, float tntMassEquivalent, string explModelPath, string soundPath, bool isMissile = true,float caliber = 0, Part explosivePart = null, Vector3 direction = default(Vector3)) { + if (ExplosionsLoaded.Count > 5) return; var go = GameDatabase.Instance.GetModel(explModelPath); var soundClip = GameDatabase.Instance.GetAudioClip(soundPath); From df124d3a4aab13ab8b09b87e4e0e1b9ab8d676a7 Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Sun, 21 Oct 2018 00:09:07 +0200 Subject: [PATCH 65/72] controlling exceptions --- BDArmory/Modules/ModuleWeapon.cs | 3 +++ BDArmory/UI/BDGUIUtils.cs | 3 +++ 2 files changed, 6 insertions(+) diff --git a/BDArmory/Modules/ModuleWeapon.cs b/BDArmory/Modules/ModuleWeapon.cs index 36efe859a..977a69237 100644 --- a/BDArmory/Modules/ModuleWeapon.cs +++ b/BDArmory/Modules/ModuleWeapon.cs @@ -703,6 +703,9 @@ public override void OnStart(StartState state) private void ReloadIconOnVesselSwitch(Vessel data0, Vessel data1) { + if (part == null) return; + if (part.vessel == null) return; + if (part.vessel.isActiveVessel) { part.stagingIconAlwaysShown = true; diff --git a/BDArmory/UI/BDGUIUtils.cs b/BDArmory/UI/BDGUIUtils.cs index b98299f56..f25ffd63b 100644 --- a/BDArmory/UI/BDGUIUtils.cs +++ b/BDArmory/UI/BDGUIUtils.cs @@ -61,6 +61,9 @@ public static bool WorldToGUIPos(Vector3 worldPos, out Vector2 guiPos) public static void DrawLineBetweenWorldPositions(Vector3 worldPosA, Vector3 worldPosB, float width, Color color) { Camera cam = GetMainCamera(); + + if (cam == null) return; + GUI.matrix = Matrix4x4.identity; bool aBehind = false; From 5c9b638e8373385fefef159455979bf22bbcb6ca Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Sun, 21 Oct 2018 19:18:35 +0200 Subject: [PATCH 66/72] better NotSafe check for missiles --- BDArmory/Modules/MissileBase.cs | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/BDArmory/Modules/MissileBase.cs b/BDArmory/Modules/MissileBase.cs index 02d1bc7d8..311b2be36 100644 --- a/BDArmory/Modules/MissileBase.cs +++ b/BDArmory/Modules/MissileBase.cs @@ -931,21 +931,17 @@ public void CheckDetonationState() { case DetonationDistanceStates.NotSafe: //Lets check if we are at a safe distance from the source vessel - Ray raySourceVessel = new Ray(futureMissilePosition, SourceVessel.CoM + SourceVessel.Velocity() * Time.fixedDeltaTime); - var hits = Physics.RaycastAll(raySourceVessel, GetBlastRadius() * 2, 557057).AsEnumerable(); - - using (var hitsEnu = hits.GetEnumerator()) + using (var hitsEnu = Physics.OverlapSphere(futureMissilePosition, GetBlastRadius() * 3f, 557057).AsEnumerable().GetEnumerator()) { while (hitsEnu.MoveNext()) { - RaycastHit hit = hitsEnu.Current; - + if (hitsEnu.Current == null) continue; try { - var hitPart = hit.collider.gameObject.GetComponentInParent(); + Part partHit = hitsEnu.Current.GetComponentInParent(); - if (hitPart?.vessel == SourceVessel) + if (partHit?.vessel == SourceVessel) { //We found a hit to the vessel return; @@ -958,7 +954,8 @@ public void CheckDetonationState() } } - //We are safe and we can continue with the next state + //We are safe and we can continue with the cruising phase + DetonationDistanceState = DetonationDistanceStates.Cruising; break; case DetonationDistanceStates.Cruising: @@ -1026,7 +1023,7 @@ public void CheckDetonationState() { Part partHit = hitsEnu.Current.GetComponentInParent(); - if (partHit?.vessel == vessel) continue; + if (partHit?.vessel == vessel || partHit?.vessel == SourceVessel) continue; Debug.Log("[BDArmory]: Missile proximity sphere hit | Distance overlap = " + optimalDistance + "| Part name = " + partHit.name); @@ -1042,8 +1039,6 @@ public void CheckDetonationState() } } - - break; } From b5234f00ddaef345ec53e7abfed0e0480763d82c Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Wed, 31 Oct 2018 23:44:25 +0100 Subject: [PATCH 67/72] fixing friendly heat seekers error #586 --- BDArmory/Modules/MissileBase.cs | 2 +- BDArmory/Modules/MissileFire.cs | 2 +- BDArmory/Modules/MissileLauncher.cs | 2 +- BDArmory/UI/BDATargetManager.cs | 8 +++++++- 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/BDArmory/Modules/MissileBase.cs b/BDArmory/Modules/MissileBase.cs index 311b2be36..dcd9a35c0 100644 --- a/BDArmory/Modules/MissileBase.cs +++ b/BDArmory/Modules/MissileBase.cs @@ -359,7 +359,7 @@ protected void UpdateHeatTarget() 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); + heatTarget = BDATargetManager.GetHeatTarget(lookRay, lockedSensorFOV / 2, heatThreshold, allAspect, SourceVessel.gameObject.GetComponent()); if (heatTarget.exists) { diff --git a/BDArmory/Modules/MissileFire.cs b/BDArmory/Modules/MissileFire.cs index eb2c9bb6c..b51654400 100644 --- a/BDArmory/Modules/MissileFire.cs +++ b/BDArmory/Modules/MissileFire.cs @@ -3802,7 +3802,7 @@ void SearchForHeatTarget() heatTarget.predictedPosition - CurrentMissile.MissileReferenceTransform.position : CurrentMissile.GetForwardTransform(); - heatTarget = BDATargetManager.GetHeatTarget(new Ray(CurrentMissile.MissileReferenceTransform.position + (50 * CurrentMissile.GetForwardTransform()), direction), scanRadius, CurrentMissile.heatThreshold, CurrentMissile.allAspect); + heatTarget = BDATargetManager.GetHeatTarget(new Ray(CurrentMissile.MissileReferenceTransform.position + (50 * CurrentMissile.GetForwardTransform()), direction), scanRadius, CurrentMissile.heatThreshold, CurrentMissile.allAspect, this); } } diff --git a/BDArmory/Modules/MissileLauncher.cs b/BDArmory/Modules/MissileLauncher.cs index bccddaa83..234277a13 100644 --- a/BDArmory/Modules/MissileLauncher.cs +++ b/BDArmory/Modules/MissileLauncher.cs @@ -1091,7 +1091,7 @@ private void UpdateTerminalGuidance() { case TargetingModes.Heat: // get ground heat targets - heatTarget = BDATargetManager.GetHeatTarget(new Ray(transform.position + (50 * GetForwardTransform()), TargetPosition - GetForwardTransform()), terminalGuidanceDistance, heatThreshold, true, null, true); + heatTarget = BDATargetManager.GetHeatTarget(new Ray(transform.position + (50 * GetForwardTransform()), TargetPosition - GetForwardTransform()), terminalGuidanceDistance, heatThreshold, true, SourceVessel.gameObject.GetComponent(), true); if (heatTarget.exists) { if (BDArmorySettings.DRAW_DEBUG_LABELS) diff --git a/BDArmory/UI/BDATargetManager.cs b/BDArmory/UI/BDATargetManager.cs index 113a534cb..f2fc1617d 100644 --- a/BDArmory/UI/BDATargetManager.cs +++ b/BDArmory/UI/BDATargetManager.cs @@ -346,7 +346,13 @@ public static TargetSignatureData GetHeatTarget(Ray ray, float scanRadius, float } } - + if (mf != null && tInfo != null) + { + if (BoolToTeam(mf.team) == tInfo.team) + { + continue; + } + } float angle = Vector3.Angle(vessel.CoM-ray.origin, ray.direction); if(angle < scanRadius) { From fec87142d3c6d67f247f3a8783c181073850e9a3 Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Sun, 4 Nov 2018 20:19:11 +0100 Subject: [PATCH 68/72] Fixing bug where a missile is detecting the same missile as enemy vessel --- BDArmory/Modules/MissileBase.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BDArmory/Modules/MissileBase.cs b/BDArmory/Modules/MissileBase.cs index dcd9a35c0..8fcad61f9 100644 --- a/BDArmory/Modules/MissileBase.cs +++ b/BDArmory/Modules/MissileBase.cs @@ -990,7 +990,7 @@ public void CheckDetonationState() { var hitPart = hit.collider.gameObject.GetComponentInParent(); - if (hitPart?.vessel != SourceVessel) + if (hitPart?.vessel != SourceVessel && hitPart?.vessel != vessel ) { //We found a hit to other vessel vessel.transform.position = hit.point; From 89311d9171dd50435ea7fce8af40284602465fa4 Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Sat, 17 Nov 2018 10:59:10 +0100 Subject: [PATCH 69/72] Fixing roll correction for modular missiles --- BDArmory/Modules/BDModularGuidance.cs | 44 +++++++++++++++++++++------ BDArmory/Modules/MissileBase.cs | 4 +-- 2 files changed, 36 insertions(+), 12 deletions(-) diff --git a/BDArmory/Modules/BDModularGuidance.cs b/BDArmory/Modules/BDModularGuidance.cs index 9423fae80..74755d358 100644 --- a/BDArmory/Modules/BDModularGuidance.cs +++ b/BDArmory/Modules/BDModularGuidance.cs @@ -9,6 +9,7 @@ using KSP.UI.Screens; using UniLinq; using UnityEngine; +using VehiclePhysics; namespace BDArmory.Modules { @@ -85,6 +86,12 @@ public class BDModularGuidance : MissileBase private float rollError; private bool _minSpeedAchieved = false; + private double lastRollAngle; + private double angularVelocity; + private double angularAcceleration; + private double lasAngularVelocity + ; + #endregion public TransformAxisVectors ForwardTransformAxis { get; set; } @@ -689,31 +696,48 @@ public void GuidanceSteer(FlightCtrlState s) if (RollCorrection) { - s.roll = GetRoll(); + SetRoll(); + s.roll = Roll; } } s.mainThrottle = Throttle; } } - - private float GetRoll() + private void SetRoll() { - Vector3 rollA = this.initialMissileForward; - Vector3 rollB = Vector3.ProjectOnPlane(vessel.transform.forward, this.initialMissileRollPlane).normalized; + var vesselTransform = vessel.transform.position; + + Vector3 gravityVector = FlightGlobals.getGeeForceAtPosition(vesselTransform).normalized; + Vector3 rollVessel = -vessel.transform.right.normalized; + + var currentAngle = Vector3.SignedAngle(rollVessel, gravityVector,Vector3.Cross(rollVessel, gravityVector) ) - 90f; - var angle = Vector3.Angle(rollA, rollB); + debugString.Append($"Roll angle: {currentAngle}"); + debugString.Append(Environment.NewLine); + this.angularVelocity = currentAngle - this.lastRollAngle; + //this.angularAcceleration = angularVelocity - this.lasAngularVelocity; - var crossErrorAngle = Vector3.Cross(rollA, rollB); + var futureAngle = currentAngle + angularVelocity / Time.fixedDeltaTime * 1f; - if (crossErrorAngle.y > 0) + debugString.Append($"future Roll angle: {futureAngle}"); + + if (futureAngle > 0.5f || currentAngle > 0.5f) + { + this.Roll = Mathf.Clamp(Roll + 0.001f, 0, 1f); + } + else if (futureAngle < -0.5f || currentAngle < -0.5f) { - angle = angle * -1; + this.Roll = Mathf.Clamp(Roll - 0.001f, -1f, 0f); } + debugString.Append($"Roll value: {this.Roll}"); - return angle * (1f / -180f); + lastRollAngle = currentAngle; + //lasAngularVelocity = angularVelocity; } + public float Roll { get; set; } + private Vector3 BallisticGuidance() { return CalculateAGMBallisticGuidance(this, TargetPosition); diff --git a/BDArmory/Modules/MissileBase.cs b/BDArmory/Modules/MissileBase.cs index 8fcad61f9..a9947d0b1 100644 --- a/BDArmory/Modules/MissileBase.cs +++ b/BDArmory/Modules/MissileBase.cs @@ -770,7 +770,7 @@ protected void UpdateAntiRadiationTarget() } } - public void DrawDebugLine(Vector3 start, Vector3 end) + public void DrawDebugLine(Vector3 start, Vector3 end,Color color = default(Color)) { if (BDArmorySettings.DRAW_DEBUG_LINES) { @@ -778,7 +778,7 @@ public void DrawDebugLine(Vector3 start, Vector3 end) { LR = gameObject.AddComponent(); LR.material = new Material(Shader.Find("KSP/Emissive/Diffuse")); - LR.material.SetColor("_EmissiveColor", Color.red); + LR.material.SetColor("_EmissiveColor", color); } else { From 006fc305ff163c49a78f2199e43ce86c094a053a Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Sat, 17 Nov 2018 10:59:38 +0100 Subject: [PATCH 70/72] adding float to atm density --- BDArmory.Core/Extension/VesselExtensions.cs | 2 +- BDArmory/BDArmory.sln | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/BDArmory.Core/Extension/VesselExtensions.cs b/BDArmory.Core/Extension/VesselExtensions.cs index 2bb25f00b..d7bb41c37 100644 --- a/BDArmory.Core/Extension/VesselExtensions.cs +++ b/BDArmory.Core/Extension/VesselExtensions.cs @@ -21,7 +21,7 @@ public static bool InOrbit(this Vessel v) public static bool InVacuum(this Vessel v) { - return v.atmDensity <= 0.001; + return v.atmDensity <= 0.001f; } public static Vector3d Velocity(this Vessel v) diff --git a/BDArmory/BDArmory.sln b/BDArmory/BDArmory.sln index 9edac5287..197553288 100644 --- a/BDArmory/BDArmory.sln +++ b/BDArmory/BDArmory.sln @@ -1,7 +1,6 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 -VisualStudioVersion = 15.0.26730.16 VisualStudioVersion = 15.0.26730.8 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BDArmory", "BDArmory.csproj", "{D86F2003-1724-4F4C-BB5A-B0109CB16F35}" @@ -37,7 +36,6 @@ Global HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {EF436DDF-5293-4F33-9859-AA8492B14669} SolutionGuid = {A3A10DCC-85B5-49BC-8AAC-5547E4143101} EndGlobalSection EndGlobal From b1b7b8c002b6301226140c602722449c7b8fd717 Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Sat, 17 Nov 2018 11:08:43 +0100 Subject: [PATCH 71/72] Preparing next release --- .../GameData/BDArmory/BDArmory.version | 14 +++++++------- .../Distribution/GameData/BDArmory/ChangeLog.txt | 13 ++++++++++++- BDArmory/Properties/AssemblyInfo.cs | 4 ++-- 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/BDArmory/Distribution/GameData/BDArmory/BDArmory.version b/BDArmory/Distribution/GameData/BDArmory/BDArmory.version index 05068533a..d66b102ec 100644 --- a/BDArmory/Distribution/GameData/BDArmory/BDArmory.version +++ b/BDArmory/Distribution/GameData/BDArmory/BDArmory.version @@ -12,25 +12,25 @@ { "MAJOR":1, "MINOR":2, - "PATCH":2, - "BUILD":2 + "PATCH":3, + "BUILD":0 }, "KSP_VERSION": { "MAJOR":1, - "MINOR":4, - "PATCH":5 + "MINOR":5, + "PATCH":1 }, "KSP_VERSION_MIN": { "MAJOR":1, - "MINOR":4, - "PATCH":3 + "MINOR":5, + "PATCH":1 }, "KSP_VERSION_MAX": { "MAJOR":1, - "MINOR":4, + "MINOR":5, "PATCH":999 } } diff --git a/BDArmory/Distribution/GameData/BDArmory/ChangeLog.txt b/BDArmory/Distribution/GameData/BDArmory/ChangeLog.txt index 8f01ba91e..54c41e97a 100644 --- a/BDArmory/Distribution/GameData/BDArmory/ChangeLog.txt +++ b/BDArmory/Distribution/GameData/BDArmory/ChangeLog.txt @@ -1,4 +1,15 @@ -v1.2.2.2a +v1.2.3 +* NEW FEATURES: + * +* ENHANCEMENTS: +* FIXES + + +v1.2.2.2a +* FIXES +* added in missing high speed missle fix. somehow got lost in the merge migration. + +v1.2.2.2a * FIXES * added in missing high speed missle fix. somehow got lost in the merge migration. diff --git a/BDArmory/Properties/AssemblyInfo.cs b/BDArmory/Properties/AssemblyInfo.cs index c654c2df8..eaeb3f0a0 100644 --- a/BDArmory/Properties/AssemblyInfo.cs +++ b/BDArmory/Properties/AssemblyInfo.cs @@ -18,8 +18,8 @@ // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. -[assembly: AssemblyVersion("1.2.2.2")] -[assembly: AssemblyFileVersion("1.2.2.2")] +[assembly: AssemblyVersion("1.2.3.0")] +[assembly: AssemblyFileVersion("1.2.3.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. From aa1c6d6485a15e9fd21f35c0994a569f0a78654f Mon Sep 17 00:00:00 2001 From: Jesus Rodriguez Valencia Date: Sat, 17 Nov 2018 12:14:06 +0100 Subject: [PATCH 72/72] Changelog update! --- .../GameData/BDArmory/ChangeLog.txt | 38 ++++++++++++++++++- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/BDArmory/Distribution/GameData/BDArmory/ChangeLog.txt b/BDArmory/Distribution/GameData/BDArmory/ChangeLog.txt index 54c41e97a..5cc2c2edd 100644 --- a/BDArmory/Distribution/GameData/BDArmory/ChangeLog.txt +++ b/BDArmory/Distribution/GameData/BDArmory/ChangeLog.txt @@ -1,9 +1,43 @@ v1.2.3 * NEW FEATURES: - * + * Recompiled for KSP 1.5.1 + * EC per shot for energy weapons like Rail guns. #486 + * EMP Weapons logic. + * Modular Missiles: Min speed before guidance trigger, time between stages. + * New High Explosive resource for missiles. + * New smoke model. + * Autopilot: Orbiting direction can be set. + * ENHANCEMENTS: -* FIXES + * Explosive blast forces increased. + * Hitpoints rounding reduced to 100. #432 + * Missiles can be jettisoned using action group #539 + * Max detonation range for air explosive bullets increased from 3500m to 8000m. + * Autopilot improvements: pitchKi has saner values, also steering added. + * Guard mode: Better calculation of missiles away. + * Better bullet distribution. + * FX performance improved limiting number of parallel animations. + * Better checks for missile detonations. +* FIXES + * HE bullets now do less kinetic damage after substracting HE mass + * HitPoints calculations: values remain the same between scenes + * HitPoints calculations: bigger vessels now have more sensible HP values. #477 + * Stop explosions moving across the ground + * Fixed detonation on collision #566 + * CSV parts export now show all parts + * Fixed weapons category due to localization issues. #580 + * Stage icons fixed for KSP 1.5.1 + * Some exceptions controlled + * Heat missiles will not lock friendly vessels. #586 + * Fixed issue where modular missiles were detecting themselves as enemy vessels and detonating. + * Modular Missiles: roll correction fixed. + +* BALANCE + * Bullet mass rebalance for lower calibers #515 + * No damage reductions for lower calibers #515 + * 120mm bullet improvements. +- Thanks to SpannerMoneky, Gedas-S, DoctorDavinci, Kergan, Gomker, PapaJoesSoup, TheDogKSP, Duck1998, and Fitiales for their work on this release! v1.2.2.2a * FIXES