Simplified null or empty check for readability.
Simplified null or empty check for readability.

 Binary files a/Assets/CurseLogo.png and b/Assets/CurseLogo.png differ
 Binary files a/Assets/CurseLogo.psd and b/Assets/CurseLogo.psd differ
  1.0.19.1, 09-11-15
  Added: Key binding editor accessible under 'Settings' on the Build Engineer.
  Added: Added current vessel name readout. (antplant)
  Added: 'Relative Radial Velocity' and 'Time To Rendezvous' readouts. (itwtx)
  Added: Readout help strings. (harryyoung)
  Changed: The 'Torque' value in the editor is now precise to two decimal places.
  Changed: Time formatting reference (Kerbin/Earth) is now based on the in-game setting.
  Changed: Eccentric Anomaly, Mean Anomaly and Mean Anomaly At Epoc now display in degrees rather than radians.
  Fixed: Optimised time formatting. (itwtx)
  Fixed: TimeToAtmosphere checks that the Apoapsis is outside atmosphere. (Kerbas-ad-astra)
  Fixed: Issue with stage priority flow. Caused Rapier calculations to fail if LF and O are drawn from different tanks. (Padishar)
  Fixed: Issue with angle to prograde/retrograde calculations on highly inclined orbits.
  Fixed: Editor input locks not being reset when a scene change is forced (e.g. via Kerbal Construction Time).
  Fixed: Roll axis readout now shows the correct sign.
  Removed: Time Formatter readout as it's not required anymore.
   
  1.0.18.0
  Added: Orbital readouts - "Speed at Periapsis" and "Speed at Apoapsis". (Padishar)
  Added: Manoeuvre readouts - "Post-burn Apoapsis" and "Post-burn Periapsis". (Padishar)
  Added: Orbital readout - "Time to Atmosphere".
  Fixed: Synched the minimum simulation time sliders and stopped them from snapping back after 999ms. (saybur)
  Fixed: Added workaround for the bug in Vessel.horizontalSrfSpeed (Padishar)
  Fixed: Physically insignificant part mass was not being correctly cascaded down through multiple parent parts.
  Fixed: Intake air demand calculation not working.
  Fixed: Some build engineer settings labels do not scale with UI size.
   
  1.0.17.0
  Added: 'Mach Number' readout under the 'Surface' category and included it on the default surface HUD.
  Added: Stock sections in the Flight Engineer can now become HUDs.
  Added 'Thermal' readouts category including:
  Internal Flux
  Convection Flux
  Radiation Flux
  Critical Part Name
  Critical Part Temperature
  Critical Part Skin Temperature
  Critical Part Thermal Percentage of Max Temperature
  Hottest Part Name
  Hottest Part Temperature
  Hottest Part Skin Temperature
  Coldest Part Name
  Coldest Part Temperature
  Coldest Part Skin Temperature
   
  Changed: Mach on the Build Engineer now accurate to 2 decimal places.
  Changed: Max mach in the Build Engineer defaults to 1.00 even when no jet engines are present.
  Changed: Increased eccentricity readout to 5 decimal places.
  Changed: Implemented Sarbian's object pooling.
  Changed: The default selected body is now assigned via 'Planitarium.Home'.
  Changed: HUDs to clamp fully inside the screen instead of allowing them to run off the edge by a certain amount.
  Fixed: Physically insignificant part mass is now associated with the parent part.
  Fixed: Longitude and Latitude readouts now use a KER formatter instead of Squad's incorrect implementation.
  Fixed: Possible null reference in the Rendezvous Processor.
  Fixed: Fairing mass issues introduced with regards to simulation changes.
  Fixed: Use of per-propellant fuel flow mode override.
  Fixed: Burn times calculated for jet engines.
  Fixed: Thrust issues introduced with Sarbian's simulation alterations.
  Fixed: Issue where HUDs positioned close to the top/bottom of the screen could be pushed out of position.
   
  1.0.16.6, 02-05-15
  Fixed: Separately staged fairing mass jettisons are now calculated in the editor.
   
  1.0.16.5, 02-05-2015
  Fixed: Delta-V not being correctly calculated.
  Changed: Editor locking now uses the InputLockManager.
   
  1.0.16.4, 01-05-2015
  Fixed: Physically insignificant part mass is now accounted for.
  Changed: Module mass accounted for as it now makes its way onto the launch pad (e.g. fairings).
   
  Various optimisations:
  Object pooling.
  Removed LINQ expressions.
  Converted foreach to for loops.
   
  1.0.16.3, 27-04-2015
  Fixed issue with the toolbar icons not being created.
  Removed superfluous 'm/s' on the mach slider in the build engineer.
   
  1.0.16.2, 27-04-2015
  Changed the atmospheric slider on the build engineer to default to 0km when changing bodies.
   
  1.0.16.1, 26-04-2015, KSP Build #828
  Merged Sarbian's mach adjustments.
  Fixed bugs relating to thrust and atmosphere/velocity curves.
  Changed the atmospheric slider on the Build Engineer to work based on altitude.
  Changed the atmospheric slider to clamp to the maximum altitude for the selected body.
  Changed the velocity slider to clamp to the maximum usable mach value for the current vessel.
   
  1.0.16.0, 25-04-2015, KSP Build #821
  Fixed errors relating to KSP 1.0 update.
  Fixed fuel simulation to account for new thrust system.
  Fixed atmospheric engines to use the new velocity curve.
  Fixed atmospheric readouts to work with the new atmospheric model.
   
  1.0.15.2, 13-02-2015
  Padishar's Fixes:
  Fixed: Calculation of per-stage resource mass.
   
  1.0.15.1, 13-02-2015
  Rebuild
   
  1.0.15.0, 08-02-2015
  Padishar's Fixes:
  Added: Support KIDS ISP thrust correction.
  Fixed: Log spam for stage priority mode.
  Fixed: Locked tanks preventing simulation from staging.
  Fixed: No flow and all vessel modes to respect flow states.
   
  1.0.14.1, 28-12-2014
  Fixed: Missing texture on the ER-7500 model.
   
1.0.14.0, 28-12-2014 1.0.14.0, 28-12-2014
Added: Career mode that limits the Flight Engineer by: Added: Career mode that limits the Flight Engineer by:
- Requiring an Engineer Kerbal of any level, or placement of an Engineer Chip or ER-7500 part. - Requiring an Engineer Kerbal of any level, or placement of an Engineer Chip or ER-7500 part.
- Tracking station level 3 enables Flight Engineer everywhere. - Tracking station level 3 enables Flight Engineer everywhere.
   
Added: New readouts to the orbital category: Added: New readouts to the orbital category:
- Mean Anomaly at Epoc - Mean Anomaly at Epoc
   
Added: New readouts to the miscellaneous category: Added: New readouts to the miscellaneous category:
- System Time - System Time
   
Added: Editor Overlay Tab's X position is now changable in the BuildOverlay.xml settings file. Added: Editor Overlay Tab's X position is now changable in the BuildOverlay.xml settings file.
Changed: Editor Overlay Tabs start position moved over as to not overlap the parts menu. Changed: Editor Overlay Tabs start position moved over as to not overlap the parts menu.
Fixed: Bug where STAGE_PRIORITY_FLOW resources would not be corrently disabled/enabled. Fixed: Bug where STAGE_PRIORITY_FLOW resources would not be corrently disabled/enabled.
Fixed: Issue with the formatting large Mass and Cost values. Fixed: Issue with the formatting large Mass and Cost values.
Fixed: Error when loading the Engineer7500 part model. Fixed: Error when loading the Engineer7500 part model.
   
1.0.13.1, 16-12-2014 1.0.13.1, 16-12-2014
Fixed: Issue with manoeuvre node readouts and low tier tracking station. Fixed: Issue with manoeuvre node readouts and low tier tracking station.
   
1.0.13.0, 16-12-2014 1.0.13.0, 16-12-2014
Updated for KSP version 0.90 Updated for KSP version 0.90
   
Added: New readouts to the vessel category: Added: New readouts to the vessel category:
- Heading Rate - Heading Rate
- Pitch Rate - Pitch Rate
- Roll Rate - Roll Rate
   
Changed: Simulation to look for fuel lines that use CModuleFuelLine module. Changed: Simulation to look for fuel lines that use CModuleFuelLine module.
Fixed: Editor Overlay now loads the saved visibility value properly. Fixed: Editor Overlay now loads the saved visibility value properly.
Fixed: Altitude (Terrain) will no longer give a reading below sea level. Fixed: Altitude (Terrain) will no longer give a reading below sea level.
Fixed: Suicide burn now uses radar altitude that clamps to sea level. Fixed: Suicide burn now uses radar altitude that clamps to sea level.
   
1.0.12.0, 01-12-2014 1.0.12.0, 01-12-2014
Added: Setting in Build Engineer to enable/disable vectored thrust calculations. Added: Setting in Build Engineer to enable/disable vectored thrust calculations.
Added: Thrust torque field in Build Engineer (courtesy of mic_e). Added: Thrust torque field in Build Engineer (courtesy of mic_e).
Added: New readouts to the vessel category: Added: New readouts to the vessel category:
- Thrust Offset Angle (courtesy of mic_e) - Thrust Offset Angle (courtesy of mic_e)
- Thrust Torque (courtesy of mic_e) - Thrust Torque (courtesy of mic_e)
- Part Count: stage/total - Part Count: stage/total
- Heading - Heading
- Pitch - Pitch
- Roll - Roll
   
Added: New readouts to the surface category: Added: New readouts to the surface category:
- Situation - Situation
   
Added: New readouts to the miscellaneous category: Added: New readouts to the miscellaneous category:
- Vectored Thrust Toggle - Vectored Thrust Toggle
   
Fixed: The category selection within the section editors now do not always reset back to 'Orbital'. Fixed: The category selection within the section editors now do not always reset back to 'Orbital'.
Fixed: Issue where the vessel simulation can sometimes permanently freeze. Fixed: Issue where the vessel simulation can sometimes permanently freeze.
Fixed: Issue where the vessel simulation would not show updates when the delay was set lower than the frame rate. Fixed: Issue where the vessel simulation would not show updates when the delay was set lower than the frame rate.
   
1.0.11.3, 11-11-2014 1.0.11.3, 11-11-2014
Changed: Gravity measurements for Isp to 9.82. Changed: Gravity measurements for Isp to 9.82.
   
1.0.11.2, 10-11-2014 1.0.11.2, 10-11-2014
Changed: Gravity measurements for Isp calculations from 9.81 to 9.8066 for accuracy. Changed: Gravity measurements for Isp calculations from 9.81 to 9.8066 for accuracy.
Changed: Manoeuvre node burn times are now more accurate. Changed: Manoeuvre node burn times are now more accurate.
Fixed: Bug in the manoeuvre node burn time calculations where it was not averaging acceleration correctly. Fixed: Bug in the manoeuvre node burn time calculations where it was not averaging acceleration correctly.
   
1.0.11.1, 07-11-2014 1.0.11.1, 07-11-2014
Changed: Build Engineer now shows stage part count as well as total. Changed: Build Engineer now shows stage part count as well as total.
Changed: Build Overlay Vessel tab data: Changed: Build Overlay Vessel tab data:
DeltaV: stage / total DeltaV: stage / total
Mass: stage / total Mass: stage / total
TWR: start (max) <- shows for bottom stage only. TWR: start (max) <- shows for bottom stage only.
Parts: stage / total Parts: stage / total
   
Fixed: Issue with the vessel tab vanishing from the editor. Fixed: Issue with the vessel tab vanishing from the editor.
   
1.0.11.0, 06-11-2014 1.0.11.0, 06-11-2014
Added: New readouts to the orbital category: Added: New readouts to the orbital category:
- Current SOI - Current SOI
- Manoeuvre Node DeltaV (Prograde) - Manoeuvre Node DeltaV (Prograde)
- Manoeuvre Node DeltaV (Normal) - Manoeuvre Node DeltaV (Normal)
- Manoeuvre Node DeltaV (Radial) - Manoeuvre Node DeltaV (Radial)
- Manoeuvre Node DeltaV (Total) - Manoeuvre Node DeltaV (Total)
- Manoeuvre Node Burn Time - Manoeuvre Node Burn Time
- Manoeuvre Node Half Burn Time - Manoeuvre Node Half Burn Time
- Manoeuvre Node Angle to Prograde - Manoeuvre Node Angle to Prograde
- Manoeuvre Node Angle to Retrograde - Manoeuvre Node Angle to Retrograde
- Time to Manoeuvre Node - Time to Manoeuvre Node
- Time to Manoeuvre Burn - Time to Manoeuvre Burn
   
Added: Readout help strings by ClassyJakey. Added: Readout help strings by ClassyJakey.
   
Fixed: Issue with separators in HUDs. Fixed: Issue with separators in HUDs.
Fixed: Issue with HUDs with backgrounds that have no displayed lines. Fixed: Issue with HUDs with backgrounds that have no displayed lines.
   
Padishar's Fixes: Padishar's Fixes:
Fixed: Issue with multicouplers when attached to parent by bottom node. Fixed: Issue with multicouplers when attached to parent by bottom node.
Fixed: Issue with sepratrons on solid rocket boosters. Fixed: Issue with sepratrons on solid rocket boosters.
   
1.0.10.0, 19-10-2014 1.0.10.0, 19-10-2014
UPDATE NOTICE: If you are updating from a previous version of Kerbal Engineer 1.0, please UPDATE NOTICE: If you are updating from a previous version of Kerbal Engineer 1.0, please
delete the 'Settings/SectionLibrary.xml' file, or remove the old install first. This will delete the 'Settings/SectionLibrary.xml' file, or remove the old install first. This will
reset the Flight Engineer sections to their default values and enable the new HUD functionality. reset the Flight Engineer sections to their default values and enable the new HUD functionality.
   
Added: New reaouts to the vessel category: Added: New reaouts to the vessel category:
- Suicide Burn Altitude (height above terrain to start burn) - Suicide Burn Altitude (height above terrain to start burn)
- Suicide Burn Distance (distance to suicide burn altitude) - Suicide Burn Distance (distance to suicide burn altitude)
- Suicide Burn DeltaV (velocity change required to zero vertical speed) - Suicide Burn DeltaV (velocity change required to zero vertical speed)
*** F5 for safety and use at your own risk! *** *** F5 for safety and use at your own risk! ***
   
Added: HUD type sections to the Flight Engineer. Added: HUD type sections to the Flight Engineer.
Added: HUD sections can have a smoked background for easy visibility. Added: HUD sections can have a smoked background for easy visibility.
Added: 'Switch to Target' button on the Target Selector readout. Added: 'Switch to Target' button on the Target Selector readout.
Changed: The default installed readouts to reduce new user brain melt. Changed: The default installed readouts to reduce new user brain melt.
Fixed: Flight Engineer not saving its hidden state. Fixed: Flight Engineer not saving its hidden state.
Fixed: Bug in the phase angle calculations. Fixed: Bug in the phase angle calculations.
Fixed: Bug where the Build Engineer would stay locked after hiding with the shortcut key. Fixed: Bug where the Build Engineer would stay locked after hiding with the shortcut key.
   
1.0.9.3, 08-10-2014 1.0.9.3, 08-10-2014
Added: Title of the build engineer in compact mode now shows if you are using atmospheric data. Added: Title of the build engineer in compact mode now shows if you are using atmospheric data.
Added: New readout to the surface category: Added: New readout to the surface category:
- Vertical Acceleration - Vertical Acceleration
- Horizontal Acceleration - Horizontal Acceleration
   
Changed: Atmospheric efficiency readout now shows as a percentage. Changed: Atmospheric efficiency readout now shows as a percentage.
Changed: Atmospheric settings (pressure/velocity) in the editor condensed onto a single line. Changed: Atmospheric settings (pressure/velocity) in the editor condensed onto a single line.
Fixed: Bug where the overlays in the editor would stay open outside of parts screen. Fixed: Bug where the overlays in the editor would stay open outside of parts screen.
   
1.0.9.2, 07-10-2014 1.0.9.2, 07-10-2014
Updated for KSP v0.25.0 Updated for KSP v0.25.0
Changed: Prettyfied Latitude and Longitude readouts. Changed: Prettyfied Latitude and Longitude readouts.
Changed: ModuleLandingGear now uses the physical significance flag. Changed: ModuleLandingGear now uses the physical significance flag.
Changed: Updated MiniAVC to 1.0.2.4. Changed: Updated MiniAVC to 1.0.2.4.
   
1.0.9.1, 17-09-2014 1.0.9.1, 17-09-2014
Fixed: Part size bug caused by TweakScale's cost calculator. Fixed: Part size bug caused by TweakScale's cost calculator.
   
1.0.9.0, 15-09-2014 1.0.9.0, 15-09-2014
Added: Build Engineer now also implements the '\' backslash show/hide shortcut. Added: Build Engineer now also implements the '\' backslash show/hide shortcut.
Added: New readouts to the vessel category: Added: New readouts to the vessel category:
- Current Stage DeltaV - Current Stage DeltaV
- Surface Thrust to Weight Ratio - Surface Thrust to Weight Ratio
   
Added: New editor overlay system. Added: New editor overlay system.
- Sleeker design. - Sleeker design.
- Hover over part information options: - Hover over part information options:
- Name only - Name only
- Middle click to show - Middle click to show
- Always show - Always show
- Slide out overlay displays: - Slide out overlay displays:
- Vessel information - Vessel information
- Resources list - Resources list
   
Fixed: Cost calculation now works with mods implementing IPartCostModifier. Fixed: Cost calculation now works with mods implementing IPartCostModifier.
   
1.0.8.1, 06-09-2014 1.0.8.1, 06-09-2014
Fixed: Bug which caused rendezvous readouts to freeze the game or show all zeros. Fixed: Bug which caused rendezvous readouts to freeze the game or show all zeros.
   
1.0.8.0, 06-09-2014 1.0.8.0, 06-09-2014
Added: New readouts to the vessel category: Added: New readouts to the vessel category:
- Intake Air (Usage) - Intake Air (Usage)
   
Added: New readouts to the rendezvous category: Added: New readouts to the rendezvous category:
- Relative Velocity - Relative Velocity
- Relative Speed - Relative Speed
   
Fixed: An issue where deltaV would not be calculated whilst flying. Fixed: An issue where deltaV would not be calculated whilst flying.
Fixed: NullRef whilst loading the in flight Action Menu. Fixed: NullRef whilst loading the in flight Action Menu.
   
1.0.7.1, 02-09-2014 1.0.7.1, 02-09-2014
Changed: Reversed Intake Air readout from 'S/D' to 'D/S' for easier reading. Changed: Reversed Intake Air readout from 'S/D' to 'D/S' for easier reading.
Changed: Increased Intake Air readout precision to 4 decimal places. Changed: Increased Intake Air readout precision to 4 decimal places.
Fixed: Issue where Intake Air supply was not representative of total supply. Fixed: Issue where Intake Air supply was not representative of total supply.
Fixed: Bug where actual thrust does not reset to zero on deactivated engines. Fixed: Bug where actual thrust does not reset to zero on deactivated engines.
Fixed: Thrust now scales with velocity for atmospheric engines. (Padishar's fix) Fixed: Thrust now scales with velocity for atmospheric engines. (Padishar's fix)
   
1.0.7.0, 01-09-2014 1.0.7.0, 01-09-2014
Added: Part count information to the Build Engineer. Added: Part count information to the Build Engineer.
Added: Reset button to the G-Force readout. Added: Reset button to the G-Force readout.
Added: Preset system to the Flight Engineer. Added: Preset system to the Flight Engineer.
Added: New stock presets: Added: New stock presets:
- Orbital - Orbital
- Surface - Surface
- Vessel - Vessel
- Rendezvous - Rendezvous
   
Added: New readouts to the orbital category: Added: New readouts to the orbital category:
- True Anomaly - True Anomaly
- Eccentric Anomaly - Eccentric Anomaly
- Mean Anomaly - Mean Anomaly
- Argument of Periapsis - Argument of Periapsis
- Angle to Prograde - Angle to Prograde
- Angle to Retrograde - Angle to Retrograde
   
Added: New readouts to the vessel category: Added: New readouts to the vessel category:
- Intake Air (Demand) - Intake Air (Demand)
- Intake Air (Supply) - Intake Air (Supply)
- Intake Air (Supply/Demand) - Intake Air (Supply/Demand)
   
Added: New readouts to the rendezvous category. Added: New readouts to the rendezvous category.
- Semi-major Axis - Semi-major Axis
- Semi-minor Axis - Semi-minor Axis
   
Added: Time formatter which can show time as referenced by any celestial body. Added: Time formatter which can show time as referenced by any celestial body.
Added: New readouts to the miscellaneous category: Added: New readouts to the miscellaneous category:
- Time Reference Adjuster - Time Reference Adjuster
   
Changed: Moved Sim Delay readout into the Miscellaneous category. Changed: Moved Sim Delay readout into the Miscellaneous category.
Changed: Updated MiniAVC to v1.0.2.3. Changed: Updated MiniAVC to v1.0.2.3.
Fixed: Issues with large value wrap around in the Flight Engineer. Fixed: Issues with large value wrap around in the Flight Engineer.
Fixed: Bug in the phase angle calculation. Fixed: Bug in the phase angle calculation.
   
1.0.6.0, 23-08-2014 1.0.6.0, 23-08-2014
Added: Time and Angle to equatorial ascending/descending nodes in the orbital display. Added: Time and Angle to equatorial ascending/descending nodes in the orbital display.
Added: Time and Angle to relative ascending/descending nodes in the rendezvous display. Added: Time and Angle to relative ascending/descending nodes in the rendezvous display.
Added: Overlay tooltip information delay adjustment slider to the Build Engineer settings. Added: Overlay tooltip information delay adjustment slider to the Build Engineer settings.
Added: Ability to rename the stock displays in the Flight Engineer. Added: Ability to rename the stock displays in the Flight Engineer.
Changed: Build Engineer is now hidden when not in parts view. Changed: Build Engineer is now hidden when not in parts view.
Changed: Custom display panels will only show in the control bar if an abbreviation is set. Changed: Custom display panels will only show in the control bar if an abbreviation is set.
Changed: Licensing and readme structures are now more verbose to satisfy the new add-on rules. Changed: Licensing and readme structures are now more verbose to satisfy the new add-on rules.
Fixed: Updated MiniAVC to v1.0.2.1 (fixes remote check bug as well as other minor bugs). Fixed: Updated MiniAVC to v1.0.2.1 (fixes remote check bug as well as other minor bugs).
   
1.0.5.0, 13-08-2014 1.0.5.0, 13-08-2014
Added: Acceleration readout to the Vessel category (current / maximum). Added: Acceleration readout to the Vessel category (current / maximum).
Added: Category library system for the Flight Engineer readouts. Added: Category library system for the Flight Engineer readouts.
Added: Drop-down category selection to better support the new system. Added: Drop-down category selection to better support the new system.
Changed: Misc category now called Miscellaneous (this will cause previously added readouts from this category to vanish). Changed: Misc category now called Miscellaneous (this will cause previously added readouts from this category to vanish).
Fixed: Bug with the Build Engineer toolbar button. Fixed: Bug with the Build Engineer toolbar button.
Fixed: Some buggyness when trying to close the bodies drop-down in the Build Engineer via the button. Fixed: Some buggyness when trying to close the bodies drop-down in the Build Engineer via the button.
Fixed: Flight Engineer toolbar menu now hides when hiding the GUI with F2. Fixed: Flight Engineer toolbar menu now hides when hiding the GUI with F2.
Fixed: Flight Engineer toolbar button now disables when in module mode and no engineer is running. Fixed: Flight Engineer toolbar button now disables when in module mode and no engineer is running.
   
1.0.4.0, 12-08-2014 1.0.4.0, 12-08-2014
Added: Better stock toolbar support in the flight engineer. Added: Better stock toolbar support in the flight engineer.
Added: Dynamically generated celestial body library for supporting add-ons that modify the star system. Added: Dynamically generated celestial body library for supporting add-ons that modify the star system.
Changed: Reference bodies are now listed with a nestable menu system. Changed: Reference bodies are now listed with a nestable menu system.
Changed: Extended logging system has been improved. Changed: Extended logging system has been improved.
Changed: Swapped out integrated MiniAVC in place of the official bundle version. Changed: Swapped out integrated MiniAVC in place of the official bundle version.
Changed: Increased general distance precision to 1 decimal place. Changed: Increased general distance precision to 1 decimal place.
Changed: Increased Semi-major/minor axis precision to 3 decimal places. Changed: Increased Semi-major/minor axis precision to 3 decimal places.
Fixed: Impact altitude was mistakenly formatted as an angle, it is now formatted correctly as a distance. Fixed: Impact altitude was mistakenly formatted as an angle, it is now formatted correctly as a distance.
   
1.0.3.0, 30-07-2014 1.0.3.0, 30-07-2014
Added: Integrated KSP-AVC support with MiniAVC. Added: Integrated KSP-AVC support with MiniAVC.
Added: Setting to change the simulation delay in the Build Engineer. Added: Setting to change the simulation delay in the Build Engineer.
Added: Setting to enable and disable the build overlay system. Added: Setting to enable and disable the build overlay system.
Added: Burn time to Delta-V readouts. Added: Burn time to Delta-V readouts.
Added: Atmospheric readouts fully support FAR. Added: Atmospheric readouts fully support FAR.
Added: Atmospheric readouts are disabled with NEAR. Added: Atmospheric readouts are disabled with NEAR.
Changed: Force formatting inversely scales decimal precision with value. Changed: Force formatting inversely scales decimal precision with value.
Fixed: Flickering in VAB and Vessel display. Fixed: Flickering in VAB and Vessel display.
Fixed: Bug saving the GUI display size. Fixed: Bug saving the GUI display size.
   
1.0.2.0, 27-07-2014 1.0.2.0, 27-07-2014
Added: Separator readout module under Misc in the Flight Engineer. Added: Separator readout module under Misc in the Flight Engineer.
Added: Adjustable GUI display size. Added: Adjustable GUI display size.
Added: Display size can be adjusted in the Build Engineer settings. Added: Display size can be adjusted in the Build Engineer settings.
Added: Misc readout for adjusting display size in the Flight Engineer. Added: Misc readout for adjusting display size in the Flight Engineer.
Changed: The rendezvous readout for the target's Orbital Period has higher precision. Changed: The rendezvous readout for the target's Orbital Period has higher precision.
Fixed: White toolbar icon by manually importing the texture if it cannot be found in the game database. Fixed: White toolbar icon by manually importing the texture if it cannot be found in the game database.
Fixed: Engines that have a minimum thrust are now calculated properly. (Thanks to nosscire.) Fixed: Engines that have a minimum thrust are now calculated properly. (Thanks to nosscire.)
Fixed: Compact collapse mode is now saved in the Build Engineer. Fixed: Compact collapse mode is now saved in the Build Engineer.
   
1.0.1.0, 26-07-2014 1.0.1.0, 26-07-2014
Added: Part-less Flight Engineer. Added: Part-less Flight Engineer.
Added: Ability to collapse the Build Engineer into compact mode from left or right. Added: Ability to collapse the Build Engineer into compact mode from left or right.
Added: Settings in Build Engineer for compact collapse mode and partless/module Flight Engineer. Added: Settings in Build Engineer for compact collapse mode and partless/module Flight Engineer.
Added: Biome, Impact Biome and Slope readouts. Added: Biome, Impact Biome and Slope readouts.
Added: Extra logging and exception handling. Added: Extra logging and exception handling.
Added: The original Engineer Chip part. Added: The original Engineer Chip part.
Added: "Show Engineer" toggle on the Flight Engineer toolbar. Added: "Show Engineer" toggle on the Flight Engineer toolbar.
Changed: Extended logging system now also writes to the standard KSP logs. Changed: Extended logging system now also writes to the standard KSP logs.
Changed: Extended logging saves next to the .dll file. Changed: Extended logging saves next to the .dll file.
Changed: ER7500 part has no physical significance. Changed: ER7500 part has no physical significance.
Fixed: ActionMenu and DisplayStack destruction bug. Fixed: ActionMenu and DisplayStack destruction bug.
   
1.0.0.1, 24-07-2014 1.0.0.1, 24-07-2014
Added: Stock toolbar support in the Flight Engineer. Added: Stock toolbar support in the Flight Engineer.
Changed: Orbital Period has higher precision. Changed: Orbital Period has higher precision.
Fixed: Various NullRefs in editor window and overlay. Fixed: Various NullRefs in editor window and overlay.
   
1.0.0.0, 24-07-2014 1.0.0.0, 24-07-2014
Initial release for public testing. Initial release for public testing.
   
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives  
   
using System;  
using System.Collections.Generic;  
using System.Linq;  
   
#endregion  
   
namespace KerbalEngineer namespace KerbalEngineer
{ {
  using System;
  using System.Collections.Generic;
  using System.Linq;
   
/* /*
* *
* With thanks to Nathaniel R. Lewis (aka. Teknoman117) (linux.robotdude@gmail.com) for working out * With thanks to Nathaniel R. Lewis (aka. Teknoman117) (linux.robotdude@gmail.com) for working out
* the best way of getting the celestial body information dynamically using PSystemManager. * the best way of getting the celestial body information dynamically using PSystemManager.
* *
*/ */
   
public static class CelestialBodies public static class CelestialBodies
{ {
#region Constructors  
   
static CelestialBodies() static CelestialBodies()
{ {
try try
{ {
SystemBody = new BodyInfo(PSystemManager.Instance.localBodies.Find(b => b.referenceBody == null || b.referenceBody == b)); SystemBody = new BodyInfo(PSystemManager.Instance.localBodies.Find(b => b.referenceBody == null || b.referenceBody == b));
if (!SetSelectedBody("Kerbin")) String homeCBName = Planetarium.fetch.Home.bodyName;
  if (!SetSelectedBody(homeCBName))
{ {
SelectedBody = SystemBody; SelectedBody = SystemBody;
SelectedBody.SetSelected(true); SelectedBody.SetSelected(true);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion  
   
#region Properties  
   
public static BodyInfo SelectedBody { get; private set; } public static BodyInfo SelectedBody { get; private set; }
public static BodyInfo SystemBody { get; private set; } public static BodyInfo SystemBody { get; private set; }
   
#endregion  
   
#region Public Methods  
   
/// <summary> /// <summary>
/// Gets a body given a supplied body name. /// Gets a body given a supplied body name.
/// </summary> /// </summary>
public static BodyInfo GetBodyInfo(string bodyName) public static BodyInfo GetBodyInfo(string bodyName)
{ {
try try
{ {
return SystemBody.GetBodyInfo(bodyName); return SystemBody.GetBodyInfo(bodyName);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
return null; return null;
} }
   
/// <summary> /// <summary>
/// Sets the selected body to one matching the supplied body name. Returns true if successful. /// Sets the selected body to one matching the supplied body name. Returns true if successful.
/// </summary> /// </summary>
public static bool SetSelectedBody(string bodyName) public static bool SetSelectedBody(string bodyName)
{ {
try try
{ {
var body = GetBodyInfo(bodyName); BodyInfo body = GetBodyInfo(bodyName);
if (body != null) if (body != null)
{ {
if (SelectedBody != null) if (SelectedBody != null)
{ {
SelectedBody.SetSelected(false); SelectedBody.SetSelected(false);
} }
SelectedBody = body; SelectedBody = body;
SelectedBody.SetSelected(true); SelectedBody.SetSelected(true);
return true; return true;
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
return false; return false;
} }
   
#endregion  
   
#region Nested type: BodyInfo  
   
public class BodyInfo public class BodyInfo
{ {
#region Constructors  
   
public BodyInfo(CelestialBody body, BodyInfo parent = null) public BodyInfo(CelestialBody body, BodyInfo parent = null)
{ {
try try
{ {
// Set the body information. // Set the body information.
this.CelestialBody = body; CelestialBody = body;
this.Name = body.bodyName; Name = body.bodyName;
this.Gravity = 9.81 * body.GeeASL; Gravity = 9.81 * body.GeeASL;
this.Atmosphere = body.atmosphere ? 101.325 * body.atmosphereMultiplier : 0; Parent = parent;
this.Parent = parent;  
   
// Set orbiting bodies information. // Set orbiting bodies information.
this.Children = new List<BodyInfo>(); Children = new List<BodyInfo>();
foreach (var orbitingBody in body.orbitingBodies) foreach (CelestialBody orbitingBody in body.orbitingBodies)
{ {
this.Children.Add(new BodyInfo(orbitingBody, this)); Children.Add(new BodyInfo(orbitingBody, this));
} }
   
this.SelectedDepth = 0; SelectedDepth = 0;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion public CelestialBody CelestialBody { get; private set; }
  public List<BodyInfo> Children { get; private set; }
#region Properties public double Gravity { get; private set; }
   
public string Name { get; private set; } public string Name { get; private set; }
public double Gravity { get; private set; }  
public double Atmosphere { get; private set; }  
public BodyInfo Parent { get; private set; } public BodyInfo Parent { get; private set; }
public List<BodyInfo> Children { get; private set; }  
public CelestialBody CelestialBody { get; private set; }  
public bool Selected { get; private set; } public bool Selected { get; private set; }
public int SelectedDepth { get; private set; } public int SelectedDepth { get; private set; }
   
#endregion  
   
#region Public Methods  
   
public BodyInfo GetBodyInfo(string bodyName) public BodyInfo GetBodyInfo(string bodyName)
{ {
try try
{ {
// This is the searched body. // This is the searched body.
if (String.Equals(this.Name, bodyName, StringComparison.CurrentCultureIgnoreCase)) if (String.Equals(Name, bodyName, StringComparison.CurrentCultureIgnoreCase))
{ {
return this; return this;
} }
   
// Check to see if any of this bodies children are the searched body. // Check to see if any of this bodies children are the searched body.
foreach (var child in this.Children) foreach (BodyInfo child in Children)
{ {
var body = child.GetBodyInfo(bodyName); BodyInfo body = child.GetBodyInfo(bodyName);
if (body != null) if (body != null)
{ {
return body; return body;
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
   
// A body with the specified name was not found. // A body with the specified name was not found.
return null; return null;
} }
   
  public double GetDensity(double altitude)
  {
  return CelestialBody.GetDensity(GetPressure(altitude), GetTemperature(altitude));
  }
   
  public double GetPressure(double altitude)
  {
  return CelestialBody.GetPressure(altitude);
  }
   
  public double GetTemperature(double altitude)
  {
  return CelestialBody.GetTemperature(altitude);
  }
   
  public double GetAtmospheres(double altitude)
  {
  return GetPressure(altitude) * PhysicsGlobals.KpaToAtmospheres;
  }
   
public void SetSelected(bool state, int depth = 0) public void SetSelected(bool state, int depth = 0)
{ {
this.Selected = state; Selected = state;
this.SelectedDepth = depth; SelectedDepth = depth;
if (this.Parent != null) if (Parent != null)
{ {
this.Parent.SetSelected(state, depth + 1); Parent.SetSelected(state, depth + 1);
} }
} }
   
#endregion  
   
#region Debugging  
   
public override string ToString() public override string ToString()
{ {
var log = "\n" + this.Name + string log = "\n" + Name +
"\n\tGravity: " + this.Gravity + "\n\tGravity: " + Gravity +
"\n\tAtmosphere: " + this.Atmosphere + "\n\tSelected: " + Selected;
"\n\tSelected: " + this.Selected;  
  return Children.Aggregate(log, (current, child) => current + "\n" + child);
return this.Children.Aggregate(log, (current, child) => current + "\n" + child); }
} }
   
#endregion  
}  
   
#endregion  
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
   
using KerbalEngineer.Control.Panels; using KerbalEngineer.Control.Panels;
   
using UnityEngine; using UnityEngine;
   
#endregion #endregion
   
namespace KerbalEngineer.Control namespace KerbalEngineer.Control
{ {
[KSPAddon(KSPAddon.Startup.Instantly, false)] [KSPAddon(KSPAddon.Startup.Instantly, false)]
public class ControlCentre : MonoBehaviour public class ControlCentre : MonoBehaviour
{ {
#region Fields #region Fields
   
private static readonly List<IControlPanel> panels = new List<IControlPanel>(); private static readonly List<IControlPanel> panels = new List<IControlPanel>();
   
private static GUIStyle button; private static GUIStyle button;
private static ControlCentre instance; private static ControlCentre instance;
private static GUIStyle label; private static GUIStyle label;
private static GUIStyle title; private static GUIStyle title;
   
private Vector2 contentsScrollPosition; private Vector2 contentsScrollPosition;
private GUIStyle panelSelectorStyle; private GUIStyle panelSelectorStyle;
private Rect position = new Rect(Screen.width, Screen.height, 900.0f, 500.0f); private Rect position = new Rect(Screen.width, Screen.height, 900.0f, 500.0f);
private IControlPanel selectedPanel; private IControlPanel selectedPanel;
private bool shouldCentre = true; private bool shouldCentre = true;
   
#endregion #endregion
   
#region Properties #region Properties
   
public static GUIStyle Button public static GUIStyle Button
{ {
get get
{ {
return button ?? (button = new GUIStyle(HighLogic.Skin.button) return button ?? (button = new GUIStyle(HighLogic.Skin.button)
{ {
normal = normal =
{ {
textColor = Color.white textColor = Color.white
}, },
fixedHeight = 30.0f fixedHeight = 30.0f
}); });
} }
} }
   
public static bool Enabled public static bool Enabled
{ {
get { return instance.enabled; } get { return instance.enabled; }
set { instance.enabled = value; } set { instance.enabled = value; }
} }
   
public static GUIStyle Label public static GUIStyle Label
{ {
get get
{ {
return label ?? (label = new GUIStyle(HighLogic.Skin.label) return label ?? (label = new GUIStyle(HighLogic.Skin.label)
{ {
normal = normal =
{ {
textColor = Color.white textColor = Color.white
}, },
fontStyle = FontStyle.Bold, fontStyle = FontStyle.Bold,
fixedHeight = 30.0f, fixedHeight = 30.0f,
alignment = TextAnchor.MiddleLeft, alignment = TextAnchor.MiddleLeft,
stretchWidth = true, stretchWidth = true,
}); });
} }
} }
   
public static List<IControlPanel> Panels public static List<IControlPanel> Panels
{ {
get { return panels; } get { return panels; }
} }
   
public static GUIStyle Title public static GUIStyle Title
{ {
get get
{ {
return title ?? (title = new GUIStyle(HighLogic.Skin.label) return title ?? (title = new GUIStyle(HighLogic.Skin.label)
{ {
normal = normal =
{ {
textColor = Color.white textColor = Color.white
}, },
fontSize = 26, fontSize = 26,
fontStyle = FontStyle.Bold, fontStyle = FontStyle.Bold,
alignment = TextAnchor.UpperCenter, alignment = TextAnchor.UpperCenter,
stretchWidth = true, stretchWidth = true,
}); });
} }
} }
   
#endregion #endregion
   
#region Methods: protected #region Methods: protected
   
protected void Awake() protected void Awake()
{ {
try try
{ {
if (instance == null) if (instance == null)
{ {
DontDestroyOnLoad(this); DontDestroyOnLoad(this);
instance = this; instance = this;
this.enabled = false; this.enabled = false;
return; return;
} }
Destroy(this); Destroy(this);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
protected void OnGUI() protected void OnGUI()
{ {
try try
{ {
GUI.skin = null; GUI.skin = null;
this.position = GUILayout.Window(this.GetInstanceID(), this.position, this.Window, "KERBAL ENGINEER REDUX " + EngineerGlobals.AssemblyVersion + " - CONTROL CENTRE", HighLogic.Skin.window); this.position = GUILayout.Window(this.GetInstanceID(), this.position, this.Window, "KERBAL ENGINEER REDUX " + EngineerGlobals.ASSEMBLY_VERSION + " - CONTROL CENTRE", HighLogic.Skin.window);
this.CentreWindow(); this.CentreWindow();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
protected void Start() protected void Start()
{ {
try try
{ {
this.InitialiseStyles(); this.InitialiseStyles();
LoadPanels(); LoadPanels();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion #endregion
   
#region Methods: private #region Methods: private
   
private static void LoadPanels() private static void LoadPanels()
{ {
panels.Add(new BuildEngineerPanel()); panels.Add(new BuildEngineerPanel());
panels.Add(new BuildOverlayPanel()); panels.Add(new BuildOverlayPanel());
} }
   
private void CentreWindow() private void CentreWindow()
{ {
if (this.shouldCentre && this.position.width > 0.0f && this.position.height > 0.0f) if (this.shouldCentre && this.position.width > 0.0f && this.position.height > 0.0f)
{ {
this.position.center = new Vector2(Screen.width * 0.5f, Screen.height * 0.5f); this.position.center = new Vector2(Screen.width * 0.5f, Screen.height * 0.5f);
this.shouldCentre = false; this.shouldCentre = false;
} }
} }
   
private void DrawContents() private void DrawContents()
{ {
GUI.skin = HighLogic.Skin; GUI.skin = HighLogic.Skin;
this.contentsScrollPosition = GUILayout.BeginScrollView(this.contentsScrollPosition, false, true); this.contentsScrollPosition = GUILayout.BeginScrollView(this.contentsScrollPosition, false, true);
GUI.skin = null; GUI.skin = null;
   
if (this.selectedPanel != null) if (this.selectedPanel != null)
{ {
this.selectedPanel.Draw(); this.selectedPanel.Draw();
} }
   
GUILayout.FlexibleSpace(); GUILayout.FlexibleSpace();
GUILayout.EndScrollView(); GUILayout.EndScrollView();
} }
   
private void DrawSelectors() private void DrawSelectors()
{ {
GUILayout.BeginVertical(HighLogic.Skin.box, GUILayout.Width(225.0f)); GUILayout.BeginVertical(HighLogic.Skin.box, GUILayout.Width(225.0f));
foreach (var panel in panels) foreach (var panel in panels)
{ {
if (GUILayout.Toggle(this.selectedPanel == panel, panel.Name, this.panelSelectorStyle)) if (GUILayout.Toggle(this.selectedPanel == panel, panel.Name, this.panelSelectorStyle))
{ {
this.selectedPanel = panel; this.selectedPanel = panel;
} }
} }
GUILayout.FlexibleSpace(); GUILayout.FlexibleSpace();
if (GUILayout.Button("CLOSE", Button)) if (GUILayout.Button("CLOSE", Button))
{ {
this.enabled = false; this.enabled = false;
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
private void InitialiseStyles() private void InitialiseStyles()
{ {
this.panelSelectorStyle = new GUIStyle(Button) this.panelSelectorStyle = new GUIStyle(Button)
{ {
fontSize = 16, fontSize = 16,
fixedHeight = 40.0f fixedHeight = 40.0f
}; };
} }
   
private void Window(int windowId) private void Window(int windowId)
{ {
try try
{ {
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
this.DrawSelectors(); this.DrawSelectors();
this.DrawContents(); this.DrawContents();
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Copyright (C) 2015 CYBUTEK
//  
// Copyright (C) 2014 CYBUTEK  
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
namespace KerbalEngineer.Editor namespace KerbalEngineer.Editor
{ {
#region Using Directives  
   
using System; using System;
using System.Linq;  
using Extensions; using Extensions;
using Flight; using Flight;
using Helpers; using Helpers;
  using KeyBinding;
using Settings; using Settings;
using UIControls; using UIControls;
using UnityEngine; using UnityEngine;
using VesselSimulator; using VesselSimulator;
   
#endregion  
   
[KSPAddon(KSPAddon.Startup.EditorAny, false)] [KSPAddon(KSPAddon.Startup.EditorAny, false)]
public class BuildAdvanced : MonoBehaviour public class BuildAdvanced : MonoBehaviour
{ {
#region Fields public static float Altitude;
   
  private static Rect compactModeRect = new Rect(0.0f, 5.0f, 0.0f, 20.0f);
  private static Stage stage;
  private static int stagesCount;
  private static int stagesLength;
  private static string title;
   
private GUIStyle areaSettingStyle; private GUIStyle areaSettingStyle;
private GUIStyle areaStyle; private GUIStyle areaStyle;
private float atmosphericPercentage = 1.0f; private float atmosphericMach;
private float atmosphericVelocity;  
private GUIStyle bodiesButtonActiveStyle; private GUIStyle bodiesButtonActiveStyle;
private GUIStyle bodiesButtonStyle; private GUIStyle bodiesButtonStyle;
private DropDown bodiesList; private DropDown bodiesList;
private Rect bodiesListPosition; private Rect bodiesListPosition;
private GUIStyle buttonStyle; private GUIStyle buttonStyle;
private int compactCheck; private int compactCheck;
private bool compactCollapseRight; private bool compactCollapseRight;
private bool compactMode; private bool compactMode;
private float compactRight; private float compactRight;
private bool hasChanged; private bool hasChanged;
private GUIStyle infoStyle; private GUIStyle infoStyle;
private bool isEditorLocked; private bool isEditorLocked;
  private float maxMach;
private int numberOfStages; private int numberOfStages;
private Rect position = new Rect(265.0f, 45.0f, 0, 0); private Rect position = new Rect(265.0f, 45.0f, 0, 0);
private GUIStyle settingAtmoStyle; private GUIStyle settingAtmoStyle;
private GUIStyle settingStyle; private GUIStyle settingStyle;
private bool showAllStages; private bool showAllStages;
private bool showAtmosphericDetails; private bool showAtmosphericDetails;
private bool showSettings; private bool showSettings;
private Stage[] stages; private Stage[] stages;
private GUIStyle titleStyle; private GUIStyle titleStyle;
private bool visible = true; private bool visible = true;
private GUIStyle windowStyle; private GUIStyle windowStyle;
   
#endregion  
   
#region Properties  
   
/// <summary> /// <summary>
/// Gets the current instance if started or returns null. /// Gets the current instance if started or returns null.
/// </summary> /// </summary>
public static BuildAdvanced Instance { get; private set; } public static BuildAdvanced Instance { get; private set; }
   
/// <summary> /// <summary>
/// Gets and sets whether to show in compact mode. /// Gets and sets whether to show in compact mode.
/// </summary> /// </summary>
public bool CompactMode public bool CompactMode
{ {
get { return this.compactMode; } get
set { this.compactMode = value; } {
  return compactMode;
  }
  set
  {
  compactMode = value;
  }
} }
   
/// <summary> /// <summary>
/// Gets and sets whether to show all stages. /// Gets and sets whether to show all stages.
/// </summary> /// </summary>
public bool ShowAllStages public bool ShowAllStages
{ {
get { return this.showAllStages; } get
set { this.showAllStages = value; } {
  return showAllStages;
  }
  set
  {
  showAllStages = value;
  }
} }
   
/// <summary> /// <summary>
/// Gets and sets whether to use atmospheric details. /// Gets and sets whether to use atmospheric details.
/// </summary> /// </summary>
public bool ShowAtmosphericDetails public bool ShowAtmosphericDetails
{ {
get { return this.showAtmosphericDetails; } get
set { this.showAtmosphericDetails = value; } {
  return showAtmosphericDetails;
  }
  set
  {
  showAtmosphericDetails = value;
  }
} }
   
/// <summary> /// <summary>
/// Gets and sets whether to show the settings display. /// Gets and sets whether to show the settings display.
/// </summary> /// </summary>
public bool ShowSettings public bool ShowSettings
{ {
get { return this.showSettings; } get
set { this.showSettings = value; } {
  return showSettings;
  }
  set
  {
  showSettings = value;
  }
} }
   
/// <summary> /// <summary>
/// Gets and sets whether the display is enabled. /// Gets and sets whether the display is enabled.
/// </summary> /// </summary>
public bool Visible public bool Visible
{ {
get { return this.visible; } get
set { this.visible = value; } {
} return visible;
  }
#endregion set
  {
#region Methods visible = value;
  }
  }
   
protected void Awake() protected void Awake()
{ {
try try
{ {
Instance = this; Instance = this;
this.bodiesList = this.gameObject.AddComponent<DropDown>(); bodiesList = gameObject.AddComponent<DropDown>();
this.bodiesList.DrawCallback = this.DrawBodiesList; bodiesList.DrawCallback = DrawBodiesList;
this.Load(); Load();
   
SimManager.OnReady -= this.GetStageInfo; SimManager.UpdateModSettings();
SimManager.OnReady += this.GetStageInfo; SimManager.OnReady -= GetStageInfo;
  SimManager.OnReady += GetStageInfo;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex, "BuildAdvanced.Awake()");
} }
} }
   
/// <summary> /// <summary>
/// Saves the settings when this object is destroyed. /// Saves the settings when this object is destroyed.
/// </summary> /// </summary>
protected void OnDestroy() protected void OnDestroy()
{ {
  Logger.Log("BuildAdvanced->OnDestroy");
   
try try
{ {
var handler = new SettingHandler(); SettingHandler handler = new SettingHandler();
handler.Set("visible", this.visible); handler.Set("visible", visible);
handler.Set("windowPositionX", this.position.x); handler.Set("windowPositionX", position.x);
handler.Set("windowPositionY", this.position.y); handler.Set("windowPositionY", position.y);
handler.Set("compactMode", this.compactMode); handler.Set("compactMode", compactMode);
handler.Set("compactCollapseRight", this.compactCollapseRight); handler.Set("compactCollapseRight", compactCollapseRight);
handler.Set("showAllStages", this.showAllStages); handler.Set("showAllStages", showAllStages);
handler.Set("showAtmosphericDetails", this.showAtmosphericDetails); handler.Set("showAtmosphericDetails", showAtmosphericDetails);
handler.Set("showSettings", this.showSettings); handler.Set("showSettings", showSettings);
handler.Set("selectedBodyName", CelestialBodies.SelectedBody.Name); handler.Set("selectedBodyName", CelestialBodies.SelectedBody.Name);
handler.Save("BuildAdvanced.xml"); handler.Save("BuildAdvanced.xml");
GuiDisplaySize.OnSizeChanged -= this.OnSizeChanged; GuiDisplaySize.OnSizeChanged -= OnSizeChanged;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex, "BuildAdvanced.OnDestroy()");
} }
   
  EditorLock(false);
} }
   
protected void OnGUI() protected void OnGUI()
{ {
try try
{ {
if (!this.visible || EditorLogic.fetch == null || EditorLogic.fetch.ship.parts.Count == 0 || EditorLogic.fetch.editorScreen != EditorScreen.Parts) if (!visible || EditorLogic.fetch == null || EditorLogic.fetch.ship.parts.Count == 0 || EditorLogic.fetch.editorScreen != EditorScreen.Parts)
{ {
return; return;
} }
   
if (this.stages == null) if (stages == null)
{ {
return; return;
} }
   
// Change the window title based on whether in compact mode or not. // Change the window title based on whether in compact mode or not.
var title = !this.compactMode ? "KERBAL ENGINEER REDUX " + EngineerGlobals.AssemblyVersion : "K.E.R. " + EngineerGlobals.AssemblyVersion + (this.showAtmosphericDetails ? " (ATMOS.)" : String.Empty); title = !compactMode ? "KERBAL ENGINEER REDUX " + EngineerGlobals.ASSEMBLY_VERSION : "K.E.R. " + EngineerGlobals.ASSEMBLY_VERSION;
   
// Reset the window size when the staging or something else has changed. // Reset the window size when the staging or something else has changed.
var stageCount = this.stages.Count(stage => this.showAllStages || stage.deltaV > 0); stagesLength = stages.Length;
if (this.hasChanged || stageCount != this.numberOfStages) if (showAllStages)
{ {
this.hasChanged = false; stagesCount = stagesLength;
this.numberOfStages = stageCount; }
  if (showAllStages == false)
this.position.width = 0; {
this.position.height = 0; stagesCount = 0;
  for (int i = 0; i < stagesLength; ++i)
  {
  if (stages[i].deltaV > 0.0f)
  {
  stagesCount = stagesCount + 1;
  }
  }
  }
   
  if (hasChanged || stagesCount != numberOfStages)
  {
  hasChanged = false;
  numberOfStages = stagesCount;
   
  position.width = 0;
  position.height = 0;
} }
   
GUI.skin = null; GUI.skin = null;
this.position = GUILayout.Window(this.GetInstanceID(), this.position, this.Window, title, this.windowStyle).ClampToScreen(); position = GUILayout.Window(GetInstanceID(), position, Window, title, windowStyle).ClampToScreen();
   
if (this.compactCheck > 0 && this.compactCollapseRight) if (compactCheck > 0 && compactCollapseRight)
{ {
this.position.x = this.compactRight - this.position.width; position.x = compactRight - position.width;
this.compactCheck--; compactCheck--;
} }
else if (this.compactCheck > 0) else if (compactCheck > 0)
{ {
this.compactCheck = 0; compactCheck = 0;
} }
   
// Check editor lock to manage click-through. // Check editor lock to manage click-through.
this.CheckEditorLock(); CheckEditorLock();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex, "BuildAdvanced.OnGUI()");
} }
} }
   
protected void Start() protected void Start()
{ {
try try
{ {
this.InitialiseStyles(); InitialiseStyles();
GuiDisplaySize.OnSizeChanged += this.OnSizeChanged; GuiDisplaySize.OnSizeChanged += OnSizeChanged;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex, "BuildAdvanced.Start()");
} }
} }
   
protected void Update() protected void Update()
{ {
try try
{ {
if (Input.GetKeyDown(KeyBinder.EditorShowHide)) if (Input.GetKeyDown(KeyBinder.EditorShowHide))
{ {
this.visible = !this.visible; visible = !visible;
if (!this.visible) if (!visible)
{ {
this.EditorLock(false); EditorLock(false);
} }
} }
   
if (!this.visible || EditorLogic.fetch == null || EditorLogic.fetch.ship.parts.Count == 0) if (!visible || EditorLogic.fetch == null || EditorLogic.fetch.ship.parts.Count == 0)
{ {
this.bodiesList.enabled = false; bodiesList.enabled = false;
return; return;
} }
   
// Configure the simulation parameters based on the selected reference body. // Configure the simulation parameters based on the selected reference body.
SimManager.Gravity = CelestialBodies.SelectedBody.Gravity; SimManager.Gravity = CelestialBodies.SelectedBody.Gravity;
   
if (this.showAtmosphericDetails) if (showAtmosphericDetails)
{ {
SimManager.Atmosphere = CelestialBodies.SelectedBody.Atmosphere * 0.01d * this.atmosphericPercentage; SimManager.Atmosphere = CelestialBodies.SelectedBody.GetAtmospheres(Altitude);
} }
else else
{ {
SimManager.Atmosphere = 0; SimManager.Atmosphere = 0;
} }
   
SimManager.Velocity = this.atmosphericVelocity; SimManager.Mach = atmosphericMach;
   
SimManager.RequestSimulation(); SimManager.RequestSimulation();
SimManager.TryStartSimulation(); SimManager.TryStartSimulation();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex, "BuildAdvanced->Update"); Logger.Exception(ex, "BuildAdvanced.Update()");
} }
} }
   
/// <summary> /// <summary>
/// Checks whether the editor should be locked to stop click-through. /// Checks whether the editor should be locked to stop click-through.
/// </summary> /// </summary>
private void CheckEditorLock() private void CheckEditorLock()
{ {
if ((this.position.MouseIsOver() || this.bodiesList.Position.MouseIsOver()) && !this.isEditorLocked) if ((position.MouseIsOver() || bodiesList.Position.MouseIsOver()) && !isEditorLocked)
{ {
this.EditorLock(true); EditorLock(true);
} }
else if (!this.position.MouseIsOver() && !this.bodiesList.Position.MouseIsOver() && this.isEditorLocked) else if (!position.MouseIsOver() && !bodiesList.Position.MouseIsOver() && isEditorLocked)
{ {
this.EditorLock(false); EditorLock(false);
} }
} }
   
/// <summary> /// <summary>
/// Draws the atmospheric settings. /// Draws the atmospheric settings.
/// </summary> /// </summary>
private void DrawAtmosphericDetails() private void DrawAtmosphericDetails()
{ {
GUILayout.BeginHorizontal(); try
GUILayout.BeginVertical(); {
GUILayout.Label("Pressure: " + (this.atmosphericPercentage * 100.0f).ToString("F1") + "%", this.settingAtmoStyle, GUILayout.Width(125.0f * GuiDisplaySize.Offset)); GUILayout.BeginHorizontal();
GUI.skin = HighLogic.Skin; GUILayout.BeginVertical();
this.atmosphericPercentage = GUILayout.HorizontalSlider(this.atmosphericPercentage, 0, 1.0f); GUILayout.Label("Altitude: " + (Altitude * 0.001f).ToString("F1") + "km", settingAtmoStyle, GUILayout.Width(125.0f * GuiDisplaySize.Offset));
GUI.skin = null; GUI.skin = HighLogic.Skin;
GUILayout.EndVertical(); Altitude = GUILayout.HorizontalSlider(Altitude, 0.0f, (float)(CelestialBodies.SelectedBody.CelestialBody.atmosphereDepth));
  GUI.skin = null;
GUILayout.Space(5.0f); GUILayout.EndVertical();
   
GUILayout.BeginVertical(); GUILayout.Space(5.0f);
GUILayout.Label("Velocity: " + this.atmosphericVelocity.ToString("F1") + "m/s", this.settingAtmoStyle, GUILayout.Width(125.0f * GuiDisplaySize.Offset));  
GUI.skin = HighLogic.Skin; GUILayout.BeginVertical();
this.atmosphericVelocity = GUILayout.HorizontalSlider(this.atmosphericVelocity, 0, 2500f); GUILayout.Label("Mach: " + atmosphericMach.ToString("F2"), settingAtmoStyle, GUILayout.Width(125.0f * GuiDisplaySize.Offset));
GUI.skin = null; GUI.skin = HighLogic.Skin;
GUILayout.EndVertical(); atmosphericMach = GUILayout.HorizontalSlider(Mathf.Clamp(atmosphericMach, 0.0f, maxMach), 0.0f, maxMach);
GUILayout.EndHorizontal(); GUI.skin = null;
  GUILayout.EndVertical();
  GUILayout.EndHorizontal();
  }
  catch (Exception ex)
  {
  Logger.Exception(ex, "BuildAdvanced.DrawAtmosphericDetails()");
  }
} }
   
private void DrawBodiesList() private void DrawBodiesList()
{ {
if (CelestialBodies.SystemBody == CelestialBodies.SelectedBody) if (CelestialBodies.SystemBody == CelestialBodies.SelectedBody)
{ {
this.DrawBody(CelestialBodies.SystemBody); DrawBody(CelestialBodies.SystemBody);
} }
else else
{ {
foreach (var body in CelestialBodies.SystemBody.Children) foreach (CelestialBodies.BodyInfo body in CelestialBodies.SystemBody.Children)
{ {
this.DrawBody(body); DrawBody(body);
} }
} }
} }
   
private void DrawBody(CelestialBodies.BodyInfo bodyInfo, int depth = 0) private void DrawBody(CelestialBodies.BodyInfo bodyInfo, int depth = 0)
{ {
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
GUILayout.Space(20.0f * depth); GUILayout.Space(20.0f * depth);
if (GUILayout.Button(bodyInfo.Children.Count > 0 ? bodyInfo.Name + " [" + bodyInfo.Children.Count + "]" : bodyInfo.Name, bodyInfo.Selected && bodyInfo.SelectedDepth == 0 ? this.bodiesButtonActiveStyle : this.bodiesButtonStyle)) if (GUILayout.Button(bodyInfo.Children.Count > 0 ? bodyInfo.Name + " [" + bodyInfo.Children.Count + "]" : bodyInfo.Name, bodyInfo.Selected && bodyInfo.SelectedDepth == 0 ? bodiesButtonActiveStyle : bodiesButtonStyle))
{ {
CelestialBodies.SetSelectedBody(bodyInfo.Name); CelestialBodies.SetSelectedBody(bodyInfo.Name);
this.bodiesList.Resize = true; Altitude = 0.0f;
  bodiesList.Resize = true;
} }
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
if (bodyInfo.Selected) if (bodyInfo.Selected)
{ {
foreach (var body in bodyInfo.Children) for (int i = 0; i < bodyInfo.Children.Count; ++i)
{ {
this.DrawBody(body, depth + 1); DrawBody(bodyInfo.Children[i], depth + 1);
} }
} }
} }
   
/// <summary> /// <summary>
/// Draws the burn time column. /// Draws the burn time column.
/// </summary> /// </summary>
private void DrawBurnTime() private void DrawBurnTime()
{ {
GUILayout.BeginVertical(GUILayout.Width(75.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(75.0f * GuiDisplaySize.Offset));
GUILayout.Label("BURN", this.titleStyle); GUILayout.Label("BURN", titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label(TimeFormatter.ConvertToString(stage.time), this.infoStyle); {
  GUILayout.Label(TimeFormatter.ConvertToString(stage.time), infoStyle);
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
/// <summary> /// <summary>
/// Draws the cost column. /// Draws the cost column.
/// </summary> /// </summary>
private void DrawCost() private void DrawCost()
{ {
GUILayout.BeginVertical(GUILayout.Width(110.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(110.0f * GuiDisplaySize.Offset));
GUILayout.Label("COST", this.titleStyle); GUILayout.Label("COST", titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label(Units.Cost(stage.cost, stage.totalCost), this.infoStyle); {
  GUILayout.Label(Units.Cost(stage.cost, stage.totalCost), infoStyle);
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
/// <summary> /// <summary>
/// Draws the deltaV column. /// Draws the deltaV column.
/// </summary> /// </summary>
private void DrawDeltaV() private void DrawDeltaV()
{ {
GUILayout.BeginVertical(GUILayout.Width(100.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(100.0f * GuiDisplaySize.Offset));
GUILayout.Label("DELTA-V", this.titleStyle); GUILayout.Label("DELTA-V", titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label(stage.deltaV.ToString("N0") + " / " + stage.inverseTotalDeltaV.ToString("N0") + "m/s", this.infoStyle); {
  GUILayout.Label(stage.deltaV.ToString("N0") + " / " + stage.inverseTotalDeltaV.ToString("N0") + "m/s", infoStyle);
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
/// <summary> /// <summary>
/// Draws the specific impluse column. /// Draws the specific impluse column.
/// </summary> /// </summary>
private void DrawIsp() private void DrawIsp()
{ {
GUILayout.BeginVertical(GUILayout.Width(75.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(75.0f * GuiDisplaySize.Offset));
GUILayout.Label("ISP", this.titleStyle); GUILayout.Label("ISP", titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label(stage.isp.ToString("F1") + "s", this.infoStyle); {
  GUILayout.Label(stage.isp.ToString("F1") + "s", infoStyle);
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
/// <summary> /// <summary>
/// Draws the mass column. /// Draws the mass column.
/// </summary> /// </summary>
private void DrawMass() private void DrawMass()
{ {
GUILayout.BeginVertical(GUILayout.Width(110.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(110.0f * GuiDisplaySize.Offset));
GUILayout.Label("MASS", this.titleStyle); GUILayout.Label("MASS", titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label(Units.ToMass(stage.mass, stage.totalMass), this.infoStyle); {
  GUILayout.Label(Units.ToMass(stage.mass, stage.totalMass), infoStyle);
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
/// <summary> /// <summary>
/// Draws the part count column. /// Draws the part count column.
/// </summary> /// </summary>
private void DrawPartCount() private void DrawPartCount()
{ {
GUILayout.BeginVertical(GUILayout.Width(50.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(50.0f * GuiDisplaySize.Offset));
GUILayout.Label("PARTS", this.titleStyle); GUILayout.Label("PARTS", titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label(stage.partCount + " / " + stage.totalPartCount, this.infoStyle); {
  GUILayout.Label(stage.partCount + " / " + stage.totalPartCount, infoStyle);
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
/// <summary> /// <summary>
/// Draws the settings panel. /// Draws the settings panel.
/// </summary> /// </summary>
private void DrawSettings() private void DrawSettings()
{ {
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
GUILayout.Label("Compact mode collapses to the:", this.settingStyle); GUILayout.Label("Compact mode collapses to the:", settingStyle);
this.compactCollapseRight = !GUILayout.Toggle(!this.compactCollapseRight, "LEFT", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)); compactCollapseRight = !GUILayout.Toggle(!compactCollapseRight, "LEFT", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
this.compactCollapseRight = GUILayout.Toggle(this.compactCollapseRight, "RIGHT", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)); compactCollapseRight = GUILayout.Toggle(compactCollapseRight, "RIGHT", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
GUILayout.Label("Simulate using vectored thrust values:"); GUILayout.Label("Simulate using vectored thrust values:", settingStyle);
SimManager.vectoredThrust = GUILayout.Toggle(SimManager.vectoredThrust, "ENABLED", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)); SimManager.vectoredThrust = GUILayout.Toggle(SimManager.vectoredThrust, "ENABLED", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
GUILayout.Label("Build Engineer Overlay:", this.settingStyle); GUILayout.Label("Verbose Simulation Log:", settingStyle);
BuildOverlay.Visible = GUILayout.Toggle(BuildOverlay.Visible, "VISIBLE", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)); SimManager.logOutput = GUILayout.Toggle(SimManager.logOutput, "ENABLED", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
BuildOverlayPartInfo.NamesOnly = GUILayout.Toggle(BuildOverlayPartInfo.NamesOnly, "NAMES ONLY", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));  
BuildOverlayPartInfo.ClickToOpen = GUILayout.Toggle(BuildOverlayPartInfo.ClickToOpen, "CLICK TO OPEN", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));  
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
GUILayout.Label("Flight Engineer activation mode:", this.settingStyle); GUILayout.Label("Build Engineer Overlay:", settingStyle);
FlightEngineerCore.IsCareerMode = GUILayout.Toggle(FlightEngineerCore.IsCareerMode, "CAREER", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)); BuildOverlay.Visible = GUILayout.Toggle(BuildOverlay.Visible, "VISIBLE", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
FlightEngineerCore.IsCareerMode = !GUILayout.Toggle(!FlightEngineerCore.IsCareerMode, "PARTLESS", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)); BuildOverlayPartInfo.NamesOnly = GUILayout.Toggle(BuildOverlayPartInfo.NamesOnly, "NAMES ONLY", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
  BuildOverlayPartInfo.ClickToOpen = GUILayout.Toggle(BuildOverlayPartInfo.ClickToOpen, "CLICK TO OPEN", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
GUILayout.Label("Flight Engineer Career Limitations:", this.settingStyle); GUILayout.Label("Flight Engineer activation mode:", settingStyle);
FlightEngineerCore.IsKerbalLimited = GUILayout.Toggle(FlightEngineerCore.IsKerbalLimited, "KERBAL", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)); FlightEngineerCore.IsCareerMode = GUILayout.Toggle(FlightEngineerCore.IsCareerMode, "CAREER", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
FlightEngineerCore.IsTrackingStationLimited = GUILayout.Toggle(FlightEngineerCore.IsTrackingStationLimited, "TRACKING", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)); FlightEngineerCore.IsCareerMode = !GUILayout.Toggle(!FlightEngineerCore.IsCareerMode, "PARTLESS", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
GUILayout.Label("GUI Size: " + GuiDisplaySize.Increment, this.settingStyle); GUILayout.Label("Flight Engineer Career Limitations:", settingStyle);
if (GUILayout.Button("<", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset))) FlightEngineerCore.IsKerbalLimited = GUILayout.Toggle(FlightEngineerCore.IsKerbalLimited, "KERBAL", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
  FlightEngineerCore.IsTrackingStationLimited = GUILayout.Toggle(FlightEngineerCore.IsTrackingStationLimited, "TRACKING", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
  GUILayout.EndHorizontal();
   
  GUILayout.BeginHorizontal();
  GUILayout.Label("Key Bindings:", settingStyle);
  if (GUILayout.Button("EDIT KEY BINDINGS", buttonStyle, GUILayout.Width(200.0f * GuiDisplaySize.Offset)))
  {
  KeyBinder.Show();
  }
  GUILayout.EndHorizontal();
   
  GUILayout.BeginHorizontal();
  GUILayout.Label("GUI Size: " + GuiDisplaySize.Increment, settingStyle);
  if (GUILayout.Button("<", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)))
{ {
GuiDisplaySize.Increment--; GuiDisplaySize.Increment--;
} }
if (GUILayout.Button(">", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset))) if (GUILayout.Button(">", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)))
{ {
GuiDisplaySize.Increment++; GuiDisplaySize.Increment++;
} }
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.Label("Minimum delay between simulations: " + SimManager.minSimTime.Milliseconds + "ms", this.settingStyle); GUILayout.Label("Minimum delay between simulations: " + SimManager.minSimTime.TotalMilliseconds + "ms", settingStyle);
GUI.skin = HighLogic.Skin; GUI.skin = HighLogic.Skin;
SimManager.minSimTime = new TimeSpan(0, 0, 0, 0, (int)GUILayout.HorizontalSlider(SimManager.minSimTime.Milliseconds, 0, 2000.0f)); SimManager.minSimTime = TimeSpan.FromMilliseconds(GUILayout.HorizontalSlider((float)SimManager.minSimTime.TotalMilliseconds, 0, 2000.0f));
   
GUI.skin = null; GUI.skin = null;
} }
   
/// <summary> /// <summary>
/// Draws the stage number column. /// Draws the stage number column.
/// </summary> /// </summary>
private void DrawStageNumbers() private void DrawStageNumbers()
{ {
GUILayout.BeginVertical(GUILayout.Width(30.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(30.0f * GuiDisplaySize.Offset));
GUILayout.Label(string.Empty, this.titleStyle); GUILayout.Label(string.Empty, titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label("S" + stage.number, this.titleStyle); {
  GUILayout.Label("S" + stage.number, titleStyle);
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
/// <summary> /// <summary>
/// Draws the thrust column. /// Draws the thrust column.
/// </summary> /// </summary>
private void DrawThrust() private void DrawThrust()
{ {
GUILayout.BeginVertical(GUILayout.Width(75.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(75.0f * GuiDisplaySize.Offset));
GUILayout.Label("THRUST", this.titleStyle); GUILayout.Label("THRUST", titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label(stage.thrust.ToForce(), this.infoStyle); {
  GUILayout.Label(stage.thrust.ToForce(), infoStyle);
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
/// <summary> /// <summary>
/// Draws the torque column. /// Draws the torque column.
/// </summary> /// </summary>
private void DrawTorque() private void DrawTorque()
{ {
GUILayout.BeginVertical(GUILayout.Width(75.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(75.0f * GuiDisplaySize.Offset));
GUILayout.Label("TORQUE", this.titleStyle); GUILayout.Label("TORQUE", titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label(stage.maxThrustTorque.ToTorque(), this.infoStyle); {
  GUILayout.Label(stage.maxThrustTorque.ToTorque(), infoStyle);
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
/// <summary> /// <summary>
/// Drwas the thrust to weight ratio column. /// Drwas the thrust to weight ratio column.
/// </summary> /// </summary>
private void DrawTwr() private void DrawTwr()
{ {
GUILayout.BeginVertical(GUILayout.Width(100.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(100.0f * GuiDisplaySize.Offset));
GUILayout.Label("TWR (MAX)", this.titleStyle); GUILayout.Label("TWR (MAX)", titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label(stage.thrustToWeight.ToString("F2") + " (" + stage.maxThrustToWeight.ToString("F2") + ")", this.infoStyle); {
  GUILayout.Label(stage.thrustToWeight.ToString("F2") + " (" + stage.maxThrustToWeight.ToString("F2") + ")", infoStyle);
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
private void EditorLock(bool state) private void EditorLock(bool state)
{ {
if (state) if (state)
{ {
EditorLogic.fetch.Lock(true, true, true, "KER_BuildAdvanced"); InputLockManager.SetControlLock(ControlTypes.All, "KER_BuildAdvanced");
BuildOverlayPartInfo.Hidden = true; BuildOverlayPartInfo.Hidden = true;
this.isEditorLocked = true; isEditorLocked = true;
} }
else else
{ {
EditorLogic.fetch.Unlock("KER_BuildAdvanced"); InputLockManager.SetControlLock(ControlTypes.None, "KER_BuildAdvanced");
BuildOverlayPartInfo.Hidden = false; BuildOverlayPartInfo.Hidden = false;
this.isEditorLocked = false; isEditorLocked = false;
} }
} }
   
private void GetStageInfo() private void GetStageInfo()
{ {
this.stages = SimManager.Stages; stages = SimManager.Stages;
  if (stages != null && stages.Length > 0)
  {
  maxMach = stages[stages.Length - 1].maxMach;
  }
} }
   
/// <summary> /// <summary>
/// Initialises all the styles that are required. /// Initialises all the styles that are required.
/// </summary> /// </summary>
private void InitialiseStyles() private void InitialiseStyles()
{ {
this.windowStyle = new GUIStyle(HighLogic.Skin.window) windowStyle = new GUIStyle(HighLogic.Skin.window)
{ {
alignment = TextAnchor.UpperLeft alignment = TextAnchor.UpperLeft
}; };
   
this.areaStyle = new GUIStyle(HighLogic.Skin.box) areaStyle = new GUIStyle(HighLogic.Skin.box)
{ {
padding = new RectOffset(0, 0, 9, 0) padding = new RectOffset(0, 0, 9, 0)
}; };
   
this.areaSettingStyle = new GUIStyle(HighLogic.Skin.box) areaSettingStyle = new GUIStyle(HighLogic.Skin.box)
{ {
padding = new RectOffset(10, 10, 10, 10) padding = new RectOffset(10, 10, 10, 10)
}; };
   
this.buttonStyle = new GUIStyle(HighLogic.Skin.button) buttonStyle = new GUIStyle(HighLogic.Skin.button)
{ {
normal = normal =
{ {
textColor = Color.white textColor = Color.white
}, },
fontSize = (int)(11 * GuiDisplaySize.Offset), fontSize = (int)(11 * GuiDisplaySize.Offset),
fontStyle = FontStyle.Bold, fontStyle = FontStyle.Bold,
alignment = TextAnchor.MiddleCenter alignment = TextAnchor.MiddleCenter
}; };
   
this.titleStyle = new GUIStyle(HighLogic.Skin.label) titleStyle = new GUIStyle(HighLogic.Skin.label)
{ {
normal = normal =
{ {
textColor = Color.white textColor = Color.white
}, },
fontSize = (int)(11 * GuiDisplaySize.Offset), fontSize = (int)(11 * GuiDisplaySize.Offset),
fontStyle = FontStyle.Bold, fontStyle = FontStyle.Bold,
alignment = TextAnchor.MiddleCenter, alignment = TextAnchor.MiddleCenter,
stretchWidth = true, stretchWidth = true
}; };
   
this.infoStyle = new GUIStyle(HighLogic.Skin.label) infoStyle = new GUIStyle(HighLogic.Skin.label)
{ {
fontSize = (int)(11 * GuiDisplaySize.Offset), fontSize = (int)(11 * GuiDisplaySize.Offset),
fontStyle = FontStyle.Bold, fontStyle = FontStyle.Bold,
alignment = TextAnchor.MiddleCenter, alignment = TextAnchor.MiddleCenter,
stretchWidth = true stretchWidth = true
}; };
   
this.settingStyle = new GUIStyle(this.titleStyle) settingStyle = new GUIStyle(titleStyle)
{ {
alignment = TextAnchor.MiddleLeft, alignment = TextAnchor.MiddleLeft,
stretchWidth = true, stretchWidth = true,
stretchHeight = true stretchHeight = true
}; };
   
this.settingAtmoStyle = new GUIStyle(this.titleStyle) settingAtmoStyle = new GUIStyle(titleStyle)
{ {
margin = new RectOffset(), margin = new RectOffset(),
padding = new RectOffset(), padding = new RectOffset(),
alignment = TextAnchor.UpperLeft alignment = TextAnchor.UpperLeft
}; };
   
this.bodiesButtonStyle = new GUIStyle(HighLogic.Skin.button) bodiesButtonStyle = new GUIStyle(HighLogic.Skin.button)
{ {
margin = new RectOffset(0, 0, 2, 0), margin = new RectOffset(0, 0, 2, 0),
padding = new RectOffset(5, 5, 5, 5), padding = new RectOffset(5, 5, 5, 5),
normal = normal =
{ {
textColor = Color.white textColor = Color.white
}, },
active = active =
{ {
textColor = Color.white textColor = Color.white
}, },
fontSize = (int)(11 * GuiDisplaySize.Offset), fontSize = (int)(11 * GuiDisplaySize.Offset),
fontStyle = FontStyle.Bold, fontStyle = FontStyle.Bold,
alignment = TextAnchor.MiddleCenter, alignment = TextAnchor.MiddleCenter,
fixedHeight = 20.0f fixedHeight = 20.0f
}; };
   
this.bodiesButtonActiveStyle = new GUIStyle(this.bodiesButtonStyle) bodiesButtonActiveStyle = new GUIStyle(bodiesButtonStyle)
{ {
normal = this.bodiesButtonStyle.onNormal, normal = bodiesButtonStyle.onNormal,
hover = this.bodiesButtonStyle.onHover hover = bodiesButtonStyle.onHover
}; };
} }
   
/// <summary> /// <summary>
/// Loads the settings when this object is created. /// Loads the settings when this object is created.
/// </summary> /// </summary>
private void Load() private void Load()
{ {
try try
{ {
var handler = SettingHandler.Load("BuildAdvanced.xml"); SettingHandler handler = SettingHandler.Load("BuildAdvanced.xml");
handler.Get("visible", ref this.visible); handler.Get("visible", ref visible);
this.position.x = handler.Get("windowPositionX", this.position.x); position.x = handler.Get("windowPositionX", position.x);
this.position.y = handler.Get("windowPositionY", this.position.y); position.y = handler.Get("windowPositionY", position.y);
handler.Get("compactMode", ref this.compactMode); handler.Get("compactMode", ref compactMode);
handler.Get("compactCollapseRight", ref this.compactCollapseRight); handler.Get("compactCollapseRight", ref compactCollapseRight);
handler.Get("showAllStages", ref this.showAllStages); handler.Get("showAllStages", ref showAllStages);
handler.Get("showAtmosphericDetails", ref this.showAtmosphericDetails); handler.Get("showAtmosphericDetails", ref showAtmosphericDetails);
handler.Get("showSettings", ref this.showSettings); handler.Get("showSettings", ref showSettings);
CelestialBodies.SetSelectedBody(handler.Get("selectedBodyName", CelestialBodies.SelectedBody.Name)); CelestialBodies.SetSelectedBody(handler.Get("selectedBodyName", CelestialBodies.SelectedBody.Name));
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex, "BuildAdvanced->Load"); Logger.Exception(ex, "BuildAdvanced.Load()");
} }
} }
   
private void OnSizeChanged() private void OnSizeChanged()
{ {
this.InitialiseStyles(); InitialiseStyles();
this.hasChanged = true; hasChanged = true;
} }
   
/// <summary> /// <summary>
/// Draws the OnGUI window. /// Draws the OnGUI window.
/// </summary> /// </summary>
private void Window(int windowId) private void Window(int windowId)
{ {
try try
{ {
  compactModeRect = new Rect(position.width - 70.0f * GuiDisplaySize.Offset, 5.0f, 65.0f * GuiDisplaySize.Offset, 20.0f);
   
// Draw the compact mode toggle. // Draw the compact mode toggle.
if (GUI.Toggle(new Rect(this.position.width - 70.0f * GuiDisplaySize.Offset, 5.0f, 65.0f * GuiDisplaySize.Offset, 20.0f), this.compactMode, "COMPACT", this.buttonStyle) != this.compactMode) if (GUI.Toggle(compactModeRect, compactMode, "COMPACT", buttonStyle) != compactMode)
{ {
this.hasChanged = true; hasChanged = true;
this.compactCheck = 2; compactCheck = 2;
this.compactRight = this.position.xMax; compactRight = position.xMax;
this.compactMode = !this.compactMode; compactMode = !compactMode;
} }
   
// When not in compact mode draw the 'All Stages' and 'Atmospheric' toggles. // When not in compact mode draw the 'All Stages' and 'Atmospheric' toggles.
if (!this.compactMode) if (!compactMode)
{ {
if (GUI.Toggle(new Rect(this.position.width - 143.0f * GuiDisplaySize.Offset, 5.0f, 70.0f * GuiDisplaySize.Offset, 20.0f), this.showSettings, "SETTINGS", this.buttonStyle) != this.showSettings) if (GUI.Toggle(new Rect(position.width - 143.0f * GuiDisplaySize.Offset, 5.0f, 70.0f * GuiDisplaySize.Offset, 20.0f), showSettings, "SETTINGS", buttonStyle) != showSettings)
{ {
this.hasChanged = true; hasChanged = true;
this.showSettings = !this.showSettings; showSettings = !showSettings;
} }
   
if (GUI.Toggle(new Rect(this.position.width - 226.0f * GuiDisplaySize.Offset, 5.0f, 80.0f * GuiDisplaySize.Offset, 20.0f), this.showAllStages, "ALL STAGES", this.buttonStyle) != this.showAllStages) if (GUI.Toggle(new Rect(position.width - 226.0f * GuiDisplaySize.Offset, 5.0f, 80.0f * GuiDisplaySize.Offset, 20.0f), showAllStages, "ALL STAGES", buttonStyle) != showAllStages)
{ {
this.hasChanged = true; hasChanged = true;
this.showAllStages = !this.showAllStages; showAllStages = !showAllStages;
} }
   
if (GUI.Toggle(new Rect(this.position.width - 324.0f * GuiDisplaySize.Offset, 5.0f, 95.0f * GuiDisplaySize.Offset, 20.0f), this.showAtmosphericDetails, "ATMOSPHERIC", this.buttonStyle) != this.showAtmosphericDetails) if (GUI.Toggle(new Rect(position.width - 324.0f * GuiDisplaySize.Offset, 5.0f, 95.0f * GuiDisplaySize.Offset, 20.0f), showAtmosphericDetails, "ATMOSPHERIC", buttonStyle) != showAtmosphericDetails)
{ {
this.hasChanged = true; hasChanged = true;
this.showAtmosphericDetails = !this.showAtmosphericDetails; showAtmosphericDetails = !showAtmosphericDetails;
} }
   
this.bodiesListPosition = new Rect(this.position.width - 452.0f * GuiDisplaySize.Offset, 5.0f, 125.0f * GuiDisplaySize.Offset, 20.0f); bodiesListPosition = new Rect(position.width - 452.0f * GuiDisplaySize.Offset, 5.0f, 125.0f * GuiDisplaySize.Offset, 20.0f);
this.bodiesList.enabled = GUI.Toggle(this.bodiesListPosition, this.bodiesList.enabled, "BODY: " + CelestialBodies.SelectedBody.Name.ToUpper(), this.buttonStyle); bodiesList.enabled = GUI.Toggle(bodiesListPosition, bodiesList.enabled, "BODY: " + CelestialBodies.SelectedBody.Name.ToUpper(), buttonStyle);
this.bodiesList.SetPosition(this.bodiesListPosition.Translate(this.position)); bodiesList.SetPosition(bodiesListPosition.Translate(position));
  }
  else
  {
  if (GUI.Toggle(new Rect(position.width - 133.0f * GuiDisplaySize.Offset, 5.0f, 60.0f * GuiDisplaySize.Offset, 20.0f), showAtmosphericDetails, "ATMO", buttonStyle) != showAtmosphericDetails)
  {
  hasChanged = true;
  showAtmosphericDetails = !showAtmosphericDetails;
  }
} }
   
// Draw the main informational display box. // Draw the main informational display box.
if (!this.compactMode) if (!compactMode)
{ {
GUILayout.BeginHorizontal(this.areaStyle); GUILayout.BeginHorizontal(areaStyle);
this.DrawStageNumbers(); DrawStageNumbers();
this.DrawPartCount(); DrawPartCount();
this.DrawCost(); DrawCost();
this.DrawMass(); DrawMass();
this.DrawIsp(); DrawIsp();
this.DrawThrust(); DrawThrust();
this.DrawTorque(); DrawTorque();
this.DrawTwr(); DrawTwr();
this.DrawDeltaV(); DrawDeltaV();
this.DrawBurnTime(); DrawBurnTime();
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
if (this.showAtmosphericDetails) if (showAtmosphericDetails && !compactMode)
{ {
GUILayout.BeginVertical(this.areaSettingStyle); GUILayout.BeginVertical(areaSettingStyle);
this.DrawAtmosphericDetails(); DrawAtmosphericDetails();
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
if (this.showSettings) if (showSettings)
{ {
GUILayout.BeginVertical(this.areaSettingStyle); GUILayout.BeginVertical(areaSettingStyle);
this.DrawSettings(); DrawSettings();
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
} }
else // Draw only a few details when in compact mode. else // Draw only a few details when in compact mode.
{ {
GUILayout.BeginHorizontal(this.areaStyle); GUILayout.BeginHorizontal(areaStyle);
this.DrawStageNumbers(); DrawStageNumbers();
this.DrawTwr(); DrawTwr();
this.DrawDeltaV(); DrawDeltaV();
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
   
GUI.DragWindow(); GUI.DragWindow();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex, "BuildAdvanced.Window()");
} }
} }
   
#endregion  
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives  
   
using System;  
using System.Collections.Generic;  
using System.Linq;  
   
using KerbalEngineer.Extensions;  
using KerbalEngineer.Helpers;  
   
using UnityEngine;  
   
#endregion  
   
namespace KerbalEngineer.Editor namespace KerbalEngineer.Editor
{ {
  using System;
  using System.Collections.Generic;
  using Extensions;
  using Helpers;
  using UnityEngine;
   
public class BuildOverlayPartInfo : MonoBehaviour public class BuildOverlayPartInfo : MonoBehaviour
{ {
#region Fields  
   
private static bool clickToOpen = true; private static bool clickToOpen = true;
  private static ModuleGenerator.GeneratorResource generatorResource;
  private static ModuleAlternator moduleAlternator;
  private static ModuleDataTransmitter moduleDataTransmitter;
  private static ModuleDeployableSolarPanel moduleDeployableSolarPanel;
  private static ModuleGenerator moduleGenerator;
  private static ModuleGimbal moduleGimbal;
  private static ModuleParachute moduleParachute;
  private static ModuleRCS moduleRcs;
  private static ModuleReactionWheel moduleReactionWheel;
  private static ModuleResource moduleResource;
  private static ModuleScienceExperiment moduleScienceExperiment;
private static bool namesOnly; private static bool namesOnly;
  private static Part part;
  private static PartInfoItem partInfoItem;
  private static PartResource partResource;
  private static Propellant propellant;
  private static PartExtensions.ProtoModuleDecoupler protoModuleDecoupler;
  private static PartExtensions.ProtoModuleEngine protoModuleEngine;
private static bool visible = true; private static bool visible = true;
   
private readonly List<PartInfoItem> infoItems = new List<PartInfoItem>(); private readonly List<PartInfoItem> infoItems = new List<PartInfoItem>();
   
private Rect position; private Rect position;
private Part selectedPart; private Part selectedPart;
private bool showInfo; private bool showInfo;
private bool skipFrame; private bool skipFrame;
   
#endregion  
   
#region Properties  
   
public static bool ClickToOpen public static bool ClickToOpen
{ {
get { return clickToOpen; } get
set { clickToOpen = value; } {
  return clickToOpen;
  }
  set
  {
  clickToOpen = value;
  }
} }
   
public static bool Hidden { get; set; } public static bool Hidden { get; set; }
   
public static bool NamesOnly public static bool NamesOnly
{ {
get { return namesOnly; } get
set { namesOnly = value; } {
  return namesOnly;
  }
  set
  {
  namesOnly = value;
  }
} }
   
public static bool Visible public static bool Visible
{ {
get { return visible; } get
set { visible = value; } {
} return visible;
  }
#endregion set
  {
#region Methods: protected visible = value;
  }
  }
   
protected void OnGUI() protected void OnGUI()
{ {
try try
{ {
if (!Visible || Hidden || this.selectedPart == null) if (!Visible || Hidden || selectedPart == null)
{ {
return; return;
} }
   
this.position = GUILayout.Window(this.GetInstanceID(), this.position, this.Window, String.Empty, BuildOverlay.WindowStyle); position = GUILayout.Window(GetInstanceID(), position, Window, String.Empty, BuildOverlay.WindowStyle);
} }
catch (Exception ex) catch (Exception ex)
   
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
protected void Update() protected void Update()
{ {
try try
{ {
if (!Visible || Hidden || EditorLogic.RootPart == null || EditorLogic.fetch.editorScreen != EditorScreen.Parts) if (!Visible || Hidden || EditorLogic.RootPart == null || EditorLogic.fetch.editorScreen != EditorScreen.Parts)
{ {
return; return;
} }
   
this.position.x = Mathf.Clamp(Input.mousePosition.x + 16.0f, 0.0f, Screen.width - this.position.width); position.x = Mathf.Clamp(Input.mousePosition.x + 16.0f, 0.0f, Screen.width - position.width);
this.position.y = Mathf.Clamp(Screen.height - Input.mousePosition.y, 0.0f, Screen.height - this.position.height); position.y = Mathf.Clamp(Screen.height - Input.mousePosition.y, 0.0f, Screen.height - position.height);
if (this.position.x < Input.mousePosition.x + 20.0f) if (position.x < Input.mousePosition.x + 20.0f)
{ {
this.position.y = Mathf.Clamp(this.position.y + 20.0f, 0.0f, Screen.height - this.position.height); position.y = Mathf.Clamp(position.y + 20.0f, 0.0f, Screen.height - position.height);
} }
if (this.position.x < Input.mousePosition.x + 16.0f && this.position.y < Screen.height - Input.mousePosition.y) if (position.x < Input.mousePosition.x + 16.0f && position.y < Screen.height - Input.mousePosition.y)
{ {
this.position.x = Input.mousePosition.x - 3 - this.position.width; position.x = Input.mousePosition.x - 3 - position.width;
} }
   
this.infoItems.Clear(); part = EditorLogic.fetch.ship.parts.Find(p => p.stackIcon.highlightIcon) ?? EditorLogic.SelectedPart;
var part = EditorLogic.fetch.ship.parts.Find(p => p.stackIcon.highlightIcon) ?? EditorLogic.SelectedPart;  
if (part != null) if (part != null)
{ {
if (!part.Equals(this.selectedPart)) if (!part.Equals(selectedPart))
{ {
this.selectedPart = part; selectedPart = part;
this.ResetInfo(); ResetInfo();
} }
if (NamesOnly || this.skipFrame) if (NamesOnly || skipFrame)
{ {
this.skipFrame = false; skipFrame = false;
return; return;
} }
   
this.SetCostInfo(); if (!showInfo && Input.GetMouseButtonDown(2))
this.SetMassItems(); {
this.SetResourceItems(); showInfo = true;
this.SetEngineInfo(); }
this.SetAlternatorInfo(); else if (ClickToOpen && showInfo && Input.GetMouseButtonDown(2))
this.SetGimbalInfo(); {
this.SetRcsInfo(); ResetInfo();
this.SetParachuteInfo(); }
this.SetSasInfo();  
this.SetReactionWheelInfo(); if (showInfo)
this.SetSolarPanelInfo(); {
this.SetGeneratorInfo(); PartInfoItem.Release(infoItems);
this.SetDecouplerInfo(); infoItems.Clear();
this.SetTransmitterInfo(); SetCostInfo();
this.SetScienceExperimentInfo(); SetMassItems();
this.SetScienceContainerInfo(); SetResourceItems();
this.SetSingleActivationInfo(); SetEngineInfo();
  SetAlternatorInfo();
if (!this.showInfo && Input.GetMouseButtonDown(2)) SetGimbalInfo();
{ SetRcsInfo();
this.showInfo = true; SetParachuteInfo();
} SetSasInfo();
else if (ClickToOpen && this.showInfo && Input.GetMouseButtonDown(2)) SetReactionWheelInfo();
{ SetSolarPanelInfo();
this.ResetInfo(); SetGeneratorInfo();
  SetDecouplerInfo();
  SetTransmitterInfo();
  SetScienceExperimentInfo();
  SetScienceContainerInfo();
  SetSingleActivationInfo();
} }
} }
else else
{ {
this.selectedPart = null; selectedPart = null;
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion  
   
#region Methods: private  
   
private void ResetInfo() private void ResetInfo()
{ {
this.showInfo = !clickToOpen; showInfo = !clickToOpen;
this.skipFrame = true; skipFrame = true;
this.position.width = namesOnly || clickToOpen ? 0.0f : 200.0f; position.width = namesOnly || clickToOpen ? 0.0f : 200.0f;
this.position.height = 0.0f; position.height = 0.0f;
} }
   
private void SetAlternatorInfo() private void SetAlternatorInfo()
{ {
if (!this.selectedPart.HasModule<ModuleAlternator>()) moduleAlternator = selectedPart.GetModule<ModuleAlternator>();
{ if (moduleAlternator != null)
return; {
} infoItems.Add(PartInfoItem.Create("Alternator"));
  for (int i = 0; i < moduleAlternator.outputResources.Count; ++i)
var alternator = this.selectedPart.GetModule<ModuleAlternator>(); {
this.infoItems.Add(new PartInfoItem("Alternator")); moduleResource = moduleAlternator.outputResources[i];
foreach (var resource in alternator.outputResources) infoItems.Add(PartInfoItem.Create("\t" + moduleResource.name, moduleResource.rate.ToRate()));
{ }
this.infoItems.Add(new PartInfoItem("\t" + resource.name, resource.rate.ToRate()));  
} }
} }
   
private void SetCostInfo() private void SetCostInfo()
{ {
this.infoItems.Add(new PartInfoItem("Cost", Units.ConcatF(this.selectedPart.GetCostDry(), this.selectedPart.GetCostWet()))); infoItems.Add(PartInfoItem.Create("Cost", Units.ConcatF(selectedPart.GetCostDry(), selectedPart.GetCostWet())));
} }
   
private void SetDecouplerInfo() private void SetDecouplerInfo()
{ {
if (!this.selectedPart.IsDecoupler()) protoModuleDecoupler = selectedPart.GetProtoModuleDecoupler();
{ if (protoModuleDecoupler != null)
return; {
} infoItems.Add(PartInfoItem.Create("Ejection Force", protoModuleDecoupler.EjectionForce.ToForce()));
  if (protoModuleDecoupler.IsOmniDecoupler)
var decoupler = this.selectedPart.GetProtoModuleDecoupler(); {
this.infoItems.Add(new PartInfoItem("Ejection Force", decoupler.EjectionForce.ToForce())); infoItems.Add(PartInfoItem.Create("Omni-directional"));
if (decoupler.IsOmniDecoupler) }
{  
this.infoItems.Add(new PartInfoItem("Omni-directional"));  
} }
} }
   
private void SetEngineInfo() private void SetEngineInfo()
{ {
if (!this.selectedPart.IsEngine()) protoModuleEngine = selectedPart.GetProtoModuleEngine();
{ if (protoModuleEngine != null)
return; {
} infoItems.Add(PartInfoItem.Create("Thrust", Units.ToForce(protoModuleEngine.MinimumThrust, protoModuleEngine.MaximumThrust)));
  infoItems.Add(PartInfoItem.Create("Isp", Units.ConcatF(protoModuleEngine.GetSpecificImpulse(1.0f), protoModuleEngine.GetSpecificImpulse(0.0f)) + "s"));
var engine = this.selectedPart.GetProtoModuleEngine(); if (protoModuleEngine.Propellants.Count > 0)
this.infoItems.Add(new PartInfoItem("Thrust", Units.ToForce(engine.MinimumThrust, engine.MaximumThrust))); {
this.infoItems.Add(new PartInfoItem("Isp", Units.ConcatF(engine.GetSpecificImpulse(1.0f), engine.GetSpecificImpulse(0.0f)) + "s")); infoItems.Add(PartInfoItem.Create("Propellants"));
if (engine.Propellants.Count > 0)  
{ float totalRatio = 0.0f;
this.infoItems.Add(new PartInfoItem("Propellants")); for (int i = 0; i < protoModuleEngine.Propellants.Count; ++i)
var totalRatio = engine.Propellants.Sum(p => p.ratio); {
foreach (var propellant in engine.Propellants) totalRatio = totalRatio + protoModuleEngine.Propellants[i].ratio;
{ }
this.infoItems.Add(new PartInfoItem("\t" + propellant.name, (propellant.ratio / totalRatio).ToPercent()));  
  for (int i = 0; i < protoModuleEngine.Propellants.Count; ++i)
  {
  propellant = protoModuleEngine.Propellants[i];
  infoItems.Add(PartInfoItem.Create("\t" + propellant.name, (propellant.ratio / totalRatio).ToPercent()));
  }
} }
} }
} }
   
private void SetGeneratorInfo() private void SetGeneratorInfo()
{ {
if (!this.selectedPart.HasModule<ModuleGenerator>()) moduleGenerator = selectedPart.GetModule<ModuleGenerator>();
{ if (moduleGenerator != null)
return; {
} if (moduleGenerator.inputList.Count > 0)
  {
var generator = this.selectedPart.GetModule<ModuleGenerator>(); infoItems.Add(PartInfoItem.Create("Generator Input"));
if (generator.inputList.Count > 0) for (int i = 0; i < moduleGenerator.inputList.Count; ++i)
{ {
this.infoItems.Add(new PartInfoItem("Generator Input")); generatorResource = moduleGenerator.inputList[i];
foreach (var resource in generator.inputList) infoItems.Add(PartInfoItem.Create("\t" + generatorResource.name, generatorResource.rate.ToRate()));
{ }
this.infoItems.Add(new PartInfoItem("\t" + resource.name, resource.rate.ToRate())); }
} if (moduleGenerator.outputList.Count > 0)
} {
if (generator.outputList.Count > 0) infoItems.Add(PartInfoItem.Create("Generator Output"));
{ for (int i = 0; i < moduleGenerator.outputList.Count; ++i)
this.infoItems.Add(new PartInfoItem("Generator Output")); {
foreach (var resource in generator.outputList) generatorResource = moduleGenerator.outputList[i];
{ infoItems.Add(PartInfoItem.Create("\t" + generatorResource.name, generatorResource.rate.ToRate()));
this.infoItems.Add(new PartInfoItem("\t" + resource.name, resource.rate.ToRate())); }
} }
} if (moduleGenerator.isAlwaysActive)
if (generator.isAlwaysActive) {
{ infoItems.Add(PartInfoItem.Create("Generator is Always Active"));
this.infoItems.Add(new PartInfoItem("Generator is Always Active")); }
} }
} }
   
private void SetGimbalInfo() private void SetGimbalInfo()
{ {
if (!this.selectedPart.HasModule<ModuleGimbal>()) moduleGimbal = selectedPart.GetModule<ModuleGimbal>();
{ if (moduleGimbal != null)
return; {
} infoItems.Add(PartInfoItem.Create("Thrust Vectoring", moduleGimbal.gimbalRange.ToString("F2")));
  }
var gimbal = this.selectedPart.GetModule<ModuleGimbal>();  
this.infoItems.Add(new PartInfoItem("Thrust Vectoring", gimbal.gimbalRange.ToString("F2")));  
} }
   
private void SetMassItems() private void SetMassItems()
{ {
if (this.selectedPart.physicalSignificance == Part.PhysicalSignificance.FULL) if (selectedPart.physicalSignificance == Part.PhysicalSignificance.FULL)
{ {
this.infoItems.Add(new PartInfoItem("Mass", Units.ToMass(this.selectedPart.GetDryMass(), this.selectedPart.GetWetMass()))); infoItems.Add(PartInfoItem.Create("Mass", Units.ToMass(selectedPart.GetDryMass(), selectedPart.GetWetMass())));
} }
} }
   
private void SetParachuteInfo() private void SetParachuteInfo()
{ {
if (!this.selectedPart.HasModule<ModuleParachute>()) moduleParachute = selectedPart.GetModule<ModuleParachute>();
{ if (moduleParachute != null)
return; {
} infoItems.Add(PartInfoItem.Create("Deployed Drag", Units.ConcatF(moduleParachute.semiDeployedDrag, moduleParachute.fullyDeployedDrag)));
  infoItems.Add(PartInfoItem.Create("Deployment Altitude", moduleParachute.deployAltitude.ToDistance()));
var parachute = this.selectedPart.GetModule<ModuleParachute>(); infoItems.Add(PartInfoItem.Create("Deployment Pressure", moduleParachute.minAirPressureToOpen.ToString("F2")));
this.infoItems.Add(new PartInfoItem("Deployed Drag", Units.ConcatF(parachute.semiDeployedDrag, parachute.fullyDeployedDrag))); }
this.infoItems.Add(new PartInfoItem("Deployment Altitude", parachute.deployAltitude.ToDistance()));  
this.infoItems.Add(new PartInfoItem("Deployment Pressure", parachute.minAirPressureToOpen.ToString("F2")));  
} }
   
private void SetRcsInfo() private void SetRcsInfo()
{ {
if (!this.selectedPart.HasModule<ModuleRCS>()) moduleRcs = selectedPart.GetModule<ModuleRCS>();
{ if (moduleRcs != null)
return; {
} infoItems.Add(PartInfoItem.Create("Thruster Power", moduleRcs.thrusterPower.ToForce()));
  infoItems.Add(PartInfoItem.Create("Specific Impulse", Units.ConcatF(moduleRcs.atmosphereCurve.Evaluate(1.0f), moduleRcs.atmosphereCurve.Evaluate(0.0f)) + "s"));
var rcs = this.selectedPart.GetModule<ModuleRCS>(); }
this.infoItems.Add(new PartInfoItem("Thruster Power", rcs.thrusterPower.ToForce()));  
this.infoItems.Add(new PartInfoItem("Specific Impulse", Units.ConcatF(rcs.atmosphereCurve.Evaluate(1.0f), rcs.atmosphereCurve.Evaluate(0.0f)) + "s"));  
} }
   
private void SetReactionWheelInfo() private void SetReactionWheelInfo()
{ {
if (!this.selectedPart.HasModule<ModuleReactionWheel>()) moduleReactionWheel = selectedPart.GetModule<ModuleReactionWheel>();
{ if (moduleReactionWheel != null)
return; {
} infoItems.Add(PartInfoItem.Create("Reaction Wheel Torque"));
  infoItems.Add(PartInfoItem.Create("\tPitch", moduleReactionWheel.PitchTorque.ToTorque()));
var reactionWheel = this.selectedPart.GetModule<ModuleReactionWheel>(); infoItems.Add(PartInfoItem.Create("\tRoll", moduleReactionWheel.RollTorque.ToTorque()));
this.infoItems.Add(new PartInfoItem("Reaction Wheel Torque")); infoItems.Add(PartInfoItem.Create("\tYaw", moduleReactionWheel.YawTorque.ToTorque()));
this.infoItems.Add(new PartInfoItem("\tPitch", reactionWheel.PitchTorque.ToTorque())); for (int i = 0; i < moduleReactionWheel.inputResources.Count; ++i)
this.infoItems.Add(new PartInfoItem("\tRoll", reactionWheel.RollTorque.ToTorque())); {
this.infoItems.Add(new PartInfoItem("\tYaw", reactionWheel.YawTorque.ToTorque())); moduleResource = moduleReactionWheel.inputResources[i];
foreach (var resource in reactionWheel.inputResources) infoItems.Add(PartInfoItem.Create("\t" + moduleResource.name, moduleResource.rate.ToRate()));
{ }
this.infoItems.Add(new PartInfoItem("\t" + resource.name, resource.rate.ToRate()));  
} }
} }
   
private void SetResourceItems() private void SetResourceItems()
{ {
if (this.selectedPart.Resources.list.Any(r => !r.hideFlow)) bool visibleResources = false;
{ for (int i = 0; i < selectedPart.Resources.list.Count; ++i)
this.infoItems.Add(new PartInfoItem("Resources")); {
foreach (var resource in this.selectedPart.Resources.list.Where(r => !r.hideFlow)) if (selectedPart.Resources.list[i].hideFlow == false)
{ {
this.infoItems.Add(resource.GetDensity() > 0 visibleResources = true;
? new PartInfoItem("\t" + resource.info.name, "(" + resource.GetMass().ToMass() + ") " + resource.amount.ToString("F1")) break;
: new PartInfoItem("\t" + resource.info.name, resource.amount.ToString("F1"))); }
  }
  if (visibleResources)
  {
  infoItems.Add(PartInfoItem.Create("Resources"));
  for (int i = 0; i < selectedPart.Resources.list.Count; ++i)
  {
  partResource = selectedPart.Resources.list[i];
   
  if (partResource.hideFlow == false)
  {
  infoItems.Add(partResource.GetDensity() > 0
  ? PartInfoItem.Create("\t" + partResource.info.name, "(" + partResource.GetMass().ToMass() + ") " + partResource.amount.ToString("F1"))
  : PartInfoItem.Create("\t" + partResource.info.name, partResource.amount.ToString("F1")));
  }
} }
} }
} }
   
private void SetSasInfo() private void SetSasInfo()
{ {
if (this.selectedPart.HasModule<ModuleSAS>()) if (selectedPart.HasModule<ModuleSAS>())
{ {
this.infoItems.Add(new PartInfoItem("SAS Equiped")); infoItems.Add(PartInfoItem.Create("SAS Equiped"));
} }
} }
   
private void SetScienceContainerInfo() private void SetScienceContainerInfo()
{ {
if (this.selectedPart.HasModule<ModuleScienceContainer>()) if (selectedPart.HasModule<ModuleScienceContainer>())
{ {
this.infoItems.Add(new PartInfoItem("Science Container")); infoItems.Add(PartInfoItem.Create("Science Container"));
} }
} }
   
private void SetScienceExperimentInfo() private void SetScienceExperimentInfo()
{ {
if (!this.selectedPart.HasModule<ModuleScienceExperiment>()) moduleScienceExperiment = selectedPart.GetModule<ModuleScienceExperiment>();
{ if (moduleScienceExperiment != null)
return; {
} infoItems.Add(PartInfoItem.Create("Science Experiment", moduleScienceExperiment.experimentActionName));
  infoItems.Add(PartInfoItem.Create("\tTransmit Efficiency", moduleScienceExperiment.xmitDataScalar.ToPercent()));
var experiment = this.selectedPart.GetModule<ModuleScienceExperiment>(); if (moduleScienceExperiment.rerunnable == false)
this.infoItems.Add(new PartInfoItem("Science Experiment", experiment.experimentActionName)); {
this.infoItems.Add(new PartInfoItem("\tTransmit Efficiency", experiment.xmitDataScalar.ToPercent())); infoItems.Add(PartInfoItem.Create("\tSingle Usage"));
if (!experiment.rerunnable) }
{  
this.infoItems.Add(new PartInfoItem("\tSingle Usage"));  
} }
} }
   
private void SetSingleActivationInfo() private void SetSingleActivationInfo()
{ {
if (this.selectedPart.HasModule<ModuleAnimateGeneric>(m => m.isOneShot)) if (selectedPart.HasModule<ModuleAnimateGeneric>(m => m.isOneShot))
{ {
this.infoItems.Add(new PartInfoItem("Single Activation")); infoItems.Add(PartInfoItem.Create("Single Activation"));
} }
} }
   
private void SetSolarPanelInfo() private void SetSolarPanelInfo()
{ {
if (!this.selectedPart.HasModule<ModuleDeployableSolarPanel>()) moduleDeployableSolarPanel = selectedPart.GetModule<ModuleDeployableSolarPanel>();
{ if (moduleDeployableSolarPanel != null)
return; {
} infoItems.Add(PartInfoItem.Create("Charge Rate", moduleDeployableSolarPanel.chargeRate.ToRate()));
  if (moduleDeployableSolarPanel.isBreakable)
var solarPanel = this.selectedPart.GetModule<ModuleDeployableSolarPanel>(); {
this.infoItems.Add(new PartInfoItem("Charge Rate", solarPanel.chargeRate.ToRate())); infoItems.Add(PartInfoItem.Create("Breakable"));
if (solarPanel.isBreakable) }
{ if (moduleDeployableSolarPanel.sunTracking)
this.infoItems.Add(new PartInfoItem("Breakable")); {
} infoItems.Add(PartInfoItem.Create("Sun Tracking"));
if (solarPanel.sunTracking) }
{  
this.infoItems.Add(new PartInfoItem("Sun Tracking"));  
} }
} }
   
private void SetTransmitterInfo() private void SetTransmitterInfo()
{ {
if (!this.selectedPart.HasModule<ModuleDataTransmitter>()) moduleDataTransmitter = selectedPart.GetModule<ModuleDataTransmitter>();
{ if (moduleDataTransmitter != null)
return; {
} infoItems.Add(PartInfoItem.Create("Packet Size", moduleDataTransmitter.packetSize.ToString("F2") + " Mits"));
  infoItems.Add(PartInfoItem.Create("Bandwidth", (moduleDataTransmitter.packetInterval * moduleDataTransmitter.packetSize).ToString("F2") + "Mits/sec"));
var transmitter = this.selectedPart.GetModule<ModuleDataTransmitter>(); infoItems.Add(PartInfoItem.Create(moduleDataTransmitter.requiredResource, moduleDataTransmitter.packetResourceCost.ToString("F2") + "/Packet"));
this.infoItems.Add(new PartInfoItem("Packet Size", transmitter.packetSize.ToString("F2") + " Mits")); }
this.infoItems.Add(new PartInfoItem("Bandwidth", (transmitter.packetInterval * transmitter.packetSize).ToString("F2") + "Mits/sec"));  
this.infoItems.Add(new PartInfoItem(transmitter.requiredResource, transmitter.packetResourceCost.ToString("F2") + "/Packet"));  
} }
   
private void Window(int windowId) private void Window(int windowId)
{ {
try try
{ {
GUILayout.Label(this.selectedPart.partInfo.title, BuildOverlay.TitleStyle); GUILayout.Label(selectedPart.partInfo.title, BuildOverlay.TitleStyle);
if (this.showInfo) if (showInfo)
{ {
foreach (var item in this.infoItems) for (int i = 0; i < infoItems.Count; ++i)
{ {
  partInfoItem = infoItems[i];
GUILayout.Space(2.0f); GUILayout.Space(2.0f);
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
if (item.Value != null) if (partInfoItem.Value != null)
{ {
GUILayout.Label(item.Name + ":", BuildOverlay.NameStyle); GUILayout.Label(partInfoItem.Name + ":", BuildOverlay.NameStyle);
GUILayout.Space(25.0f); GUILayout.Space(25.0f);
GUILayout.Label(item.Value, BuildOverlay.ValueStyle); GUILayout.Label(partInfoItem.Value, BuildOverlay.ValueStyle);
} }
else else
{ {
GUILayout.Label(item.Name, BuildOverlay.NameStyle); GUILayout.Label(partInfoItem.Name, BuildOverlay.NameStyle);
} }
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
} }
else if (this.infoItems.Count > 0) else if (clickToOpen && namesOnly == false)
{ {
GUILayout.Space(2.0f); GUILayout.Space(2.0f);
GUILayout.Label("Click middle mouse to show more info...", BuildOverlay.NameStyle); GUILayout.Label("Click middle mouse to show more info...", BuildOverlay.NameStyle);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion  
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using System;  
using System.Collections.Generic;  
using System.Linq;  
   
using KerbalEngineer.Extensions;  
   
using UnityEngine;  
   
#endregion #endregion
   
namespace KerbalEngineer.Editor namespace KerbalEngineer.Editor
{ {
  using System;
  using System.Collections.Generic;
  using Extensions;
  using UnityEngine;
   
public class BuildOverlayResources : MonoBehaviour public class BuildOverlayResources : MonoBehaviour
{ {
#region Fields #region Fields
   
private static bool visible = true; private static bool visible = true;
   
private readonly Dictionary<int, ResourceInfoItem> resources = new Dictionary<int, ResourceInfoItem>(); private readonly Dictionary<int, ResourceInfoItem> resources = new Dictionary<int, ResourceInfoItem>();
   
private bool open = true; private bool open = true;
private float openPercent; private float openPercent;
private GUIContent tabContent; private GUIContent tabContent;
private Rect tabPosition; private Rect tabPosition;
private Vector2 tabSize; private Vector2 tabSize;
private Rect windowPosition = new Rect(0.0f, 0.0f, BuildOverlay.MinimumWidth, 0.0f); private Rect windowPosition = new Rect(0.0f, 0.0f, BuildOverlay.MinimumWidth, 0.0f);
   
#endregion #endregion
   
#region Properties #region Properties
   
public static bool Visible public static bool Visible
{ {
get { return visible; } get
set { visible = value; } {
  return visible;
  }
  set
  {
  visible = value;
  }
} }
   
public bool Open public bool Open
{ {
get { return this.open; } get
set { this.open = value; } {
} return open;
  }
  set
  {
  open = value;
  }
  }
#endregion #endregion
   
#region Methods: protected #region Methods: protected
   
protected void OnGUI() protected void OnGUI()
{ {
try try
{ {
if (!Visible || this.resources.Count == 0 || EditorLogic.fetch.editorScreen != EditorScreen.Parts) if (!Visible || resources.Count == 0 || EditorLogic.fetch.editorScreen != EditorScreen.Parts)
{ {
return; return;
} }
   
this.open = GUI.Toggle(this.tabPosition, this.open, this.tabContent, BuildOverlay.TabStyle); open = GUI.Toggle(tabPosition, open, tabContent, BuildOverlay.TabStyle);
if (this.openPercent > 0.0) if (openPercent > 0.0)
{ {
this.windowPosition = GUILayout.Window(this.GetInstanceID(), this.windowPosition, this.Window, String.Empty, BuildOverlay.WindowStyle); windowPosition = GUILayout.Window(GetInstanceID(), windowPosition, Window, String.Empty, BuildOverlay.WindowStyle);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
protected void Start() protected void Start()
{ {
try try
{ {
this.tabContent = new GUIContent("RESOURCES"); tabContent = new GUIContent("RESOURCES");
this.tabSize = BuildOverlay.TabStyle.CalcSize(this.tabContent); tabSize = BuildOverlay.TabStyle.CalcSize(tabContent);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
protected void Update() protected void Update()
{ {
try try
{ {
if (!Visible) if (!Visible)
{ {
return; return;
} }
   
this.SetResources(); SetResources();
this.SetSlidePosition(); SetSlidePosition();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion #endregion
   
#region Methods: private #region Methods: private
  private static Part part;
  private static PartResource partResource;
   
private void SetResources() private void SetResources()
{ {
var previousCount = this.resources.Count; int previousCount = resources.Count;
this.resources.Clear(); resources.Clear();
foreach (var resource in EditorLogic.fetch.ship.parts.SelectMany(p => p.Resources.list).Where(r => r.amount > 0.0))  
{ for (int i = 0; i < EditorLogic.fetch.ship.parts.Count; ++i)
if (this.resources.ContainsKey(resource.info.id)) {
{ part = EditorLogic.fetch.ship.parts[i];
this.resources[resource.info.id].Amount += resource.amount; for (int j = 0; j < part.Resources.list.Count; ++j)
} {
else partResource = part.Resources.list[j];
{  
this.resources.Add(resource.info.id, new ResourceInfoItem(resource)); if (resources.ContainsKey(partResource.info.id))
} {
} resources[partResource.info.id].Amount += partResource.amount;
  }
if (this.resources.Count < previousCount) else
{ {
this.windowPosition.height = 0; resources.Add(partResource.info.id, new ResourceInfoItem(partResource));
  }
  }
  }
   
  if (resources.Count < previousCount)
  {
  windowPosition.height = 0;
} }
} }
   
private void SetSlidePosition() private void SetSlidePosition()
{ {
if (this.open && this.openPercent < 1.0f) if (open && openPercent < 1.0f)
{ {
this.openPercent = Mathf.Clamp(this.openPercent + Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f); openPercent = Mathf.Clamp(openPercent + Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f);
} }
else if (!this.open && this.openPercent > 0.0f) else if (!open && openPercent > 0.0f)
{ {
this.openPercent = Mathf.Clamp(this.openPercent - Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f); openPercent = Mathf.Clamp(openPercent - Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f);
} }
   
this.windowPosition.x = BuildOverlay.BuildOverlayVessel.WindowPosition.xMax + 5.0f; windowPosition.x = BuildOverlay.BuildOverlayVessel.WindowPosition.xMax + 5.0f;
this.windowPosition.y = Mathf.Lerp(Screen.height, Screen.height - this.windowPosition.height, this.openPercent); windowPosition.y = Mathf.Lerp(Screen.height, Screen.height - windowPosition.height, openPercent);
this.tabPosition.width = this.tabSize.x; tabPosition.width = tabSize.x;
this.tabPosition.height = this.tabSize.y; tabPosition.height = tabSize.y;
this.tabPosition.x = this.windowPosition.x; tabPosition.x = windowPosition.x;
this.tabPosition.y = this.windowPosition.y - this.tabPosition.height; tabPosition.y = windowPosition.y - tabPosition.height;
} }
   
private void Window(int windowId) private void Window(int windowId)
{ {
try try
{ {
var firstItem = true; bool firstItem = true;
foreach (var resource in this.resources) foreach (KeyValuePair<int, ResourceInfoItem> resource in resources)
{ {
if (!firstItem) if (!firstItem)
{ {
GUILayout.Space(2.0f); GUILayout.Space(2.0f);
} }
firstItem = false; firstItem = false;
   
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
   
GUILayout.Label(resource.Value.Name + ":", BuildOverlay.NameStyle); GUILayout.Label(resource.Value.Name + ":", BuildOverlay.NameStyle);
GUILayout.Space(50.0f); GUILayout.Space(50.0f);
if (resource.Value.Mass > 0.0) if (resource.Value.Mass > 0.0)
{ {
GUILayout.Label("(" + resource.Value.Mass.ToMass() + ") " + resource.Value.Amount.ToString("N1"), BuildOverlay.ValueStyle); GUILayout.Label("(" + resource.Value.Mass.ToMass() + ") " + resource.Value.Amount.ToString("N1"), BuildOverlay.ValueStyle);
} }
else else
{ {
GUILayout.Label(resource.Value.Amount.ToString("N1"), BuildOverlay.ValueStyle); GUILayout.Label(resource.Value.Amount.ToString("N1"), BuildOverlay.ValueStyle);
} }
   
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
#endregion #endregion
   
namespace KerbalEngineer.Editor namespace KerbalEngineer.Editor
{ {
#region Using Directives #region Using Directives
   
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using Helpers; using Helpers;
using UnityEngine; using UnityEngine;
using VesselSimulator; using VesselSimulator;
   
#endregion #endregion
   
public class BuildOverlayVessel : MonoBehaviour public class BuildOverlayVessel : MonoBehaviour
{ {
#region Constants #region Constants
   
private const float Width = 175.0f; private const float Width = 175.0f;
   
#endregion #endregion
   
#region Fields #region Fields
   
private static bool visible = true; private static bool visible = true;
   
private readonly List<PartInfoItem> infoItems = new List<PartInfoItem>(); private readonly List<PartInfoItem> infoItems = new List<PartInfoItem>();
   
private Stage lastStage; private Stage lastStage;
private bool open = true; private bool open = true;
private float openPercent; private float openPercent;
private GUIContent tabContent; private GUIContent tabContent;
private Rect tabPosition; private Rect tabPosition;
private Vector2 tabSize; private Vector2 tabSize;
private Rect windowPosition = new Rect(330.0f, 0.0f, Width, 0.0f); private Rect windowPosition = new Rect(330.0f, 0.0f, Width, 0.0f);
   
#endregion #endregion
   
#region Properties #region Properties
   
public static bool Visible public static bool Visible
{ {
get { return visible; } get
set { visible = value; } {
  return visible;
  }
  set
  {
  visible = value;
  }
} }
   
public bool Open public bool Open
{ {
get { return this.open; } get
set { this.open = value; } {
  return open;
  }
  set
  {
  open = value;
  }
} }
   
public Rect WindowPosition public Rect WindowPosition
{ {
get { return this.windowPosition; } get
  {
  return windowPosition;
  }
} }
   
public float WindowX public float WindowX
{ {
get { return this.windowPosition.x; } get
set { this.windowPosition.x = value; } {
} return windowPosition.x;
  }
  set
  {
  windowPosition.x = value;
  }
  }
#endregion #endregion
   
#region Methods #region Methods
   
protected void Awake() protected void Awake()
{ {
try try
{ {
SimManager.OnReady -= this.GetStageInfo; SimManager.OnReady -= GetStageInfo;
SimManager.OnReady += this.GetStageInfo; SimManager.OnReady += GetStageInfo;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
protected void OnGUI() protected void OnGUI()
{ {
try try
{ {
if (!Visible || EditorLogic.RootPart == null || EditorLogic.fetch.editorScreen != EditorScreen.Parts) if (!Visible || EditorLogic.RootPart == null || EditorLogic.fetch.editorScreen != EditorScreen.Parts)
{ {
return; return;
} }
   
this.open = GUI.Toggle(this.tabPosition, this.open, this.tabContent, BuildOverlay.TabStyle); open = GUI.Toggle(tabPosition, open, tabContent, BuildOverlay.TabStyle);
if (this.openPercent > 0.0) if (openPercent > 0.0)
{ {
this.windowPosition = GUILayout.Window(this.GetInstanceID(), this.windowPosition, this.VesselWindow, String.Empty, BuildOverlay.WindowStyle); windowPosition = GUILayout.Window(GetInstanceID(), windowPosition, VesselWindow, String.Empty, BuildOverlay.WindowStyle);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
protected void Start() protected void Start()
{ {
try try
{ {
this.tabContent = new GUIContent("VESSEL"); tabContent = new GUIContent("VESSEL");
this.tabSize = BuildOverlay.TabStyle.CalcSize(this.tabContent); tabSize = BuildOverlay.TabStyle.CalcSize(tabContent);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
protected void Update() protected void Update()
{ {
try try
{ {
if (!Visible || EditorLogic.RootPart == null) if (!Visible || EditorLogic.RootPart == null)
{ {
return; return;
} }
   
if (this.openPercent > 0.0) if (openPercent > 0.0)
{ {
this.SetVesselInfo(); SetVesselInfo();
} }
   
this.SetSlidePosition(); SetSlidePosition();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
private void GetStageInfo() private void GetStageInfo()
{ {
this.lastStage = SimManager.LastStage; lastStage = SimManager.LastStage;
} }
   
private void SetSlidePosition() private void SetSlidePosition()
{ {
if (this.open && this.openPercent < 1.0f) if (open && openPercent < 1.0f)
{ {
this.openPercent = Mathf.Clamp(this.openPercent + Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f); openPercent = Mathf.Clamp(openPercent + Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f);
} }
else if (!this.open && this.openPercent > 0.0f) else if (!open && openPercent > 0.0f)
{ {
this.openPercent = Mathf.Clamp(this.openPercent - Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f); openPercent = Mathf.Clamp(openPercent - Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f);
} }
   
this.windowPosition.y = Mathf.Lerp(Screen.height, Screen.height - this.windowPosition.height, this.openPercent); windowPosition.y = Mathf.Lerp(Screen.height, Screen.height - windowPosition.height, openPercent);
if (this.windowPosition.width < Width) if (windowPosition.width < Width)
{ {
this.windowPosition.width = Width; windowPosition.width = Width;
} }
this.tabPosition.width = this.tabSize.x; tabPosition.width = tabSize.x;
this.tabPosition.height = this.tabSize.y; tabPosition.height = tabSize.y;
this.tabPosition.x = this.windowPosition.x; tabPosition.x = windowPosition.x;
this.tabPosition.y = this.windowPosition.y - this.tabPosition.height; tabPosition.y = windowPosition.y - tabPosition.height;
} }
   
private void SetVesselInfo() private void SetVesselInfo()
{ {
SimManager.Gravity = CelestialBodies.SelectedBody.Gravity; SimManager.Gravity = CelestialBodies.SelectedBody.Gravity;
   
if (BuildAdvanced.Instance.ShowAtmosphericDetails) if (BuildAdvanced.Instance.ShowAtmosphericDetails)
{ {
SimManager.Atmosphere = CelestialBodies.SelectedBody.Atmosphere * 0.01; SimManager.Atmosphere = CelestialBodies.SelectedBody.GetAtmospheres(BuildAdvanced.Altitude);
} }
else else
{ {
SimManager.Atmosphere = 0.0; SimManager.Atmosphere = 0.0;
} }
   
SimManager.RequestSimulation(); SimManager.RequestSimulation();
SimManager.TryStartSimulation(); SimManager.TryStartSimulation();
   
if (this.lastStage != null) if (lastStage != null)
{ {
this.infoItems.Clear(); PartInfoItem.Release(infoItems);
this.infoItems.Add(new PartInfoItem("Delta-V", this.lastStage.deltaV.ToString("N0") + " / " + this.lastStage.totalDeltaV.ToString("N0") + "m/s")); infoItems.Clear();
this.infoItems.Add(new PartInfoItem("Mass", Units.ToMass(this.lastStage.mass, this.lastStage.totalMass))); infoItems.Add(PartInfoItem.Create("Delta-V", lastStage.deltaV.ToString("N0") + " / " + lastStage.totalDeltaV.ToString("N0") + "m/s"));
this.infoItems.Add(new PartInfoItem("TWR", this.lastStage.thrustToWeight.ToString("F2") + " (" + this.lastStage.maxThrustToWeight.ToString("F2") + ")")); infoItems.Add(PartInfoItem.Create("Mass", Units.ToMass(lastStage.mass, lastStage.totalMass)));
this.infoItems.Add(new PartInfoItem("Parts", this.lastStage.partCount + " / " + this.lastStage.totalPartCount)); infoItems.Add(PartInfoItem.Create("TWR", lastStage.thrustToWeight.ToString("F2") + " (" + lastStage.maxThrustToWeight.ToString("F2") + ")"));
  infoItems.Add(PartInfoItem.Create("Parts", lastStage.partCount + " / " + lastStage.totalPartCount));
} }
} }
   
private void VesselWindow(int windowId) private void VesselWindow(int windowId)
{ {
try try
{ {
var firstItem = true; bool firstItem = true;
foreach (var item in this.infoItems) foreach (PartInfoItem item in infoItems)
{ {
if (!firstItem) if (!firstItem)
{ {
GUILayout.Space(2.0f); GUILayout.Space(2.0f);
} }
firstItem = false; firstItem = false;
   
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
if (item.Value != null) if (item.Value != null)
{ {
GUILayout.Label(item.Name + ":", BuildOverlay.NameStyle); GUILayout.Label(item.Name + ":", BuildOverlay.NameStyle);
GUILayout.FlexibleSpace(); GUILayout.FlexibleSpace();
GUILayout.Label(item.Value, BuildOverlay.ValueStyle); GUILayout.Label(item.Value, BuildOverlay.ValueStyle);
} }
else else
{ {
GUILayout.Label(item.Name, BuildOverlay.NameStyle); GUILayout.Label(item.Name, BuildOverlay.NameStyle);
} }
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using System; using System;
   
using UnityEngine; using UnityEngine;
   
#endregion #endregion
   
namespace KerbalEngineer.Editor namespace KerbalEngineer.Editor
{ {
[KSPAddon(KSPAddon.Startup.EditorAny, false)] [KSPAddon(KSPAddon.Startup.EditorAny, false)]
public class BuildToolbar : MonoBehaviour public class BuildToolbar : MonoBehaviour
{ {
#region Fields #region Fields
   
private ApplicationLauncherButton button; private ApplicationLauncherButton button;
   
#endregion #endregion
   
#region Methods: private #region Methods: private
   
private void Awake() private void Awake()
{ {
GameEvents.onGUIApplicationLauncherReady.Add(this.OnGuiAppLauncherReady); GameEvents.onGUIApplicationLauncherReady.Add(this.OnGuiAppLauncherReady);
Logger.Log("BuildToolbar->Awake"); Logger.Log("BuildToolbar->Awake");
  }
   
  private void Start()
  {
  if (button == null)
  {
  OnGuiAppLauncherReady();
  }
} }
   
private void OnDestroy() private void OnDestroy()
{ {
GameEvents.onGUIApplicationLauncherReady.Remove(this.OnGuiAppLauncherReady); GameEvents.onGUIApplicationLauncherReady.Remove(this.OnGuiAppLauncherReady);
if (this.button != null) if (this.button != null)
{ {
ApplicationLauncher.Instance.RemoveModApplication(this.button); ApplicationLauncher.Instance.RemoveModApplication(this.button);
} }
Logger.Log("BuildToolbar->OnDestroy"); Logger.Log("BuildToolbar->OnDestroy");
} }
   
private void OnGuiAppLauncherReady() private void OnGuiAppLauncherReady()
{ {
try try
{ {
this.button = ApplicationLauncher.Instance.AddModApplication( this.button = ApplicationLauncher.Instance.AddModApplication(
() => BuildAdvanced.Instance.Visible = true, () => BuildAdvanced.Instance.Visible = true,
() => BuildAdvanced.Instance.Visible = false, () => BuildAdvanced.Instance.Visible = false,
null, null,
null, null,
null, null,
null, null,
ApplicationLauncher.AppScenes.ALWAYS, ApplicationLauncher.AppScenes.ALWAYS,
GameDatabase.Instance.GetTexture("KerbalEngineer/Textures/ToolbarIcon", false) GameDatabase.Instance.GetTexture("KerbalEngineer/Textures/ToolbarIcon", false)
); );
Logger.Log("BuildToolbar->OnGuiAppLauncherReady"); Logger.Log("BuildToolbar->OnGuiAppLauncherReady");
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex, "BuildToolbar->OnGuiAppLauncherReady"); Logger.Exception(ex, "BuildToolbar->OnGuiAppLauncherReady");
} }
} }
   
private void Update() private void Update()
{ {
try try
{ {
if (this.button == null) if (this.button == null)
{ {
return; return;
} }
   
if (EditorLogic.fetch != null && EditorLogic.fetch.ship.parts.Count > 0) if (EditorLogic.fetch != null && EditorLogic.fetch.ship.parts.Count > 0)
{ {
if (BuildAdvanced.Instance.Visible && this.button.State != RUIToggleButton.ButtonState.TRUE) if (BuildAdvanced.Instance.Visible && this.button.State != RUIToggleButton.ButtonState.TRUE)
{ {
this.button.SetTrue(); this.button.SetTrue();
} }
else if (!BuildAdvanced.Instance.Visible && this.button.State != RUIToggleButton.ButtonState.FALSE) else if (!BuildAdvanced.Instance.Visible && this.button.State != RUIToggleButton.ButtonState.FALSE)
{ {
this.button.SetFalse(); this.button.SetFalse();
} }
} }
else if (this.button.State != RUIToggleButton.ButtonState.DISABLED) else if (this.button.State != RUIToggleButton.ButtonState.DISABLED)
{ {
this.button.Disable(); this.button.Disable();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex, "BuildToolbar->Update"); Logger.Exception(ex, "BuildToolbar->Update");
} }
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
namespace KerbalEngineer.Editor namespace KerbalEngineer.Editor
{ {
  using System.Collections.Generic;
  using VesselSimulator;
   
public class PartInfoItem public class PartInfoItem
{ {
#region Constructors private static readonly Pool<PartInfoItem> pool = new Pool<PartInfoItem>(Create, Reset);
   
public PartInfoItem(string name)  
{  
this.Name = name;  
}  
   
public PartInfoItem(string name, string value)  
{  
this.Name = name;  
this.Value = value;  
}  
   
#endregion  
   
#region Properties  
   
public string Name { get; set; } public string Name { get; set; }
   
public string Value { get; set; } public string Value { get; set; }
   
#endregion private static PartInfoItem Create()
  {
  return new PartInfoItem();
  }
   
  public void Release()
  {
  pool.Release(this);
  }
   
  public static void Release(List<PartInfoItem> objList)
  {
  for (int i = 0; i < objList.Count; ++i)
  {
  objList[i].Release();
  }
  }
   
  private static void Reset(PartInfoItem obj)
  {
  obj.Name = string.Empty;
  obj.Value = string.Empty;
  }
   
  public static PartInfoItem Create(string name)
  {
  return New(name);
  }
   
  public static PartInfoItem Create(string name, string value)
  {
  return New(name, value);
  }
   
  public static PartInfoItem New(string name)
  {
  PartInfoItem obj = pool.Borrow();
   
  obj.Name = name;
  obj.Value = string.Empty;
   
  return obj;
  }
   
  public static PartInfoItem New(string name, string value)
  {
  PartInfoItem obj = pool.Borrow();
   
  obj.Name = name;
  obj.Value = value;
   
  return obj;
  }
} }
} }
// //
// Kerbal Engineer Redux // Copyright (C) 2015 CYBUTEK
//  
// Copyright (C) 2014 CYBUTEK  
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives  
   
using System.IO;  
using System.Reflection;  
   
#endregion  
   
namespace KerbalEngineer namespace KerbalEngineer
{ {
public class EngineerGlobals using System.IO;
  using System.Reflection;
   
  public static class EngineerGlobals
{ {
#region Constants  
   
/// <summary> /// <summary>
/// Current version of the Kerbal Engineer assembly. /// Current version of the Kerbal Engineer assembly.
/// </summary> /// </summary>
public const string AssemblyVersion = "1.0.14"; public const string ASSEMBLY_VERSION = "1.0.19.2";
   
#endregion  
   
#region Fields  
   
private static string assemblyFile; private static string assemblyFile;
private static string assemblyName; private static string assemblyName;
private static string assemblyPath; private static string assemblyPath;
  private static string settingsPath;
#endregion  
   
#region Properties  
   
/// <summary> /// <summary>
/// Gets the Kerbal Engineer assembly's path including the file name. /// Gets the Kerbal Engineer assembly's path including the file name.
/// </summary> /// </summary>
public static string AssemblyFile public static string AssemblyFile
{ {
get { return assemblyFile ?? (assemblyFile = Assembly.GetExecutingAssembly().Location); } get
  {
  return assemblyFile ?? (assemblyFile = Assembly.GetExecutingAssembly().Location);
  }
} }
   
/// <summary> /// <summary>
/// Gets the Kerbal Engineer assembly's file name. /// Gets the Kerbal Engineer assembly's file name.
/// </summary> /// </summary>
public static string AssemblyName public static string AssemblyName
{ {
get { return assemblyName ?? (assemblyName = new FileInfo(AssemblyFile).Name); } get
  {
  return assemblyName ?? (assemblyName = new FileInfo(AssemblyFile).Name);
  }
} }
   
/// <summary> /// <summary>
/// Gets the Kerbal Engineer assembly's path excluding the file name. /// Gets the Kerbal Engineer assembly's path excluding the file name.
/// </summary> /// </summary>
public static string AssemblyPath public static string AssemblyPath
{ {
get { return assemblyPath ?? (assemblyPath = AssemblyFile.Replace(new FileInfo(AssemblyFile).Name, "")); } get
  {
  return assemblyPath ?? (assemblyPath = AssemblyFile.Replace(new FileInfo(AssemblyFile).Name, ""));
  }
} }
   
#endregion /// <summary>
  /// Gets the settings directory path.
  /// </summary>
  public static string SettingsPath
  {
  get
  {
  if (string.IsNullOrEmpty(settingsPath))
  {
  settingsPath = Path.Combine(AssemblyPath, "Settings");
  }
  return settingsPath;
  }
  }
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2015 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives  
   
using KerbalEngineer.Helpers;  
   
#endregion  
   
namespace KerbalEngineer.Extensions namespace KerbalEngineer.Extensions
{ {
  using Helpers;
   
public static class DoubleExtensions public static class DoubleExtensions
{ {
#region Methods: public  
   
public static double Clamp(this double value, double lower, double higher) public static double Clamp(this double value, double lower, double higher)
{ {
return value < lower ? lower : value > higher ? higher : value; return value < lower ? lower : value > higher ? higher : value;
} }
   
public static string ToAcceleration(this double value) public static string ToAcceleration(this double value)
{ {
return Units.ToAcceleration(value); return Units.ToAcceleration(value);
} }
   
public static string ToAngle(this double value) public static string ToAngle(this double value)
{ {
return Units.ToAngle(value); return Units.ToAngle(value);
} }
   
public static string ToDistance(this double value) public static string ToDistance(this double value)
{ {
return Units.ToDistance(value); return Units.ToDistance(value);
} }
   
public static string ToTorque(this double value) public static string ToFlux(this double value)
{ {
return Units.ToTorque(value); return Units.ToFlux(value);
} }
   
public static string ToForce(this double value) public static string ToForce(this double value)
{ {
return Units.ToForce(value); return Units.ToForce(value);
  }
   
  public static string ToMach(this double value)
  {
  return Units.ToMach(value);
} }
   
public static string ToMass(this double value) public static string ToMass(this double value)
{ {
return Units.ToMass(value); return Units.ToMass(value);
} }
   
public static string ToPercent(this double value) public static string ToPercent(this double value)
{ {
return Units.ToPercent(value); return Units.ToPercent(value);
} }
   
public static string ToRate(this double value) public static string ToRate(this double value)
{ {
return Units.ToRate(value); return Units.ToRate(value);
} }
   
public static string ToSpeed(this double value) public static string ToSpeed(this double value)
{ {
return Units.ToSpeed(value); return Units.ToSpeed(value);
} }
   
#endregion public static string ToTemperature(this double value)
  {
  return Units.ToTemperature(value);
  }
   
  public static string ToTorque(this double value)
  {
  return Units.ToTorque(value);
  }
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2015 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives  
   
using KerbalEngineer.Helpers;  
   
#endregion  
   
namespace KerbalEngineer.Extensions namespace KerbalEngineer.Extensions
{ {
  using Helpers;
   
public static class FloatExtensions public static class FloatExtensions
{ {
#region Methods: public  
   
public static string ToAcceleration(this float value) public static string ToAcceleration(this float value)
{ {
return Units.ToAcceleration(value); return Units.ToAcceleration(value);
} }
   
public static string ToAngle(this float value) public static string ToAngle(this float value)
{ {
return Units.ToAngle(value); return Units.ToAngle(value);
} }
   
public static string ToDistance(this float value) public static string ToDistance(this float value)
{ {
return Units.ToDistance(value); return Units.ToDistance(value);
} }
   
  public static string ToFlux(this float value)
  {
  return Units.ToFlux(value);
  }
   
public static string ToForce(this float value) public static string ToForce(this float value)
{ {
return Units.ToForce(value); return Units.ToForce(value);
} }
   
public static string ToTorque(this float value) public static string ToMach(this float value)
{ {
return Units.ToTorque(value); return Units.ToMach(value);
} }
   
public static string ToMass(this float value) public static string ToMass(this float value)
{ {
return Units.ToMass(value); return Units.ToMass(value);
} }
   
public static string ToPercent(this float value) public static string ToPercent(this float value)
{ {
return Units.ToPercent(value); return Units.ToPercent(value);
} }
   
public static string ToRate(this float value) public static string ToRate(this float value)
{ {
return Units.ToRate(value); return Units.ToRate(value);
} }
   
public static string ToSpeed(this float value) public static string ToSpeed(this float value)
{ {
return Units.ToSpeed(value); return Units.ToSpeed(value);
} }
   
#endregion public static string ToTemperature(this float value)
  {
  return Units.ToTemperature(value);
  }
   
  public static string ToTorque(this float value)
  {
  return Units.ToTorque(value);
  }
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using System; using System;
   
using KerbalEngineer.Helpers; using KerbalEngineer.Helpers;
   
using UnityEngine; using UnityEngine;
   
#endregion #endregion
   
namespace KerbalEngineer.Extensions namespace KerbalEngineer.Extensions
{ {
public static class OrbitExtensions public static class OrbitExtensions
{ {
#region Constants #region Constants
   
public const double Tau = Math.PI * 2.0; public const double Tau = Math.PI * 2.0;
   
#endregion #endregion
   
#region Methods: public #region Methods: public
   
public static double GetAngleToAscendingNode(this Orbit orbit) public static double GetAngleToAscendingNode(this Orbit orbit)
{ {
return GetAngleToTrueAnomaly(orbit, GetTrueAnomalyOfAscendingNode(orbit)); return GetAngleToTrueAnomaly(orbit, GetTrueAnomalyOfAscendingNode(orbit));
} }
   
public static double GetAngleToDescendingNode(this Orbit orbit) public static double GetAngleToDescendingNode(this Orbit orbit)
{ {
return GetAngleToTrueAnomaly(orbit, GetTrueAnomalyOfDescendingNode(orbit)); return GetAngleToTrueAnomaly(orbit, GetTrueAnomalyOfDescendingNode(orbit));
} }
   
public static double GetAngleToPrograde(this Orbit orbit) public static double GetAngleToPrograde(this Orbit orbit)
{ {
return GetAngleToPrograde(orbit, Planetarium.GetUniversalTime()); return GetAngleToPrograde(orbit, Planetarium.GetUniversalTime());
} }
   
public static double GetAngleToPrograde(this Orbit orbit, double universalTime) public static double GetAngleToPrograde(this Orbit orbit, double universalTime)
{ {
if (orbit.referenceBody == CelestialBodies.SystemBody.CelestialBody) if (orbit.referenceBody == CelestialBodies.SystemBody.CelestialBody)
{ {
return 0.0; return 0.0;
} }
   
var angle = AngleHelper.GetAngleBetweenVectors(orbit.getRelativePositionAtUT(universalTime), Vector3d orbitVector = orbit.getRelativePositionAtUT(universalTime);
Vector3d.Exclude(orbit.GetOrbitNormal(), orbit.referenceBody.orbit.getRelativePositionAtUT(universalTime))); orbitVector.z = 0.0;
   
angle = AngleHelper.Clamp360(angle - 90.0); Vector3d bodyVector = orbit.referenceBody.orbit.getOrbitalVelocityAtUT(universalTime);
  bodyVector.z = 0.0;
   
return orbit.inclination > 90.0 ? angle : 360.0 - angle; double angle = AngleHelper.GetAngleBetweenVectors(bodyVector, orbitVector);
   
  return AngleHelper.Clamp360(orbit.inclination < 90.0 ? angle : 360.0 - angle);
} }
   
public static double GetAngleToRetrograde(this Orbit orbit) public static double GetAngleToRetrograde(this Orbit orbit)
{ {
return GetAngleToRetrograde(orbit, Planetarium.GetUniversalTime()); return GetAngleToRetrograde(orbit, Planetarium.GetUniversalTime());
} }
   
public static double GetAngleToRetrograde(this Orbit orbit, double universalTime) public static double GetAngleToRetrograde(this Orbit orbit, double universalTime)
{ {
if (orbit.referenceBody == CelestialBodies.SystemBody.CelestialBody) if (orbit.referenceBody == CelestialBodies.SystemBody.CelestialBody)
{ {
return 0.0; return 0.0;
} }
   
var angle = AngleHelper.GetAngleBetweenVectors(orbit.getRelativePositionAtUT(universalTime), Vector3d orbitVector = orbit.getRelativePositionAtUT(universalTime);
Vector3d.Exclude(orbit.GetOrbitNormal(), orbit.referenceBody.orbit.getRelativePositionAtUT(universalTime))); orbitVector.z = 0.0;
   
angle = AngleHelper.Clamp360(angle + 90.0); Vector3d bodyVector = orbit.referenceBody.orbit.getOrbitalVelocityAtUT(universalTime);
  bodyVector.z = 0.0;
   
return orbit.inclination > 90.0 ? angle : 360.0 - angle; double angle = AngleHelper.GetAngleBetweenVectors(-bodyVector, orbitVector);
   
  return AngleHelper.Clamp360(orbit.inclination < 90.0 ? angle : 360.0 - angle);
} }
   
public static double GetAngleToTrueAnomaly(this Orbit orbit, double trueAnomaly) public static double GetAngleToTrueAnomaly(this Orbit orbit, double trueAnomaly)
{ {
return AngleHelper.Clamp360(trueAnomaly - orbit.trueAnomaly); return AngleHelper.Clamp360(trueAnomaly - orbit.trueAnomaly);
} }
   
public static double GetAngleToVector(this Orbit orbit, Vector3d vector) public static double GetAngleToVector(this Orbit orbit, Vector3d vector)
{ {
return GetAngleToTrueAnomaly(orbit, GetTrueAnomalyFromVector(orbit, Vector3d.Exclude(orbit.GetOrbitNormal(), vector))); return GetAngleToTrueAnomaly(orbit, GetTrueAnomalyFromVector(orbit, Vector3d.Exclude(orbit.GetOrbitNormal(), vector)));
} }
   
public static double GetPhaseAngle(this Orbit orbit, Orbit target) public static double GetPhaseAngle(this Orbit orbit, Orbit target)
{ {
var angle = AngleHelper.GetAngleBetweenVectors(Vector3d.Exclude(orbit.GetOrbitNormal(), target.pos), orbit.pos); var angle = AngleHelper.GetAngleBetweenVectors(Vector3d.Exclude(orbit.GetOrbitNormal(), target.pos), orbit.pos);
return (orbit.semiMajorAxis < target.semiMajorAxis) ? angle : angle - 360.0; return (orbit.semiMajorAxis < target.semiMajorAxis) ? angle : angle - 360.0;
} }
   
public static double GetRelativeInclination(this Orbit orbit, Orbit target) public static double GetRelativeInclination(this Orbit orbit, Orbit target)
{ {
return Vector3d.Angle(orbit.GetOrbitNormal(), target.GetOrbitNormal()); return Vector3d.Angle(orbit.GetOrbitNormal(), target.GetOrbitNormal());
} }
   
public static double GetTimeToAscendingNode(this Orbit orbit) public static double GetTimeToAscendingNode(this Orbit orbit)
{ {
return GetTimeToTrueAnomaly(orbit, GetTrueAnomalyOfAscendingNode(orbit)); return GetTimeToTrueAnomaly(orbit, GetTrueAnomalyOfAscendingNode(orbit));
} }
   
public static double GetTimeToDescendingNode(this Orbit orbit) public static double GetTimeToDescendingNode(this Orbit orbit)
{ {
return GetTimeToTrueAnomaly(orbit, GetTrueAnomalyOfDescendingNode(orbit)); return GetTimeToTrueAnomaly(orbit, GetTrueAnomalyOfDescendingNode(orbit));
} }
   
public static double GetTimeToTrueAnomaly(this Orbit orbit, double trueAnomaly) public static double GetTimeToTrueAnomaly(this Orbit orbit, double trueAnomaly)
{ {
var time = orbit.GetDTforTrueAnomaly(trueAnomaly * Mathf.Deg2Rad, orbit.period); var time = orbit.GetDTforTrueAnomaly(trueAnomaly * Mathf.Deg2Rad, orbit.period);
return time < 0.0 ? time + orbit.period : time; return time < 0.0 ? time + orbit.period : time;
} }
   
public static double GetTimeToVector(this Orbit orbit, Vector3d vector) public static double GetTimeToVector(this Orbit orbit, Vector3d vector)
{ {
return GetTimeToTrueAnomaly(orbit, GetTrueAnomalyFromVector(orbit, vector)); return GetTimeToTrueAnomaly(orbit, GetTrueAnomalyFromVector(orbit, vector));
} }
   
public static double GetTrueAnomalyFromVector(this Orbit orbit, Vector3d vector) public static double GetTrueAnomalyFromVector(this Orbit orbit, Vector3d vector)
{ {
return orbit.GetTrueAnomalyOfZupVector(vector) * Mathf.Rad2Deg; return orbit.GetTrueAnomalyOfZupVector(vector) * Mathf.Rad2Deg;
} }
   
public static double GetTrueAnomalyOfAscendingNode(this Orbit orbit) public static double GetTrueAnomalyOfAscendingNode(this Orbit orbit)
{ {
return 360.0 - orbit.argumentOfPeriapsis; return 360.0 - orbit.argumentOfPeriapsis;
} }
   
public static double GetTrueAnomalyOfDescendingNode(this Orbit orbit) public static double GetTrueAnomalyOfDescendingNode(this Orbit orbit)
{ {
return 180.0 - orbit.argumentOfPeriapsis; return 180.0 - orbit.argumentOfPeriapsis;
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives  
   
using System;  
using System.Collections.Generic;  
using System.Linq;  
   
#endregion  
   
namespace KerbalEngineer.Extensions namespace KerbalEngineer.Extensions
{ {
  using System;
  using System.Collections.Generic;
using CompoundParts; using CompoundParts;
   
public static class PartExtensions public static class PartExtensions
{ {
#region Methods: public //private static Part cachePart;
  //private static PartModule cachePartModule;
  //private static PartResource cachePartResource;
   
/// <summary> /// <summary>
/// Gets whether the part contains a specific resource. /// Gets whether the part contains a specific resource.
/// </summary> /// </summary>
public static bool ContainsResource(this Part part, int resourceId) public static bool ContainsResource(this Part part, int resourceId)
{ {
return part.Resources.Contains(resourceId); return part.Resources.Contains(resourceId);
} }
   
/// <summary> /// <summary>
/// Gets whether the part contains resources. /// Gets whether the part contains resources.
/// </summary> /// </summary>
public static bool ContainsResources(this Part part) public static bool ContainsResources(this Part part)
{ {
return part.Resources.list.Count(p => p.amount > 0d) > 0; for (int i = 0; i < part.Resources.list.Count; ++i)
  {
  if (part.Resources.list[i].amount > 0.0)
  {
  return true;
  }
  }
  return false;
} }
   
/// <summary> /// <summary>
/// Gets whether the part has fuel. /// Gets whether the part has fuel.
/// </summary> /// </summary>
  /* not used
public static bool EngineHasFuel(this Part part) public static bool EngineHasFuel(this Part part)
{ {
if (part.HasModule<ModuleEngines>()) PartModule cachePartModule = GetModule<ModuleEngines>(part);
{ if (cachePartModule != null)
return part.GetModuleEngines().getFlameoutState; {
} return (cachePartModule as ModuleEngines).getFlameoutState;
if (part.HasModule<MultiModeEngine>()) }
{  
return part.GetModuleMultiModeEngine().getFlameoutState; cachePartModule = GetModuleMultiModeEngine(part);
  if (cachePartModule != null)
  {
  return (cachePartModule as ModuleEnginesFX).getFlameoutState;
} }
   
return false; return false;
} }
  */
/// <summary> /// <summary>
/// Gets the cost of the part excluding resources. /// Gets the cost of the part excluding resources.
/// </summary> /// </summary>
public static double GetCostDry(this Part part) public static double GetCostDry(this Part part)
{ {
return part.partInfo.cost - GetResourceCostMax(part) + part.GetModuleCosts(0.0f); return part.partInfo.cost - GetResourceCostMax(part) + part.GetModuleCosts(0.0f);
} }
   
/// <summary> /// <summary>
/// Gets the cost of the part including maximum resources. /// Gets the cost of the part including maximum resources.
/// </summary> /// </summary>
public static double GetCostMax(this Part part) public static double GetCostMax(this Part part)
{ {
return part.partInfo.cost + part.GetModuleCosts(0.0f); return part.partInfo.cost + part.GetModuleCosts(0.0f);
} }
   
/// <summary> /// <summary>
  /// Gets the cost of the part modules
  /// Same as stock but without mem allocation
  /// </summary>
  public static double GetModuleCostsNoAlloc(this Part part, float defaultCost)
  {
  float cost = 0f;
  for (int i = 0; i < part.Modules.Count; i++)
  {
  PartModule pm = part.Modules[i];
  if (pm is IPartCostModifier)
  cost += (pm as IPartCostModifier).GetModuleCost(defaultCost);
  }
  return cost;
  }
   
  /// <summary>
/// Gets the cost of the part including resources. /// Gets the cost of the part including resources.
/// </summary> /// </summary>
public static double GetCostWet(this Part part) public static double GetCostWet(this Part part)
{ {
return part.partInfo.cost - GetResourceCostInverted(part) + part.GetModuleCosts(0.0f); return part.partInfo.cost - GetResourceCostInverted(part) + part.GetModuleCostsNoAlloc(0.0f); // part.GetModuleCosts allocate 44B per call.
} }
   
/// <summary> /// <summary>
/// Gets the dry mass of the part. /// Gets the dry mass of the part.
/// </summary> /// </summary>
public static double GetDryMass(this Part part) public static double GetDryMass(this Part part)
{ {
return (part.physicalSignificance == Part.PhysicalSignificance.FULL) ? part.mass : 0d; return (part.physicalSignificance == Part.PhysicalSignificance.FULL) ? part.mass : 0d;
} }
   
/// <summary> /// <summary>
/// Gets the maximum thrust of the part if it's an engine. /// Gets the maximum thrust of the part if it's an engine.
/// </summary> /// </summary>
  /* not used
public static double GetMaxThrust(this Part part) public static double GetMaxThrust(this Part part)
{ {
if (part.HasModule<ModuleEngines>()) PartModule cachePartModule = GetModule<ModuleEngines>(part);
{ if (cachePartModule != null)
return part.GetModuleEngines().maxThrust; {
} return (cachePartModule as ModuleEngines).maxThrust;
if (part.HasModule<MultiModeEngine>()) }
{  
return part.GetModuleMultiModeEngine().maxThrust; cachePartModule = GetModuleMultiModeEngine(part) ?? GetModule<ModuleEnginesFX>(part);
} if (cachePartModule != null)
if (part.HasModule<ModuleEnginesFX>()) {
{ return (cachePartModule as ModuleEnginesFX).maxThrust;
return part.GetModuleEnginesFx().maxThrust; }
}  
  return 0.0;
return 0d; }
} */
   
/// <summary> /// <summary>
/// Gets the first typed PartModule in the part's module list. /// Gets the first typed PartModule in the part's module list.
/// </summary> /// </summary>
public static T GetModule<T>(this Part part) where T : PartModule public static T GetModule<T>(this Part part) where T : PartModule
{ {
return part.Modules.OfType<T>().FirstOrDefault(); for (int i = 0; i < part.Modules.Count; i++)
  {
  PartModule pm = part.Modules[i];
  if (pm is T)
  return (T)pm;
  }
  return null;
} }
   
/// <summary> /// <summary>
/// Gets a typed PartModule. /// Gets a typed PartModule.
/// </summary> /// </summary>
public static T GetModule<T>(this Part part, string className) where T : PartModule public static T GetModule<T>(this Part part, string className) where T : PartModule
{ {
return (T)Convert.ChangeType(part.Modules[className], typeof(T)); return part.Modules[className] as T;
} }
   
/// <summary> /// <summary>
/// Gets a typed PartModule. /// Gets a typed PartModule.
/// </summary> /// </summary>
public static T GetModule<T>(this Part part, int classId) where T : PartModule public static T GetModule<T>(this Part part, int classId) where T : PartModule
{ {
return (T)Convert.ChangeType(part.Modules[classId], typeof(T)); return part.Modules[classId] as T;
} }
   
/// <summary> /// <summary>
/// Gets a ModuleAlternator typed PartModule. /// Gets a ModuleAlternator typed PartModule.
/// </summary> /// </summary>
public static ModuleAlternator GetModuleAlternator(this Part part) public static ModuleAlternator GetModuleAlternator(this Part part)
{ {
return part.GetModule<ModuleAlternator>(); return GetModule<ModuleAlternator>(part);
} }
   
/// <summary> /// <summary>
/// Gets a ModuleDeployableSolarPanel typed PartModule. /// Gets a ModuleDeployableSolarPanel typed PartModule.
/// </summary> /// </summary>
public static ModuleDeployableSolarPanel GetModuleDeployableSolarPanel(this Part part) public static ModuleDeployableSolarPanel GetModuleDeployableSolarPanel(this Part part)
{ {
return part.GetModule<ModuleDeployableSolarPanel>(); return GetModule<ModuleDeployableSolarPanel>(part);
} }
   
/// <summary> /// <summary>
/// Gets a ModuleEngines typed PartModule. /// Gets a ModuleEngines typed PartModule.
/// </summary> /// </summary>
public static ModuleEngines GetModuleEngines(this Part part) public static ModuleEngines GetModuleEngines(this Part part)
{ {
return part.GetModule<ModuleEngines>(); return GetModule<ModuleEngines>(part);
} }
   
public static ModuleEnginesFX GetModuleEnginesFx(this Part part) /* public static ModuleEnginesFX GetModuleEnginesFx(this Part part)
{ {
return part.GetModule<ModuleEnginesFX>(); return GetModule<ModuleEnginesFX>(part);
} }*/
   
/// <summary> /// <summary>
/// Gets a ModuleGenerator typed PartModule. /// Gets a ModuleGenerator typed PartModule.
/// </summary> /// </summary>
public static ModuleGenerator GetModuleGenerator(this Part part) public static ModuleGenerator GetModuleGenerator(this Part part)
{ {
return part.GetModule<ModuleGenerator>(); return GetModule<ModuleGenerator>(part);
} }
   
/// <summary> /// <summary>
/// Gets a ModuleGimbal typed PartModule. /// Gets a ModuleGimbal typed PartModule.
/// </summary> /// </summary>
public static ModuleGimbal GetModuleGimbal(this Part part) public static ModuleGimbal GetModuleGimbal(this Part part)
{ {
return part.GetModule<ModuleGimbal>(); return GetModule<ModuleGimbal>(part);
} }
   
/// <summary> /// <summary>
/// Gets the current selected ModuleEnginesFX. /// Gets the current selected ModuleEnginesFX.
/// </summary> /// </summary>
public static ModuleEnginesFX GetModuleMultiModeEngine(this Part part) public static ModuleEngines GetModuleMultiModeEngine(this Part part)
{ {
var mode = part.GetModule<MultiModeEngine>().mode; ModuleEngines moduleEngines;
return part.Modules.OfType<ModuleEnginesFX>().FirstOrDefault(engine => engine.engineID == mode); MultiModeEngine multiMod = GetModule<MultiModeEngine>(part);
  if (multiMod != null)
  {
  string mode = multiMod.mode;
  for (int i = 0; i < part.Modules.Count; ++i)
  {
  moduleEngines = part.Modules[i] as ModuleEngines;
  if (moduleEngines != null && moduleEngines.engineID == mode)
  {
  return moduleEngines;
  }
  }
  }
  return null;
} }
   
/// <summary> /// <summary>
/// Gets a ModuleParachute typed PartModule. /// Gets a ModuleParachute typed PartModule.
/// </summary> /// </summary>
public static ModuleParachute GetModuleParachute(this Part part) public static ModuleParachute GetModuleParachute(this Part part)
{ {
return part.GetModule<ModuleParachute>(); return GetModule<ModuleParachute>(part);
} }
   
public static ModuleRCS GetModuleRcs(this Part part) public static ModuleRCS GetModuleRcs(this Part part)
{ {
return part.GetModule<ModuleRCS>(); return GetModule<ModuleRCS>(part);
} }
   
/// <summary> /// <summary>
/// Gets a typed list of PartModules. /// Gets a typed list of PartModules.
/// </summary> /// </summary>
public static List<T> GetModules<T>(this Part part) where T : PartModule public static List<T> GetModules<T>(this Part part) where T : PartModule
{ {
return part.Modules.OfType<T>().ToList(); List<T> list = new List<T>();
  for (int i = 0; i < part.Modules.Count; ++i)
  {
  T module = part.Modules[i] as T;
  if (module != null)
  {
  list.Add(module);
  }
  }
  return list;
} }
   
public static ProtoModuleDecoupler GetProtoModuleDecoupler(this Part part) public static ProtoModuleDecoupler GetProtoModuleDecoupler(this Part part)
{ {
if (HasModule<ModuleDecouple>(part)) PartModule cachePartModule = GetModule<ModuleDecouple>(part);
{ if (cachePartModule == null)
return new ProtoModuleDecoupler(GetModule<ModuleDecouple>(part)); {
} cachePartModule = GetModule<ModuleAnchoredDecoupler>(part);
if (HasModule<ModuleAnchoredDecoupler>(part)) }
{ if (cachePartModule != null)
return new ProtoModuleDecoupler(GetModule<ModuleAnchoredDecoupler>(part)); {
} return new ProtoModuleDecoupler(cachePartModule);
  }
   
return null; return null;
} }
   
/// <summary> /// <summary>
/// Gets a generic proto engine for the current engine module attached to the part. /// Gets a generic proto engine for the current engine module attached to the part.
/// </summary> /// </summary>
public static ProtoModuleEngine GetProtoModuleEngine(this Part part) public static ProtoModuleEngine GetProtoModuleEngine(this Part part)
{ {
if (HasModule<ModuleEngines>(part)) PartModule cachePartModule = GetModule<ModuleEngines>(part);
{ if (cachePartModule != null)
return new ProtoModuleEngine(GetModule<ModuleEngines>(part)); {
} return new ProtoModuleEngine(cachePartModule);
if (HasModule<MultiModeEngine>(part)) }
{  
return new ProtoModuleEngine(GetModuleMultiModeEngine(part)); cachePartModule = GetModuleMultiModeEngine(part) ?? GetModule<ModuleEnginesFX>(part);
} if (cachePartModule != null)
if (HasModule<ModuleEnginesFX>(part)) {
{ return new ProtoModuleEngine(cachePartModule);
return new ProtoModuleEngine(GetModule<ModuleEnginesFX>(part)); }
}  
return null; return null;
} }
   
/// <summary> /// <summary>
/// Gets the cost of the part's contained resources. /// Gets the cost of the part's contained resources.
/// </summary> /// </summary>
public static double GetResourceCost(this Part part) public static double GetResourceCost(this Part part)
{ {
return part.Resources.list.Sum(r => r.amount * r.info.unitCost); double cost = 0.0;
  for (int i = 0; i < part.Resources.list.Count; ++i)
  {
  PartResource cachePartResource = part.Resources.list[i];
  cost = cost + (cachePartResource.amount * cachePartResource.info.unitCost);
  }
  return cost;
} }
   
/// <summary> /// <summary>
/// Gets the cost of the part's contained resources, inverted. /// Gets the cost of the part's contained resources, inverted.
/// </summary> /// </summary>
public static double GetResourceCostInverted(this Part part) public static double GetResourceCostInverted(this Part part)
{ {
return part.Resources.list.Sum(r => (r.maxAmount - r.amount) * r.info.unitCost); double sum = 0;
  for (int i = 0; i < part.Resources.list.Count; i++)
  {
  PartResource r = part.Resources.list[i];
  sum += (r.maxAmount - r.amount) * r.info.unitCost;
  }
  return sum;
} }
   
/// <summary> /// <summary>
/// Gets the cost of the part's maximum contained resources. /// Gets the cost of the part's maximum contained resources.
/// </summary> /// </summary>
public static double GetResourceCostMax(this Part part) public static double GetResourceCostMax(this Part part)
{ {
return part.Resources.list.Sum(r => r.maxAmount * r.info.unitCost); double cost = 0.0;
  for (int i = 0; i < part.Resources.list.Count; ++i)
  {
  PartResource cachePartResource = part.Resources.list[i];
  cost = cost + (cachePartResource.maxAmount * cachePartResource.info.unitCost);
  }
  return cost;
} }
   
/// <summary> /// <summary>
/// Gets the current specific impulse for the engine. /// Gets the current specific impulse for the engine.
/// </summary> /// </summary>
  /* not used
public static double GetSpecificImpulse(this Part part, float atmosphere) public static double GetSpecificImpulse(this Part part, float atmosphere)
{ {
if (part.HasModule<ModuleEngines>()) PartModule cachePartModule = GetModule<ModuleEngines>(part);
{ if (cachePartModule != null)
return part.GetModuleEngines().atmosphereCurve.Evaluate(atmosphere); {
} return (cachePartModule as ModuleEngines).atmosphereCurve.Evaluate(atmosphere);
if (part.HasModule<MultiModeEngine>()) }
{  
return part.GetModuleMultiModeEngine().atmosphereCurve.Evaluate(atmosphere); cachePartModule = GetModuleMultiModeEngine(part) ?? GetModule<ModuleEnginesFX>(part);
} if (cachePartModule != null)
if (part.HasModule<ModuleEnginesFX>()) {
{ return (cachePartModule as ModuleEnginesFX).atmosphereCurve.Evaluate(atmosphere);
return part.GetModuleEnginesFx().atmosphereCurve.Evaluate(atmosphere); }
}  
  return 0.0;
return 0d; }
} */
   
/// <summary> /// <summary>
/// Gets the total mass of the part including resources. /// Gets the total mass of the part including resources.
/// </summary> /// </summary>
public static double GetWetMass(this Part part) public static double GetWetMass(this Part part)
{ {
return (part.physicalSignificance == Part.PhysicalSignificance.FULL) ? part.mass + part.GetResourceMass() : part.GetResourceMass(); return (part.physicalSignificance == Part.PhysicalSignificance.FULL) ? part.mass + part.GetResourceMass() : part.GetResourceMass();
} }
   
/// <summary> /// <summary>
/// Gets whether the part contains a PartModule. /// Gets whether the part contains a PartModule.
/// </summary> /// </summary>
public static bool HasModule<T>(this Part part) where T : PartModule public static bool HasModule<T>(this Part part) where T : PartModule
{ {
return part.Modules.OfType<T>().Any(); for (int i = 0; i < part.Modules.Count; i++)
  {
  if (part.Modules[i] is T)
  return true;
  }
  return false;
} }
   
/// <summary> /// <summary>
/// Gets whether the part contains a PartModule conforming to the supplied predicate. /// Gets whether the part contains a PartModule conforming to the supplied predicate.
/// </summary> /// </summary>
public static bool HasModule<T>(this Part part, Func<T, bool> predicate) where T : PartModule public static bool HasModule<T>(this Part part, Func<T, bool> predicate) where T : PartModule
{ {
return part.Modules.OfType<T>().Any(predicate); for (int i = 0; i < part.Modules.Count; i++)
  {
  PartModule pm = part.Modules[i];
  if (pm is T && predicate(pm as T))
  return true;
  }
  return false;
} }
   
/// <summary> /// <summary>
/// Gets whether the part contains a PartModule. /// Gets whether the part contains a PartModule.
/// </summary> /// </summary>
public static bool HasModule(this Part part, string className) public static bool HasModule(this Part part, string className)
{ {
return part.Modules.Contains(className); return part.Modules.Contains(className);
} }
   
/// <summary> /// <summary>
/// Gets whether the part contains a PartModule. /// Gets whether the part contains a PartModule.
/// </summary> /// </summary>
public static bool HasModule(this Part part, int moduleId) public static bool HasModule(this Part part, int moduleId)
{ {
return part.Modules.Contains(moduleId); return part.Modules.Contains(moduleId);
} }
   
/// <summary> /// <summary>
/// Gets whether the part has a one shot animation. /// Gets whether the part has a one shot animation.
/// </summary> /// </summary>
public static bool HasOneShotAnimation(this Part part) public static bool HasOneShotAnimation(this Part part)
{ {
return part.HasModule<ModuleAnimateGeneric>() && part.GetModule<ModuleAnimateGeneric>().isOneShot; PartModule cachePartModule = GetModule<ModuleAnimateGeneric>(part);
  return cachePartModule != null && (cachePartModule as ModuleAnimateGeneric).isOneShot;
} }
   
/// <summary> /// <summary>
/// Gets whether the part is a command module. /// Gets whether the part is a command module.
/// </summary> /// </summary>
public static bool IsCommandModule(this Part part) public static bool IsCommandModule(this Part part)
{ {
return part.HasModule<ModuleCommand>(); return HasModule<ModuleCommand>(part);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is decoupled in a specified stage. /// Gets whether the part is decoupled in a specified stage.
/// </summary> /// </summary>
public static bool IsDecoupledInStage(this Part part, int stage) public static bool IsDecoupledInStage(this Part part, int stage)
{ {
if ((part.IsDecoupler() || part.IsLaunchClamp()) && part.inverseStage == stage) if ((IsDecoupler(part) || IsLaunchClamp(part)) && part.inverseStage == stage)
{ {
return true; return true;
} }
if (part.parent == null) if (part.parent == null)
{ {
return false; return false;
} }
return part.parent.IsDecoupledInStage(stage); return IsDecoupledInStage(part.parent, stage);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is a decoupler. /// Gets whether the part is a decoupler.
/// </summary> /// </summary>
public static bool IsDecoupler(this Part part) public static bool IsDecoupler(this Part part)
{ {
return part.HasModule<ModuleDecouple>() || part.HasModule<ModuleAnchoredDecoupler>(); return HasModule<ModuleDecouple>(part) || HasModule<ModuleAnchoredDecoupler>(part);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is an active engine. /// Gets whether the part is an active engine.
/// </summary> /// </summary>
public static bool IsEngine(this Part part) public static bool IsEngine(this Part part)
{ {
return part.HasModule<ModuleEngines>() || part.HasModule<ModuleEnginesFX>(); return HasModule<ModuleEngines>(part);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is a fuel line. /// Gets whether the part is a fuel line.
/// </summary> /// </summary>
public static bool IsFuelLine(this Part part) public static bool IsFuelLine(this Part part)
{ {
return (HasModule<CModuleFuelLine>(part)); return HasModule<CModuleFuelLine>(part);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is a generator. /// Gets whether the part is a generator.
/// </summary> /// </summary>
public static bool IsGenerator(this Part part) public static bool IsGenerator(this Part part)
{ {
return part.HasModule<ModuleGenerator>(); return HasModule<ModuleGenerator>(part);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is a launch clamp. /// Gets whether the part is a launch clamp.
/// </summary> /// </summary>
public static bool IsLaunchClamp(this Part part) public static bool IsLaunchClamp(this Part part)
{ {
return part.HasModule<LaunchClamp>(); return HasModule<LaunchClamp>(part);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is a parachute. /// Gets whether the part is a parachute.
/// </summary> /// </summary>
public static bool IsParachute(this Part part) public static bool IsParachute(this Part part)
{ {
return part.HasModule<ModuleParachute>(); return HasModule<ModuleParachute>(part);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is considered a primary part on the vessel. /// Gets whether the part is considered a primary part on the vessel.
/// </summary> /// </summary>
public static bool IsPrimary(this Part part, List<Part> partsList, PartModule module) public static bool IsPrimary(this Part part, List<Part> partsList, PartModule module)
{ {
foreach (var vesselPart in partsList) for (int i = 0; i < partsList.Count; i++)
{ {
  var vesselPart = partsList[i];
if (!vesselPart.HasModule(module.ClassID)) if (!vesselPart.HasModule(module.ClassID))
{ {
continue; continue;
} }
   
if (vesselPart == part) if (vesselPart == part)
{ {
return true; return true;
} }
break; break;
} }
   
return false; return false;
} }
   
public static bool IsRcsModule(this Part part) public static bool IsRcsModule(this Part part)
{ {
return part.HasModule<ModuleRCS>(); return HasModule<ModuleRCS>(part);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is a sepratron. /// Gets whether the part is a sepratron.
/// </summary> /// </summary>
public static bool IsSepratron(this Part part) public static bool IsSepratron(this Part part)
{ {
return (part.IsSolidRocket() && part.ActivatesEvenIfDisconnected && part.IsDecoupledInStage(part.inverseStage)); return IsSolidRocket(part) && part.ActivatesEvenIfDisconnected && IsDecoupledInStage(part, part.inverseStage);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is a deployable solar panel. /// Gets whether the part is a deployable solar panel.
/// </summary> /// </summary>
public static bool IsSolarPanel(this Part part) public static bool IsSolarPanel(this Part part)
{ {
return part.HasModule<ModuleDeployableSolarPanel>(); return HasModule<ModuleDeployableSolarPanel>(part);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is a solid rocket motor. /// Gets whether the part is a solid rocket motor.
/// </summary> /// </summary>
public static bool IsSolidRocket(this Part part) public static bool IsSolidRocket(this Part part)
{ {
return part.HasModule<ModuleEngines>() && part.GetModuleEngines().throttleLocked; return (part.HasModule<ModuleEngines>() && part.GetModuleEngines().throttleLocked);
} }
   
#endregion  
   
#region Nested Type: ProtoModuleDecoupler  
   
public class ProtoModuleDecoupler public class ProtoModuleDecoupler
{ {
#region Fields  
   
private readonly PartModule module; private readonly PartModule module;
   
#endregion  
   
#region Constructors  
   
public ProtoModuleDecoupler(PartModule module) public ProtoModuleDecoupler(PartModule module)
{ {
this.module = module; this.module = module;
   
if (this.module is ModuleDecouple) if (this.module is ModuleDecouple)
{ {
this.SetModuleDecouple(); SetModuleDecouple();
} }
else if (this.module is ModuleAnchoredDecoupler) else if (this.module is ModuleAnchoredDecoupler)
{ {
this.SetModuleAnchoredDecoupler(); SetModuleAnchoredDecoupler();
} }
} }
   
#endregion  
   
#region Properties  
   
public double EjectionForce { get; private set; } public double EjectionForce { get; private set; }
public bool IsOmniDecoupler { get; private set; } public bool IsOmniDecoupler { get; private set; }
   
#endregion  
   
#region Methods: private  
   
private void SetModuleAnchoredDecoupler() private void SetModuleAnchoredDecoupler()
{ {
var decoupler = this.module as ModuleAnchoredDecoupler; ModuleAnchoredDecoupler decoupler = module as ModuleAnchoredDecoupler;
if (decoupler == null) if (decoupler == null)
{ {
return; return;
} }
   
this.EjectionForce = decoupler.ejectionForce; EjectionForce = decoupler.ejectionForce;
} }
   
private void SetModuleDecouple() private void SetModuleDecouple()
{ {
var decoupler = this.module as ModuleDecouple; ModuleDecouple decoupler = module as ModuleDecouple;
if (decoupler == null) if (decoupler == null)
{ {
return; return;
} }
   
this.EjectionForce = decoupler.ejectionForce; EjectionForce = decoupler.ejectionForce;
this.IsOmniDecoupler = decoupler.isOmniDecoupler; IsOmniDecoupler = decoupler.isOmniDecoupler;
} }
  }
#endregion  
} // This needs updating to handle multi-mode engines and engines with multiple ModuleEngines correctly.
  // It currently just shows the stats of the currently active module for multi-mode engines and just
#endregion // the first ModuleEngines for engines with multiple modules.
  // It should really show all the modes for multi-mode engines as separate sections.
#region Nested Type: ProtoModuleEngine // For other engines with multiple ModuleEngines it should combine the separate modules into a single set of data
  // The constructor should be changed to take the Part itself. It can be called if HasModule<ModuleEngines>() is true.
public class ProtoModuleEngine public class ProtoModuleEngine
{ {
#region Fields  
   
private readonly PartModule module; private readonly PartModule module;
   
#endregion  
   
#region Constructors  
   
public ProtoModuleEngine(PartModule module) public ProtoModuleEngine(PartModule module)
{ {
this.module = module; this.module = module;
   
if (module is ModuleEngines) if (module is ModuleEngines)
{ {
this.SetModuleEngines(); SetModuleEngines();
} }
else if (module is ModuleEnginesFX) }
{  
this.SetModuleEnginesFx();  
}  
}  
   
#endregion  
   
#region Properties  
   
public double MaximumThrust { get; private set; } public double MaximumThrust { get; private set; }
public double MinimumThrust { get; private set; } public double MinimumThrust { get; private set; }
public List<Propellant> Propellants { get; private set; } public List<Propellant> Propellants { get; private set; }
   
#endregion  
   
#region Methods: public  
   
public float GetSpecificImpulse(float atmosphere) public float GetSpecificImpulse(float atmosphere)
{ {
if (this.module is ModuleEngines) if (module is ModuleEngines)
{ {
return (this.module as ModuleEngines).atmosphereCurve.Evaluate(atmosphere); return (module as ModuleEngines).atmosphereCurve.Evaluate(atmosphere);
}  
if (this.module is ModuleEnginesFX)  
{  
return (this.module as ModuleEnginesFX).atmosphereCurve.Evaluate(atmosphere);  
} }
return 0.0f; return 0.0f;
} }
   
#endregion  
   
#region Methods: private  
   
private void SetModuleEngines() private void SetModuleEngines()
{ {
var engine = this.module as ModuleEngines; ModuleEngines engine = module as ModuleEngines;
if (engine == null) if (engine == null)
{ {
return; return;
} }
   
this.MaximumThrust = engine.maxThrust * (engine.thrustPercentage * 0.01); MaximumThrust = engine.maxThrust * (engine.thrustPercentage * 0.01);
this.MinimumThrust = engine.minThrust; MinimumThrust = engine.minThrust;
this.Propellants = engine.propellants; Propellants = engine.propellants;
} }
  }
private void SetModuleEnginesFx()  
{  
var engine = this.module as ModuleEnginesFX;  
if (engine == null)  
{  
return;  
}  
   
this.MaximumThrust = engine.maxThrust * (engine.thrustPercentage * 0.01);  
this.MinimumThrust = engine.minThrust;  
this.Propellants = engine.propellants;  
}  
   
#endregion  
}  
   
#endregion  
} }
} }
  //
  // Kerbal Engineer Redux
  //
  // Copyright (C) 2015 CYBUTEK
  //
  // This program is free software: you can redistribute it and/or modify
  // it under the terms of the GNU General Public License as published by
  // the Free Software Foundation, either version 3 of the License, or
  // (at your option) any later version.
  //
  // This program is distributed in the hope that it will be useful,
  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  // GNU General Public License for more details.
  //
  // You should have received a copy of the GNU General Public License
  // along with this program. If not, see <http://www.gnu.org/licenses/>.
  //
 
  namespace KerbalEngineer.Extensions
  {
  public static class StringExtensions
  {
  public static string ToLength(this string value, int length)
  {
  if (value != null && value.Length > length)
  {
  value = value.Substring(0, length) + "...";
  }
  return value;
  }
  }
  }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using System; using System;
   
using UnityEngine; using UnityEngine;
   
#endregion #endregion
   
namespace KerbalEngineer.Flight namespace KerbalEngineer.Flight
{ {
/// <summary> /// <summary>
/// Graphical controller for section interaction in the form of a menu system. /// Graphical controller for section interaction in the form of a menu system.
/// </summary> /// </summary>
[KSPAddon(KSPAddon.Startup.Flight, false)] [KSPAddon(KSPAddon.Startup.Flight, false)]
public class ActionMenu : MonoBehaviour public class ActionMenu : MonoBehaviour
{ {
#region Fields #region Fields
   
private ActionMenuGui actionMenuGui; private ActionMenuGui actionMenuGui;
private ApplicationLauncherButton button; private ApplicationLauncherButton button;
   
#endregion #endregion
   
#region Methods: protected #region Methods: protected
   
protected void Awake() protected void Awake()
{ {
try try
{ {
GameEvents.onGUIApplicationLauncherReady.Add(this.OnGuiAppLauncherReady); GameEvents.onGUIApplicationLauncherReady.Add(this.OnGuiAppLauncherReady);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
Logger.Log("ActionMenu was created."); Logger.Log("ActionMenu was created.");
} }
   
  protected void Start()
  {
  if (button == null)
  {
  OnGuiAppLauncherReady();
  }
  }
   
protected void OnDestroy() protected void OnDestroy()
{ {
try try
{ {
GameEvents.onGUIApplicationLauncherReady.Remove(this.OnGuiAppLauncherReady); GameEvents.onGUIApplicationLauncherReady.Remove(this.OnGuiAppLauncherReady);
GameEvents.onHideUI.Remove(this.OnHide); GameEvents.onHideUI.Remove(this.OnHide);
GameEvents.onShowUI.Remove(this.OnShow); GameEvents.onShowUI.Remove(this.OnShow);
ApplicationLauncher.Instance.RemoveModApplication(this.button); if (button != null)
  {
  ApplicationLauncher.Instance.RemoveModApplication(this.button);
  }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
Logger.Log("ActionMenu was destroyed."); Logger.Log("ActionMenu was destroyed.");
} }
   
protected void Update() protected void Update()
{ {
try try
{ {
if (this.button == null) if (this.button == null)
{ {
return; return;
} }
if (FlightEngineerCore.IsDisplayable && this.button.State == RUIToggleButton.ButtonState.DISABLED) if (FlightEngineerCore.IsDisplayable && this.button.State == RUIToggleButton.ButtonState.DISABLED)
{ {
this.button.Enable(); this.button.Enable();
} }
else if (!FlightEngineerCore.IsDisplayable && this.button.State != RUIToggleButton.ButtonState.DISABLED) else if (!FlightEngineerCore.IsDisplayable && this.button.State != RUIToggleButton.ButtonState.DISABLED)
{ {
this.button.Disable(); this.button.Disable();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion #endregion
   
#region Methods: private #region Methods: private
   
private void OnFalse() private void OnFalse()
{ {
try try
{ {
this.actionMenuGui.enabled = false; this.actionMenuGui.enabled = false;
this.actionMenuGui.StayOpen = false; this.actionMenuGui.StayOpen = false;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
private void OnGuiAppLauncherReady() private void OnGuiAppLauncherReady()
{ {
try try
{ {
this.button = ApplicationLauncher.Instance.AddModApplication( this.button = ApplicationLauncher.Instance.AddModApplication(
this.OnTrue, this.OnTrue,
this.OnFalse, this.OnFalse,
this.OnHover, this.OnHover,
this.OnHoverOut, this.OnHoverOut,
null, null,
null, null,
ApplicationLauncher.AppScenes.ALWAYS, ApplicationLauncher.AppScenes.ALWAYS,
GameDatabase.Instance.GetTexture("KerbalEngineer/Textures/ToolbarIcon", false)); GameDatabase.Instance.GetTexture("KerbalEngineer/Textures/ToolbarIcon", false));
this.actionMenuGui = this.button.gameObject.AddComponent<ActionMenuGui>(); this.actionMenuGui = this.button.gameObject.AddComponent<ActionMenuGui>();
this.actionMenuGui.transform.parent = this.button.transform; this.actionMenuGui.transform.parent = this.button.transform;
ApplicationLauncher.Instance.EnableMutuallyExclusive(this.button); ApplicationLauncher.Instance.EnableMutuallyExclusive(this.button);
GameEvents.onHideUI.Add(this.OnHide); GameEvents.onHideUI.Add(this.OnHide);
GameEvents.onShowUI.Add(this.OnShow); GameEvents.onShowUI.Add(this.OnShow);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
private void OnHide() private void OnHide()
{ {
try try
{ {
this.actionMenuGui.Hidden = true; this.actionMenuGui.Hidden = true;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
private void OnHover() private void OnHover()
{ {
try try
{ {
this.actionMenuGui.enabled = true; this.actionMenuGui.enabled = true;
this.actionMenuGui.Hovering = true; this.actionMenuGui.Hovering = true;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
private void OnHoverOut() private void OnHoverOut()
{ {
try try
{ {
this.actionMenuGui.Hovering = false; this.actionMenuGui.Hovering = false;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
private void OnShow() private void OnShow()
{ {
try try
{ {
this.actionMenuGui.Hidden = false; this.actionMenuGui.Hidden = false;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
private void OnTrue() private void OnTrue()
{ {
try try
{ {
this.actionMenuGui.enabled = true; this.actionMenuGui.enabled = true;
this.actionMenuGui.StayOpen = true; this.actionMenuGui.StayOpen = true;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
   
using KerbalEngineer.Extensions; using KerbalEngineer.Extensions;
using KerbalEngineer.Flight.Sections; using KerbalEngineer.Flight.Sections;
using KerbalEngineer.Settings; using KerbalEngineer.Settings;
   
using UnityEngine; using UnityEngine;
   
#endregion #endregion
   
namespace KerbalEngineer.Flight namespace KerbalEngineer.Flight
{ {
  using KeyBinding;
using Upgradeables; using Upgradeables;
   
/// <summary> /// <summary>
/// Graphical controller for displaying stacked sections. /// Graphical controller for displaying stacked sections.
/// </summary> /// </summary>
[KSPAddon(KSPAddon.Startup.Flight, false)] [KSPAddon(KSPAddon.Startup.Flight, false)]
public class DisplayStack : MonoBehaviour public class DisplayStack : MonoBehaviour
{ {
#region Fields #region Fields
   
private GUIStyle buttonStyle; private GUIStyle buttonStyle;
private int numberOfStackSections; private int numberOfStackSections;
private bool resizeRequested; private bool resizeRequested;
private bool showControlBar = true; private bool showControlBar = true;
private GUIStyle titleStyle; private GUIStyle titleStyle;
private int windowId; private int windowId;
private Rect windowPosition; private Rect windowPosition;
private GUIStyle windowStyle; private GUIStyle windowStyle;
   
#endregion #endregion
   
#region Properties #region Properties
   
/// <summary> /// <summary>
/// Gets the current instance of the DisplayStack. /// Gets the current instance of the DisplayStack.
/// </summary> /// </summary>
public static DisplayStack Instance { get; private set; } public static DisplayStack Instance { get; private set; }
   
public bool Hidden { get; set; } public bool Hidden { get; set; }
   
/// <summary> /// <summary>
/// Gets and sets the visibility of the control bar. /// Gets and sets the visibility of the control bar.
/// </summary> /// </summary>
public bool ShowControlBar public bool ShowControlBar
{ {
get { return this.showControlBar; } get { return this.showControlBar; }
set { this.showControlBar = value; } set { this.showControlBar = value; }
} }
   
#endregion #endregion
   
#region Methods: public #region Methods: public
   
/// <summary> /// <summary>
/// Request that the display stack's size is reset in the next draw call. /// Request that the display stack's size is reset in the next draw call.
/// </summary> /// </summary>
public void RequestResize() public void RequestResize()
{ {
this.resizeRequested = true; this.resizeRequested = true;
} }
   
#endregion #endregion
   
#region Methods: protected #region Methods: protected
   
/// <summary> /// <summary>
/// Sets the instance to this object. /// Sets the instance to this object.
/// </summary> /// </summary>
protected void Awake() protected void Awake()
{ {
try try
{ {
if (Instance == null) if (Instance == null)
{ {
Instance = this; Instance = this;
GuiDisplaySize.OnSizeChanged += this.OnSizeChanged; GuiDisplaySize.OnSizeChanged += this.OnSizeChanged;
Logger.Log("ActionMenu->Awake"); Logger.Log("ActionMenu->Awake");
} }
else else
{ {
Destroy(this); Destroy(this);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
/// <summary> /// <summary>
/// Runs when the object is destroyed. /// Runs when the object is destroyed.
/// </summary> /// </summary>
protected void OnDestroy() protected void OnDestroy()
{ {
try try
{ {
this.Save(); this.Save();
RenderingManager.RemoveFromPostDrawQueue(0, this.Draw); RenderingManager.RemoveFromPostDrawQueue(0, this.Draw);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
Logger.Log("ActionMenu->OnDestroy"); Logger.Log("ActionMenu->OnDestroy");
} }
   
/// <summary> /// <summary>
/// Initialises the object's state on creation. /// Initialises the object's state on creation.
/// </summary> /// </summary>
protected void Start() protected void Start()
{ {
try try
{ {
this.windowId = this.GetHashCode(); this.windowId = this.GetHashCode();
this.InitialiseStyles(); this.InitialiseStyles();
this.Load(); this.Load();
RenderingManager.AddToPostDrawQueue(0, this.Draw); RenderingManager.AddToPostDrawQueue(0, this.Draw);
Logger.Log("ActionMenu->Start"); Logger.Log("ActionMenu->Start");
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
protected void Update() protected void Update()
{ {
try try
{ {
if (!FlightEngineerCore.IsDisplayable) if (!FlightEngineerCore.IsDisplayable)
{ {
return; return;
} }
   
if (Input.GetKeyDown(KeyBinder.FlightShowHide)) if (Input.GetKeyDown(KeyBinder.FlightShowHide))
{ {
this.Hidden = !this.Hidden; this.Hidden = !this.Hidden;
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion #endregion
   
#region Methods: private #region Methods: private
   
/// <summary> /// <summary>
/// Called to draw the display stack when the UI is enabled. /// Called to draw the display stack when the UI is enabled.
/// </summary> /// </summary>
private void Draw() private void Draw()
{ {
try try
{ {
if (!FlightEngineerCore.IsDisplayable) if (!FlightEngineerCore.IsDisplayable)
{ {
return; return;
} }
   
if (this.resizeRequested || this.numberOfStackSections != SectionLibrary.NumberOfStackSections) if (this.resizeRequested || this.numberOfStackSections != SectionLibrary.NumberOfStackSections)
{ {
this.numberOfStackSections = SectionLibrary.NumberOfStackSections; this.numberOfStackSections = SectionLibrary.NumberOfStackSections;
this.windowPosition.width = 0; this.windowPosition.width = 0;
this.windowPosition.height = 0; this.windowPosition.height = 0;
this.resizeRequested = false; this.resizeRequested = false;
} }
   
if (!this.Hidden && (SectionLibrary.NumberOfStackSections > 0 || this.ShowControlBar)) if (!this.Hidden && (SectionLibrary.NumberOfStackSections > 0 || this.ShowControlBar))
{ {
var shouldCentre = this.windowPosition.min == Vector2.zero; var shouldCentre = this.windowPosition.min == Vector2.zero;
GUI.skin = null; GUI.skin = null;
this.windowPosition = GUILayout.Window(this.windowId, this.windowPosition, this.Window, string.Empty, this.windowStyle).ClampToScreen(); this.windowPosition = GUILayout.Window(this.windowId, this.windowPosition, this.Window, string.Empty, this.windowStyle).ClampToScreen();
if (shouldCentre) if (shouldCentre)
{ {
this.windowPosition.center = new Vector2(Screen.width * 0.5f, Screen.height * 0.5f); this.windowPosition.center = new Vector2(Screen.width * 0.5f, Screen.height * 0.5f);
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
/// <summary> /// <summary>
/// Draws the control bar. /// Draws the control bar.
/// </summary> /// </summary>
private void DrawControlBar() private void DrawControlBar()
{ {
GUILayout.Label("FLIGHT ENGINEER " + EngineerGlobals.AssemblyVersion, this.titleStyle); GUILayout.Label("FLIGHT ENGINEER " + EngineerGlobals.ASSEMBLY_VERSION, this.titleStyle);
   
this.DrawControlBarButtons(SectionLibrary.StockSections); this.DrawControlBarButtons(SectionLibrary.StockSections);
this.DrawControlBarButtons(SectionLibrary.CustomSections); this.DrawControlBarButtons(SectionLibrary.CustomSections);
} }
   
/// <summary> /// <summary>
/// Draws a button list for a set of sections. /// Draws a button list for a set of sections.
/// </summary> /// </summary>
private void DrawControlBarButtons(IEnumerable<SectionModule> sections) private void DrawControlBarButtons(IEnumerable<SectionModule> sections)
{ {
var index = 0; var index = 0;
foreach (var section in sections.Where(s => !string.IsNullOrEmpty(s.Abbreviation) || !s.IsCustom)) foreach (var section in sections.Where(s => !string.IsNullOrEmpty(s.Abbreviation) || !s.IsCustom))
{ {
if (index % 4 == 0) if (index % 4 == 0)
{ {
if (index > 0) if (index > 0)
{ {
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
} }
section.IsVisible = GUILayout.Toggle(section.IsVisible, section.Abbreviation.ToUpper(), this.buttonStyle); section.IsVisible = GUILayout.Toggle(section.IsVisible, section.Abbreviation.ToUpper(), this.buttonStyle);
index++; index++;
} }
if (index > 0) if (index > 0)
{ {
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
} }
   
/// <summary> /// <summary>
/// Draws a list of sections. /// Draws a list of sections.
/// </summary> /// </summary>
private void DrawSections(IEnumerable<SectionModule> sections) private void DrawSections(IEnumerable<SectionModule> sections)
{ {
foreach (var section in sections) foreach (var section in sections)
{ {
if (!section.IsFloating) if (!section.IsFloating)
{ {
section.Draw(); section.Draw();
} }
} }
} }
   
/// <summary> /// <summary>
/// Initialises all the styles required for this object. /// Initialises all the styles required for this object.
/// </summary> /// </summary>
private void InitialiseStyles() private void InitialiseStyles()
{ {
this.windowStyle = new GUIStyle(HighLogic.Skin.window) this.windowStyle = new GUIStyle(HighLogic.Skin.window)
{ {
margin = new RectOffset(), margin = new RectOffset(),
padding = new RectOffset(5, 5, 0, 5) padding = new RectOffset(5, 5, 0, 5)
}; };
   
this.titleStyle = new GUIStyle(HighLogic.Skin.label) this.titleStyle = new GUIStyle(HighLogic.Skin.label)
{ {
margin = new RectOffset(0, 0, 5, 3), margin = new RectOffset(0, 0, 5, 3),
padding = new RectOffset(), padding = new RectOffset(),
alignment = TextAnchor.MiddleCenter, alignment = TextAnchor.MiddleCenter,
fontSize = (int)(13 * GuiDisplaySize.Offset), fontSize = (int)(13 * GuiDisplaySize.Offset),
fontStyle = FontStyle.Bold, fontStyle = FontStyle.Bold,
stretchWidth = true stretchWidth = true
}; };
   
this.buttonStyle = new GUIStyle(HighLogic.Skin.button) this.buttonStyle = new GUIStyle(HighLogic.Skin.button)
{ {
normal = normal =
{ {
textColor = Color.white textColor = Color.white
}, },
margin = new RectOffset(), margin = new RectOffset(),
padding = new RectOffset(), padding = new RectOffset(),
alignment = TextAnchor.MiddleCenter, alignment = TextAnchor.MiddleCenter,
fontSize = (int)(11 * GuiDisplaySize.Offset), fontSize = (int)(11 * GuiDisplaySize.Offset),
fontStyle = FontStyle.Bold, fontStyle = FontStyle.Bold,
fixedWidth = 60.0f * GuiDisplaySize.Offset, fixedWidth = 60.0f * GuiDisplaySize.Offset,
fixedHeight = 25.0f * GuiDisplaySize.Offset, fixedHeight = 25.0f * GuiDisplaySize.Offset,
}; };
} }
   
/// <summary> /// <summary>
/// Load the stack's state. /// Load the stack's state.
/// </summary> /// </summary>
private void Load() private void Load()
{ {
try try
{ {
var handler = SettingHandler.Load("DisplayStack.xml"); var handler = SettingHandler.Load("DisplayStack.xml");
this.Hidden = handler.Get("hidden", this.Hidden); this.Hidden = handler.Get("hidden", this.Hidden);
this.ShowControlBar = handler.Get("showControlBar", this.ShowControlBar); this.ShowControlBar = handler.Get("showControlBar", this.ShowControlBar);
this.windowPosition.x = handler.Get("windowPositionX", this.windowPosition.x); this.windowPosition.x = handler.Get("windowPositionX", this.windowPosition.x);
this.windowPosition.y = handler.Get("windowPositionY", this.windowPosition.y); this.windowPosition.y = handler.Get("windowPositionY", this.windowPosition.y);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex, "DisplayStack->Load"); Logger.Exception(ex, "DisplayStack->Load");
} }
} }
   
private void OnSizeChanged() private void OnSizeChanged()
{ {
this.InitialiseStyles(); this.InitialiseStyles();
this.RequestResize(); this.RequestResize();
} }
   
/// <summary> /// <summary>
/// Saves the stack's state. /// Saves the stack's state.
/// </summary> /// </summary>
private void Save() private void Save()
{ {
try try
{ {
var handler = new SettingHandler(); var handler = new SettingHandler();
handler.Set("hidden", this.Hidden); handler.Set("hidden", this.Hidden);
handler.Set("showControlBar", this.ShowControlBar); handler.Set("showControlBar", this.ShowControlBar);
handler.Set("windowPositionX", this.windowPosition.x); handler.Set("windowPositionX", this.windowPosition.x);
handler.Set("windowPositionY", this.windowPosition.y); handler.Set("windowPositionY", this.windowPosition.y);
handler.Save("DisplayStack.xml"); handler.Save("DisplayStack.xml");
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex, "DisplayStack->Save"); Logger.Exception(ex, "DisplayStack->Save");
} }
} }
   
/// <summary> /// <summary>
/// Draws the display stack window. /// Draws the display stack window.
/// </summary> /// </summary>
private void Window(int windowId) private void Window(int windowId)
{ {
try try
{ {
if (this.ShowControlBar) if (this.ShowControlBar)
{ {
this.DrawControlBar(); this.DrawControlBar();
} }
   
if (SectionLibrary.NumberOfStackSections > 0) if (SectionLibrary.NumberOfStackSections > 0)
{ {
this.DrawSections(SectionLibrary.StockSections); this.DrawSections(SectionLibrary.StockSections);
this.DrawSections(SectionLibrary.CustomSections); this.DrawSections(SectionLibrary.CustomSections);
} }
   
GUI.DragWindow(); GUI.DragWindow();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex, "DisplayStack->Widnow"); Logger.Exception(ex, "DisplayStack->Widnow");
} }
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
#endregion #endregion
   
namespace KerbalEngineer.Flight namespace KerbalEngineer.Flight
{ {
#region Using Directives #region Using Directives
   
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Extensions; using Extensions;
using Readouts; using Readouts;
using Sections; using Sections;
using Settings; using Settings;
using UnityEngine; using UnityEngine;
  using VesselSimulator;
   
#endregion #endregion
   
/// <summary> /// <summary>
/// Core management system for the Flight Engineer. /// Core management system for the Flight Engineer.
/// </summary> /// </summary>
[KSPAddon(KSPAddon.Startup.Flight, false)] [KSPAddon(KSPAddon.Startup.Flight, false)]
public sealed class FlightEngineerCore : MonoBehaviour public sealed class FlightEngineerCore : MonoBehaviour
{ {
#region Instance #region Instance
   
/// <summary> /// <summary>
/// Gets the current instance of FlightEngineerCore. /// Gets the current instance of FlightEngineerCore.
/// </summary> /// </summary>
public static FlightEngineerCore Instance { get; private set; } public static FlightEngineerCore Instance { get; private set; }
   
#endregion #endregion
   
#region Fields #region Fields
   
private static bool isCareerMode = true; private static bool isCareerMode = true;
private static bool isKerbalLimited = true; private static bool isKerbalLimited = true;
private static bool isTrackingStationLimited = true; private static bool isTrackingStationLimited = true;
   
#endregion #endregion
   
#region Constructors #region Constructors
   
static FlightEngineerCore() static FlightEngineerCore()
{ {
try try
{ {
var handler = SettingHandler.Load("FlightEngineerCore.xml"); var handler = SettingHandler.Load("FlightEngineerCore.xml");
handler.Get("isCareerMode", ref isCareerMode); handler.Get("isCareerMode", ref isCareerMode);
handler.Get("isKerbalLimited", ref isKerbalLimited); handler.Get("isKerbalLimited", ref isKerbalLimited);
handler.Get("isTrackingStationLimited", ref isTrackingStationLimited); handler.Get("isTrackingStationLimited", ref isTrackingStationLimited);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion #endregion
   
#region Properties #region Properties
   
/// <summary> /// <summary>
/// Gets and sets whether to the Flight Engineer should be run using career limitations. /// Gets and sets whether to the Flight Engineer should be run using career limitations.
/// </summary> /// </summary>
public static bool IsCareerMode public static bool IsCareerMode
{ {
get { return isCareerMode; } get { return isCareerMode; }
set set
{ {
try try
{ {
if (isCareerMode != value) if (isCareerMode != value)
{ {
var handler = SettingHandler.Load("FlightEngineerCore.xml"); var handler = SettingHandler.Load("FlightEngineerCore.xml");
handler.Set("isCareerMode", value); handler.Set("isCareerMode", value);
handler.Save("FlightEngineerCore.xml"); handler.Save("FlightEngineerCore.xml");
} }
isCareerMode = value; isCareerMode = value;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
} }
   
/// <summary> /// <summary>
/// Gets whether the FlightEngineer should be displayed. /// Gets whether the FlightEngineer should be displayed.
/// </summary> /// </summary>
public static bool IsDisplayable public static bool IsDisplayable
{ {
get get
{ {
if (isCareerMode) if (isCareerMode)
{ {
if (isKerbalLimited && FlightGlobals.ActiveVessel.GetVesselCrew().Exists(c => c.experienceTrait.TypeName == "Engineer")) if (isKerbalLimited && FlightGlobals.ActiveVessel.GetVesselCrew().Exists(c => c.experienceTrait.TypeName == "Engineer"))
{ {
return true; return true;
} }
if (isTrackingStationLimited && ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.TrackingStation) == 1.0f) if (isTrackingStationLimited && ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.TrackingStation) == 1.0f)
{ {
return true; return true;
} }
return FlightGlobals.ActiveVessel.parts.Any(p => p.HasModule<FlightEngineerModule>()); return FlightGlobals.ActiveVessel.parts.Any(p => p.HasModule<FlightEngineerModule>());
} }
   
return true; return true;
} }
} }
   
/// <summary> /// <summary>
/// Gets and sets whether to the Flight Engineer should be kerbal limited. /// Gets and sets whether to the Flight Engineer should be kerbal limited.
/// </summary> /// </summary>
public static bool IsKerbalLimited public static bool IsKerbalLimited
{ {
get { return isKerbalLimited; } get { return isKerbalLimited; }
set set
{ {
try try
{ {
if (isKerbalLimited != value) if (isKerbalLimited != value)
{ {
var handler = SettingHandler.Load("FlightEngineerCore.xml"); var handler = SettingHandler.Load("FlightEngineerCore.xml");
handler.Set("isKerbalLimited", value); handler.Set("isKerbalLimited", value);
handler.Save("FlightEngineerCore.xml"); handler.Save("FlightEngineerCore.xml");
} }
isKerbalLimited = value; isKerbalLimited = value;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
} }
   
/// <summary> /// <summary>
/// Gets and sets whether to the Flight Engineer should be tracking station limited. /// Gets and sets whether to the Flight Engineer should be tracking station limited.
/// </summary> /// </summary>
public static bool IsTrackingStationLimited public static bool IsTrackingStationLimited
{ {
get { return isTrackingStationLimited; } get { return isTrackingStationLimited; }
set set
{ {
try try
{ {
if (isTrackingStationLimited != value) if (isTrackingStationLimited != value)
{ {
var handler = SettingHandler.Load("FlightEngineerCore.xml"); var handler = SettingHandler.Load("FlightEngineerCore.xml");
handler.Set("isTrackingStationLimited", value); handler.Set("isTrackingStationLimited", value);
handler.Save("FlightEngineerCore.xml"); handler.Save("FlightEngineerCore.xml");
} }
isTrackingStationLimited = value; isTrackingStationLimited = value;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
} }
   
/// <summary> /// <summary>
/// Gets the editor windows for sections with open editors. /// Gets the editor windows for sections with open editors.
/// </summary> /// </summary>
public List<SectionEditor> SectionEditors { get; private set; } public List<SectionEditor> SectionEditors { get; private set; }
   
/// <summary> /// <summary>
/// Gets the section windows for floating sections. /// Gets the section windows for floating sections.
/// </summary> /// </summary>
public List<SectionWindow> SectionWindows { get; private set; } public List<SectionWindow> SectionWindows { get; private set; }
   
/// <summary> /// <summary>
/// Gets the list of currently running updatable modules. /// Gets the list of currently running updatable modules.
/// </summary> /// </summary>
public List<IUpdatable> UpdatableModules { get; private set; } public List<IUpdatable> UpdatableModules { get; private set; }
   
#endregion #endregion
   
#region Methods #region Methods
   
/// <summary> /// <summary>
/// Creates a section editor, adds it to the FlightEngineerCore and returns a reference to it. /// Creates a section editor, adds it to the FlightEngineerCore and returns a reference to it.
/// </summary> /// </summary>
public SectionEditor AddSectionEditor(SectionModule section) public SectionEditor AddSectionEditor(SectionModule section)
{ {
try try
{ {
var editor = this.gameObject.AddComponent<SectionEditor>(); var editor = this.gameObject.AddComponent<SectionEditor>();
editor.ParentSection = section; editor.ParentSection = section;
editor.Position = new Rect(section.EditorPositionX, section.EditorPositionY, SectionEditor.Width, SectionEditor.Height); editor.Position = new Rect(section.EditorPositionX, section.EditorPositionY, SectionEditor.Width, SectionEditor.Height);
this.SectionEditors.Add(editor); this.SectionEditors.Add(editor);
return editor; return editor;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
return null; return null;
} }
} }
   
/// <summary> /// <summary>
/// Creates a section window, adds it to the FlightEngineerCore and returns a reference to it. /// Creates a section window, adds it to the FlightEngineerCore and returns a reference to it.
/// </summary> /// </summary>
public SectionWindow AddSectionWindow(SectionModule section) public SectionWindow AddSectionWindow(SectionModule section)
{ {
try try
{ {
var window = this.gameObject.AddComponent<SectionWindow>(); var window = this.gameObject.AddComponent<SectionWindow>();
window.ParentSection = section; window.ParentSection = section;
window.WindowPosition = new Rect(section.FloatingPositionX, section.FloatingPositionY, 0, 0); window.WindowPosition = new Rect(section.FloatingPositionX, section.FloatingPositionY, 0, 0);
this.SectionWindows.Add(window); this.SectionWindows.Add(window);
return window; return window;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
return null; return null;
} }
} }
   
/// <summary> /// <summary>
/// Adds an updatable object to be automatically updated every frame and will ignore duplicate objects. /// Adds an updatable object to be automatically updated every frame and will ignore duplicate objects.
/// </summary> /// </summary>
public void AddUpdatable(IUpdatable updatable) public void AddUpdatable(IUpdatable updatable)
{ {
try try
{ {
if (!this.UpdatableModules.Contains(updatable)) if (!this.UpdatableModules.Contains(updatable))
{ {
this.UpdatableModules.Add(updatable); this.UpdatableModules.Add(updatable);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
/// <summary> /// <summary>
/// Create base Flight Engineer child objects. /// Create base Flight Engineer child objects.
/// </summary> /// </summary>
private void Awake() private void Awake()
{ {
try try
{ {
Instance = this; Instance = this;
   
this.SectionWindows = new List<SectionWindow>(); this.SectionWindows = new List<SectionWindow>();
this.SectionEditors = new List<SectionEditor>(); this.SectionEditors = new List<SectionEditor>();
this.UpdatableModules = new List<IUpdatable>(); this.UpdatableModules = new List<IUpdatable>();
   
  SimManager.UpdateModSettings();
   
Logger.Log("FlightEngineerCore->Awake"); Logger.Log("FlightEngineerCore->Awake");
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
/// <summary> /// <summary>
/// Fixed update all required Flight Engineer objects. /// Fixed update all required Flight Engineer objects.
/// </summary> /// </summary>
private void FixedUpdate() private void FixedUpdate()
{ {
try try
{ {
SectionLibrary.FixedUpdate(); SectionLibrary.FixedUpdate();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
/// <summary> /// <summary>
/// Force the destruction of child objects on core destruction. /// Force the destruction of child objects on core destruction.
/// </summary> /// </summary>
private void OnDestroy() private void OnDestroy()
{ {
try try
{ {
SectionLibrary.Save(); SectionLibrary.Save();
   
foreach (var window in this.SectionWindows) foreach (var window in this.SectionWindows)
{ {
print("[FlightEngineer]: Destroying Floating Window for " + window.ParentSection.Name); print("[FlightEngineer]: Destroying Floating Window for " + window.ParentSection.Name);
Destroy(window); Destroy(window);
} }
   
foreach (var editor in this.SectionEditors) foreach (var editor in this.SectionEditors)
{ {
print("[FlightEngineer]: Destroying Editor Window for " + editor.ParentSection.Name); print("[FlightEngineer]: Destroying Editor Window for " + editor.ParentSection.Name);
Destroy(editor); Destroy(editor);
} }
   
Logger.Log("FlightEngineerCore->OnDestroy"); Logger.Log("FlightEngineerCore->OnDestroy");
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
/// <summary> /// <summary>
/// Initialises the object's state on creation. /// Initialises the object's state on creation.
/// </summary> /// </summary>
private void Start() private void Start()
{ {
try try
{ {
SectionLibrary.Load(); SectionLibrary.Load();
ReadoutLibrary.Reset(); ReadoutLibrary.Reset();
Logger.Log("FlightEngineerCore->Start"); Logger.Log("FlightEngineerCore->Start");
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
/// <summary> /// <summary>
/// Update all required Flight Engineer objects. /// Update all required Flight Engineer objects.
/// </summary> /// </summary>
private void Update() private void Update()
{ {
try try
{ {
SectionLibrary.Update(); SectionLibrary.Update();
this.UpdateModules(); this.UpdateModules();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
/// <summary> /// <summary>
/// Update all updatable modules. /// Update all updatable modules.
/// </summary> /// </summary>
private void UpdateModules() private void UpdateModules()
{ {
try try
{ {
foreach (var updatable in this.UpdatableModules) foreach (var updatable in this.UpdatableModules)
{ {
if (updatable is IUpdateRequest) if (updatable is IUpdateRequest)
{ {
var request = updatable as IUpdateRequest; var request = updatable as IUpdateRequest;
if (request.UpdateRequested) if (request.UpdateRequested)
{ {
updatable.Update(); updatable.Update();
request.UpdateRequested = false; request.UpdateRequested = false;
} }
} }
else else
{ {
updatable.Update(); updatable.Update();
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using System; using System;
   
using KerbalEngineer.Flight.Sections; using KerbalEngineer.Flight.Sections;
using KerbalEngineer.Helpers; using KerbalEngineer.Helpers;
   
using UnityEngine; using UnityEngine;
   
#endregion #endregion
   
namespace KerbalEngineer.Flight.Readouts.Miscellaneous namespace KerbalEngineer.Flight.Readouts.Miscellaneous
{ {
public class Separator : ReadoutModule public class Separator : ReadoutModule
{ {
#region Fields #region Fields
   
private GUIStyle boxStyle; private GUIStyle boxStyle;
private GUIStyle boxStyleHud; private GUIStyle boxStyleHud;
   
#endregion #endregion
   
#region Constructors #region Constructors
   
public Separator() public Separator()
{ {
this.Name = "Separator"; this.Name = "Separator";
this.Category = ReadoutCategory.GetCategory("Miscellaneous"); this.Category = ReadoutCategory.GetCategory("Miscellaneous");
this.HelpString = String.Empty; this.HelpString = "Creats a line to help seperate subsections in a module.";
this.IsDefault = false; this.IsDefault = false;
this.Cloneable = true; this.Cloneable = true;
   
this.InitialiseStyles(); this.InitialiseStyles();
   
GuiDisplaySize.OnSizeChanged += this.InitialiseStyles; GuiDisplaySize.OnSizeChanged += this.InitialiseStyles;
} }
   
#endregion #endregion
   
#region Methods: public #region Methods: public
   
public override void Draw(SectionModule section) public override void Draw(SectionModule section)
{ {
GUILayout.Box(String.Empty, section.IsHud ? this.boxStyleHud : this.boxStyle); GUILayout.Box(String.Empty, section.IsHud ? this.boxStyleHud : this.boxStyle);
} }
   
#endregion #endregion
   
#region Methods: private #region Methods: private
   
private void InitialiseStyles() private void InitialiseStyles()
{ {
this.boxStyle = new GUIStyle this.boxStyle = new GUIStyle
{ {
normal = normal =
{ {
background = TextureHelper.CreateTextureFromColour(new Color(1.0f, 1.0f, 1.0f, 0.5f)) background = TextureHelper.CreateTextureFromColour(new Color(1.0f, 1.0f, 1.0f, 0.5f))
}, },
fixedHeight = 1.0f, fixedHeight = 1.0f,
stretchWidth = true stretchWidth = true
}; };
   
this.boxStyleHud = new GUIStyle(this.boxStyle) this.boxStyleHud = new GUIStyle(this.boxStyle)
{ {
margin = new RectOffset(0, 0, (int)(8 * GuiDisplaySize.Offset), 0) margin = new RectOffset(0, 0, (int)(8 * GuiDisplaySize.Offset), 0)
}; };
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using KerbalEngineer.Flight.Sections; using KerbalEngineer.Flight.Sections;
using KerbalEngineer.VesselSimulator; using KerbalEngineer.VesselSimulator;
   
using UnityEngine; using UnityEngine;
   
#endregion #endregion
   
namespace KerbalEngineer.Flight.Readouts.Miscellaneous namespace KerbalEngineer.Flight.Readouts.Miscellaneous
{ {
using System; using System;
   
public class SimulationDelay : ReadoutModule public class SimulationDelay : ReadoutModule
{ {
#region Constructors #region Constructors
   
public SimulationDelay() public SimulationDelay()
{ {
this.Name = "Minimum Simulation Delay"; this.Name = "Minimum Simulation Delay";
this.Category = ReadoutCategory.GetCategory("Miscellaneous"); this.Category = ReadoutCategory.GetCategory("Miscellaneous");
this.HelpString = "Controls the minimum delay between processing vessel simulations."; this.HelpString = "Controls the minimum delay between processing vessel simulations.";
this.IsDefault = true; this.IsDefault = true;
} }
   
#endregion #endregion
   
#region Methods: public #region Methods: public
   
public override void Draw(SectionModule section) public override void Draw(SectionModule section)
{ {
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
GUILayout.Label("Sim Delay", this.NameStyle); GUILayout.Label("Sim Delay", this.NameStyle);
GUI.skin = HighLogic.Skin; GUI.skin = HighLogic.Skin;
SimManager.minSimTime = new TimeSpan(0, 0, 0, 0, (int)GUILayout.HorizontalSlider(SimManager.minSimTime.Milliseconds, 0, 1000.0f)); SimManager.minSimTime = TimeSpan.FromMilliseconds(GUILayout.HorizontalSlider((float)SimManager.minSimTime.TotalMilliseconds, 0, 2000.0f));
GUI.skin = null; GUI.skin = null;
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using System; using System;
   
using KerbalEngineer.Flight.Sections; using KerbalEngineer.Flight.Sections;
using KerbalEngineer.Helpers; using KerbalEngineer.Helpers;
   
using UnityEngine; using UnityEngine;
   
#endregion #endregion
   
namespace KerbalEngineer.Flight.Readouts.Miscellaneous namespace KerbalEngineer.Flight.Readouts.Miscellaneous
{ {
public class SystemTime : ReadoutModule public class SystemTime : ReadoutModule
{ {
   
   
#region Constructors #region Constructors
   
public SystemTime() public SystemTime()
{ {
this.Name = "System Time"; this.Name = "System Time";
this.Category = ReadoutCategory.GetCategory("Miscellaneous"); this.Category = ReadoutCategory.GetCategory("Miscellaneous");
this.HelpString = String.Empty; this.HelpString = "Shows the System Time in 12 hour format (AM/PM)";
this.IsDefault = false; this.IsDefault = false;
} }
   
#endregion #endregion
   
#region Methods: public #region Methods: public
   
public override void Draw(SectionModule section) public override void Draw(SectionModule section)
{ {
this.DrawLine(DateTime.Now.ToLongTimeString(), section.IsHud); this.DrawLine(DateTime.Now.ToLongTimeString(), section.IsHud);
} }
   
#endregion #endregion
   
} }
} }
//  
// Kerbal Engineer Redux  
//  
// Copyright (C) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
#region Using Directives  
 
using System;  
 
using KerbalEngineer.Flight.Sections;  
using KerbalEngineer.Helpers;  
 
using UnityEngine;  
 
#endregion  
 
namespace KerbalEngineer.Flight.Readouts.Miscellaneous  
{  
public class TimeReference : ReadoutModule  
{  
#region Constructors  
 
public TimeReference()  
{  
this.Name = "Time Reference Adjuster";  
this.Category = ReadoutCategory.GetCategory("Miscellaneous");  
this.HelpString = String.Empty;  
this.IsDefault = false;  
}  
 
#endregion  
 
#region Methods: public  
 
public override void Draw(SectionModule section)  
{  
GUILayout.BeginHorizontal();  
GUILayout.Label("Time Ref.: " + TimeFormatter.Reference, this.NameStyle);  
if (GUILayout.Button("Earth", this.ButtonStyle))  
{  
TimeFormatter.SetReference();  
}  
if (GUILayout.Button("Kerbin", this.ButtonStyle))  
{  
TimeFormatter.SetReference(PSystemManager.Instance.localBodies.Find(body => body.bodyName.Equals("Kerbin")));  
}  
GUILayout.EndHorizontal();  
}  
 
#endregion  
}  
}  
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using KerbalEngineer.Extensions; using KerbalEngineer.Extensions;
using KerbalEngineer.Flight.Sections; using KerbalEngineer.Flight.Sections;
   
#endregion #endregion
   
namespace KerbalEngineer.Flight.Readouts.Orbital namespace KerbalEngineer.Flight.Readouts.Orbital
{ {
public class AngleToEquatorialAscendingNode : ReadoutModule public class AngleToEquatorialAscendingNode : ReadoutModule
{ {
#region Constructors #region Constructors
   
public AngleToEquatorialAscendingNode() public AngleToEquatorialAscendingNode()
{ {
this.Name = "Angle to Equ. AN"; this.Name = "Angle to Equ. AN";
this.Category = ReadoutCategory.GetCategory("Orbital"); this.Category = ReadoutCategory.GetCategory("Orbital");
this.HelpString = string.Empty; this.HelpString = "Angular Distance from the vessel to crossing the Equator of the central body, going north of it.";
this.IsDefault = false; this.IsDefault = false;
} }
   
#endregion #endregion
   
#region Methods: public #region Methods: public
   
public override void Draw(SectionModule section) public override void Draw(SectionModule section)
{ {
this.DrawLine(FlightGlobals.ActiveVessel.orbit.GetAngleToAscendingNode().ToAngle(), section.IsHud); this.DrawLine(FlightGlobals.ActiveVessel.orbit.GetAngleToAscendingNode().ToAngle(), section.IsHud);
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using KerbalEngineer.Extensions; using KerbalEngineer.Extensions;
using KerbalEngineer.Flight.Sections; using KerbalEngineer.Flight.Sections;
   
#endregion #endregion
   
namespace KerbalEngineer.Flight.Readouts.Orbital namespace KerbalEngineer.Flight.Readouts.Orbital
{ {
public class AngleToEquatorialDescendingNode : ReadoutModule public class AngleToEquatorialDescendingNode : ReadoutModule
{ {
#region Constructors #region Constructors
   
public AngleToEquatorialDescendingNode() public AngleToEquatorialDescendingNode()
{ {
this.Name = "Angle to Equ. DN"; this.Name = "Angle to Equ. DN";
this.Category = ReadoutCategory.GetCategory("Orbital"); this.Category = ReadoutCategory.GetCategory("Orbital");
this.HelpString = string.Empty; this.HelpString = "Angular Distance from the vessel to crossing the Equator of the central body, going south of it.";
this.IsDefault = false; this.IsDefault = false;
} }
   
#endregion #endregion
   
#region Methods: public #region Methods: public
   
public override void Draw(SectionModule section) public override void Draw(SectionModule section)
{ {
this.DrawLine(FlightGlobals.ActiveVessel.orbit.GetAngleToDescendingNode().ToAngle(), section.IsHud); this.DrawLine(FlightGlobals.ActiveVessel.orbit.GetAngleToDescendingNode().ToAngle(), section.IsHud);
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using System; using System;
   
using KerbalEngineer.Extensions; using KerbalEngineer.Extensions;
using KerbalEngineer.Flight.Sections; using KerbalEngineer.Flight.Sections;
   
#endregion #endregion
   
namespace KerbalEngineer.Flight.Readouts.Orbital namespace KerbalEngineer.Flight.Readouts.Orbital
{ {
public class AngleToPrograde : ReadoutModule public class AngleToPrograde : ReadoutModule
{ {
#region Constructors #region Constructors
   
public AngleToPrograde() public AngleToPrograde()
{ {
this.Name = "Angle to Prograde"; this.Name = "Angle to Prograde";
this.Category = ReadoutCategory.GetCategory("Orbital"); this.Category = ReadoutCategory.GetCategory("Orbital");
this.HelpString = String.Empty; this.HelpString = "Angular Distance from the vessel to crossing the Orbit of the central body on it's retrograde side.";
this.IsDefault = true; this.IsDefault = true;
} }
   
#endregion #endregion
   
#region Methods: public #region Methods: public
   
public override void Draw(SectionModule section) public override void Draw(SectionModule section)
{ {
this.DrawLine(FlightGlobals.ship_orbit.GetAngleToPrograde().ToAngle(), section.IsHud); this.DrawLine(FlightGlobals.ship_orbit.GetAngleToPrograde().ToAngle(), section.IsHud);
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using System; using System;
   
using KerbalEngineer.Extensions; using KerbalEngineer.Extensions;
using KerbalEngineer.Flight.Sections; using KerbalEngineer.Flight.Sections;
   
#endregion #endregion
   
namespace KerbalEngineer.Flight.Readouts.Orbital namespace KerbalEngineer.Flight.Readouts.Orbital
{ {
public class AngleToRetrograde : ReadoutModule public class AngleToRetrograde : ReadoutModule
{ {
#region Constructors #region Constructors
   
public AngleToRetrograde() public AngleToRetrograde()
{ {
this.Name = "Angle to Retrograde"; this.Name = "Angle to Retrograde";
this.Category = ReadoutCategory.GetCategory("Orbital"); this.Category = ReadoutCategory.GetCategory("Orbital");
this.HelpString = String.Empty; this.HelpString = "Angular Distance from the vessel to crossing the Orbit of the central body on it's retrograde side.";
this.IsDefault = true; this.IsDefault = true;
} }
   
#endregion #endregion
   
#region Methods: public #region Methods: public
   
public override void Draw(SectionModule section) public override void Draw(SectionModule section)
{ {
this.DrawLine(FlightGlobals.ship_orbit.GetAngleToRetrograde().ToAngle(), section.IsHud); this.DrawLine(FlightGlobals.ship_orbit.GetAngleToRetrograde().ToAngle(), section.IsHud);
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using KerbalEngineer.Extensions; using KerbalEngineer.Extensions;
using KerbalEngineer.Flight.Sections; using KerbalEngineer.Flight.Sections;
   
#endregion #endregion
   
namespace KerbalEngineer.Flight.Readouts.Orbital namespace KerbalEngineer.Flight.Readouts.Orbital
{ {
public class ApoapsisHeight : ReadoutModule public class ApoapsisHeight : ReadoutModule
{ {
#region Constructors #region Constructors
   
public ApoapsisHeight() public ApoapsisHeight()
{ {
this.Name = "Apoapsis Height"; this.Name = "Apoapsis Height";
this.Category = ReadoutCategory.GetCategory("Orbital"); this.Category = ReadoutCategory.GetCategory("Orbital");
this.HelpString = "Shows the vessel's apoapsis height relative to sea level. (Apoapsis is the highest point of an orbit.)"; this.HelpString = "Shows the vessel's apoapsis height relative to sea level. (Apoapsis is the highest point of an orbit.)";
this.IsDefault = true; this.IsDefault = true;
} }
   
#endregion #endregion
   
#region Methods: public #region Methods: public
   
public override void Draw(SectionModule section) public override void Draw(SectionModule section)
{ {
this.DrawLine(FlightGlobals.ship_orbit.ApA.ToDistance(), section.IsHud); this.DrawLine(FlightGlobals.ship_orbit.ApA.ToDistance(), section.IsHud);
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2015 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives  
   
using System;  
   
using KerbalEngineer.Extensions;  
using KerbalEngineer.Flight.Sections;  
   
#endregion  
   
namespace KerbalEngineer.Flight.Readouts.Orbital namespace KerbalEngineer.Flight.Readouts.Orbital
{ {
  using Extensions;
  using Helpers;
  using Sections;
   
public class EccentricAnomaly : ReadoutModule public class EccentricAnomaly : ReadoutModule
{ {
#region Constructors  
   
public EccentricAnomaly() public EccentricAnomaly()
{ {
this.Name = "Eccentric Anomaly"; Name = "Eccentric Anomaly";
this.Category = ReadoutCategory.GetCategory("Orbital"); Category = ReadoutCategory.GetCategory("Orbital");
this.HelpString = String.Empty; HelpString = string.Empty;
this.IsDefault = false; IsDefault = false;
} }
   
#endregion  
   
#region Methods: public  
   
public override void Draw(SectionModule section) public override void Draw(SectionModule section)
{ {
this.DrawLine(FlightGlobals.ship_orbit.eccentricAnomaly.ToAngle(), section.IsHud); DrawLine((FlightGlobals.ship_orbit.eccentricAnomaly * Units.RAD_TO_DEG).ToAngle(), section.IsHud);
} }
   
#endregion  
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using KerbalEngineer.Flight.Sections; using KerbalEngineer.Flight.Sections;
   
#endregion #endregion
   
namespace KerbalEngineer.Flight.Readouts.Orbital namespace KerbalEngineer.Flight.Readouts.Orbital
{ {
public class Eccentricity : ReadoutModule public class Eccentricity : ReadoutModule
{ {
#region Constructors #region Constructors
   
public Eccentricity() public Eccentricity()
{ {
this.Name = "Eccentricity"; this.Name = "Eccentricity";
this.Category = ReadoutCategory.GetCategory("Orbital"); this.Category = ReadoutCategory.GetCategory("Orbital");
this.HelpString = "Shows the vessel's orbital eccentricity."; this.HelpString = "Shows the vessel's orbital eccentricity.";
this.IsDefault = true; this.IsDefault = true;
} }
   
#endregion #endregion
   
#region Methods: public #region Methods: public
   
public override void Draw(SectionModule section) public override void Draw(SectionModule section)
{ {
this.DrawLine(FlightGlobals.ship_orbit.eccentricity.ToString("F3"), section.IsHud); this.DrawLine(FlightGlobals.ship_orbit.eccentricity.ToString("F5"), section.IsHud);
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using KerbalEngineer.Extensions; using KerbalEngineer.Extensions;
using KerbalEngineer.Flight.Sections; using KerbalEngineer.Flight.Sections;
   
#endregion #endregion
   
namespace KerbalEngineer.Flight.Readouts.Orbital namespace KerbalEngineer.Flight.Readouts.Orbital
{ {
public class Inclination : ReadoutModule public class Inclination : ReadoutModule
{ {
#region Constructors #region Constructors
   
public Inclination() public Inclination()
{ {
this.Name = "Inclination"; this.Name = "Inclination";
this.Category = ReadoutCategory.GetCategory("Orbital"); this.Category = ReadoutCategory.GetCategory("Orbital");
this.HelpString = "Shows the vessel's orbital inclination."; this.HelpString = "Shows the vessel's orbital inclination relative to the Equator.";
this.IsDefault = true; this.IsDefault = true;
} }
   
#endregion #endregion
   
#region Methods: public #region Methods: public
   
public override void Draw(SectionModule section) public override void Draw(SectionModule section)
{ {
this.DrawLine(FlightGlobals.ship_orbit.inclination.ToAngle(), section.IsHud); this.DrawLine(FlightGlobals.ship_orbit.inclination.ToAngle(), section.IsHud);
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using System; using System;
   
using KerbalEngineer.Extensions; using KerbalEngineer.Extensions;
using KerbalEngineer.Flight.Readouts.Vessel; using KerbalEngineer.Flight.Readouts.Vessel;
   
using UnityEngine; using UnityEngine;
   
#endregion #endregion
   
namespace KerbalEngineer.Flight.Readouts.Orbital.ManoeuvreNode namespace KerbalEngineer.Flight.Readouts.Orbital.ManoeuvreNode
{ {
  using Helpers;
   
public class ManoeuvreProcessor : IUpdatable, IUpdateRequest public class ManoeuvreProcessor : IUpdatable, IUpdateRequest
{ {
#region Fields #region Fields
   
private static readonly ManoeuvreProcessor instance = new ManoeuvreProcessor(); private static readonly ManoeuvreProcessor instance = new ManoeuvreProcessor();
   
#endregion #endregion
   
#region Properties #region Properties
   
public static double AngleToPrograde { get; private set; } public static double AngleToPrograde { get; private set; }
   
public static double AngleToRetrograde { get; private set; } public static double AngleToRetrograde { get; private set; }
   
public static double AvailableDeltaV { get; private set; } public static double AvailableDeltaV { get; private set; }
   
public static double BurnTime { get; private set; } public static double BurnTime { get; private set; }
   
public static int FinalStage { get; private set; } public static int FinalStage { get; private set; }
   
public static double HalfBurnTime { get; private set; } public static double HalfBurnTime { get; private set; }
   
public static bool HasDeltaV { get; private set; } public static bool HasDeltaV { get; private set; }
   
public static ManoeuvreProcessor Instance public static ManoeuvreProcessor Instance
{ {
get { return instance; } get { return instance; }
} }
   
public static double NormalDeltaV { get; private set; } public static double NormalDeltaV { get; private set; }
   
  public static double PostBurnAp { get; private set; }
   
  public static double PostBurnPe { get; private set; }
   
public static double ProgradeDeltaV { get; private set; } public static double ProgradeDeltaV { get; private set; }
   
public static double RadialDeltaV { get; private set; } public static double RadialDeltaV { get; private set; }
   
public static bool ShowDetails { get; set; } public static bool ShowDetails { get; set; }
   
public static double TotalDeltaV { get; private set; } public static double TotalDeltaV { get; private set; }
   
public static double UniversalTime { get; private set; } public static double UniversalTime { get; private set; }
   
public bool UpdateRequested { get; set; } public bool UpdateRequested { get; set; }
   
#endregion #endregion
   
#region Methods: public #region Methods: public
   
public static void RequestUpdate() public static void RequestUpdate()
{ {
instance.UpdateRequested = true; instance.UpdateRequested = true;
SimulationProcessor.RequestUpdate(); SimulationProcessor.RequestUpdate();
} }
   
public static void Reset() public static void Reset()
{ {
FlightEngineerCore.Instance.AddUpdatable(SimulationProcessor.Instance); FlightEngineerCore.Instance.AddUpdatable(SimulationProcessor.Instance);
FlightEngineerCore.Instance.AddUpdatable(instance); FlightEngineerCore.Instance.AddUpdatable(instance);
} }
   
public void Update() public void Update()
{ {
// Extra tests for low level tracking station not supporting patched conics and maneuver nodes // Extra tests for low level tracking station not supporting patched conics and maneuver nodes
if (FlightGlobals.ActiveVessel.patchedConicSolver == null || if (FlightGlobals.ActiveVessel.patchedConicSolver == null ||
FlightGlobals.ActiveVessel.patchedConicSolver.maneuverNodes == null || FlightGlobals.ActiveVessel.patchedConicSolver.maneuverNodes == null ||
FlightGlobals.ActiveVessel.patchedConicSolver.maneuverNodes.Count == 0 || FlightGlobals.ActiveVessel.patchedConicSolver.maneuverNodes.Count == 0 ||
!SimulationProcessor.ShowDetails) !SimulationProcessor.ShowDetails)
{ {
ShowDetails = false; ShowDetails = false;
return; return;
} }
   
var node = FlightGlobals.ActiveVessel.patchedConicSolver.maneuverNodes[0]; var node = FlightGlobals.ActiveVessel.patchedConicSolver.maneuverNodes[0];
var deltaV = node.DeltaV; var deltaV = node.DeltaV;
   
ProgradeDeltaV = deltaV.z; ProgradeDeltaV = deltaV.z;
NormalDeltaV = deltaV.y; NormalDeltaV = deltaV.y;
RadialDeltaV = deltaV.x; RadialDeltaV = deltaV.x;
TotalDeltaV = node.GetBurnVector(FlightGlobals.ship_orbit).magnitude; TotalDeltaV = node.GetBurnVector(FlightGlobals.ship_orbit).magnitude;
  PostBurnAp = node.nextPatch != null ? node.nextPatch.ApA : 0;
  PostBurnPe = node.nextPatch != null ? node.nextPatch.PeA : 0;
   
UniversalTime = FlightGlobals.ActiveVessel.patchedConicSolver.maneuverNodes[0].UT; UniversalTime = FlightGlobals.ActiveVessel.patchedConicSolver.maneuverNodes[0].UT;
AngleToPrograde = FlightGlobals.ActiveVessel.patchedConicSolver.maneuverNodes[0].patch.GetAngleToPrograde(UniversalTime); AngleToPrograde = FlightGlobals.ActiveVessel.patchedConicSolver.maneuverNodes[0].patch.GetAngleToPrograde(UniversalTime);
AngleToRetrograde = FlightGlobals.ActiveVessel.patchedConicSolver.maneuverNodes[0].patch.GetAngleToRetrograde(UniversalTime); AngleToRetrograde = FlightGlobals.ActiveVessel.patchedConicSolver.maneuverNodes[0].patch.GetAngleToRetrograde(UniversalTime);
   
var burnTime = 0.0; var burnTime = 0.0;
var midPointTime = 0.0; var midPointTime = 0.0;
HasDeltaV = GetBurnTime(TotalDeltaV, ref burnTime, ref midPointTime); HasDeltaV = GetBurnTime(TotalDeltaV, ref burnTime, ref midPointTime);
AvailableDeltaV = SimulationProcessor.LastStage.totalDeltaV; AvailableDeltaV = SimulationProcessor.LastStage.totalDeltaV;
   
BurnTime = burnTime; BurnTime = burnTime;
HalfBurnTime = midPointTime; HalfBurnTime = midPointTime;
   
ShowDetails = true; ShowDetails = true;
} }
   
#endregion #endregion
   
#region Methods: private #region Methods: private
   
private static bool GetBurnTime(double deltaV, ref double burnTime, ref double midPointTime) private static bool GetBurnTime(double deltaV, ref double burnTime, ref double midPointTime)
{ {
var setMidPoint = false; var setMidPoint = false;
var deltaVMidPoint = deltaV * 0.5; var deltaVMidPoint = deltaV * 0.5;
   
for (var i = SimulationProcessor.Stages.Length - 1; i > -1; i--) for (var i = SimulationProcessor.Stages.Length - 1; i > -1; i--)
{ {
var stage = SimulationProcessor.Stages[i]; var stage = SimulationProcessor.Stages[i];
var stageDeltaV = stage.deltaV; var stageDeltaV = stage.deltaV;
var startMass = stage.totalMass; var startMass = stage.totalMass;
   
ProcessStageDrain: ProcessStageDrain:
if (deltaV <= Double.Epsilon) if (deltaV <= Double.Epsilon)
{ {
break; break;
} }
if (stageDeltaV <= Double.Epsilon) if (stageDeltaV <= Double.Epsilon)
{ {
continue; continue;
} }
   
FinalStage = i; FinalStage = i;
   
double deltaVDrain; double deltaVDrain;
if (deltaVMidPoint > 0.0) if (deltaVMidPoint > 0.0)
{ {
deltaVDrain = deltaV.Clamp(0.0, stageDeltaV.Clamp(0.0, deltaVMidPoint)); deltaVDrain = deltaV.Clamp(0.0, stageDeltaV.Clamp(0.0, deltaVMidPoint));
deltaVMidPoint -= deltaVDrain; deltaVMidPoint -= deltaVDrain;
setMidPoint = deltaVMidPoint <= Double.Epsilon; setMidPoint = deltaVMidPoint <= Double.Epsilon;
} }
else else
{ {
deltaVDrain = deltaV.Clamp(0.0, stageDeltaV); deltaVDrain = deltaV.Clamp(0.0, stageDeltaV);
} }
   
var exhaustVelocity = stage.isp * 9.82; var exhaustVelocity = stage.isp * Units.GRAVITY;
var flowRate = stage.thrust / exhaustVelocity; var flowRate = stage.thrust / exhaustVelocity;
var endMass = Math.Exp(Math.Log(startMass) - deltaVDrain / exhaustVelocity); var endMass = Math.Exp(Math.Log(startMass) - deltaVDrain / exhaustVelocity);
var deltaMass = (startMass - endMass) * Math.Exp(-(deltaVDrain * 0.001) / exhaustVelocity); var deltaMass = (startMass - endMass) * Math.Exp(-(deltaVDrain * 0.001) / exhaustVelocity);
burnTime += deltaMass / flowRate; burnTime += deltaMass / flowRate;
   
deltaV -= deltaVDrain; deltaV -= deltaVDrain;
stageDeltaV -= deltaVDrain; stageDeltaV -= deltaVDrain;
startMass -= deltaMass; startMass -= deltaMass;
   
if (setMidPoint) if (setMidPoint)
{ {
midPointTime = burnTime; midPointTime = burnTime;
setMidPoint = false; setMidPoint = false;
goto ProcessStageDrain; goto ProcessStageDrain;
} }
} }