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

1.0.19.0 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: Added current vessel name readout. (antplant)
Added: 'Relative Radial Velocity' and 'Time To Rendezvous' readouts. (itwtx) Added: 'Relative Radial Velocity' and 'Time To Rendezvous' readouts. (itwtx)
Added: Readout help strings. (harryyoung) Added: Readout help strings. (harryyoung)
Changed: The 'Torque' value in the editor is now precise to two decimal places. 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: 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. Changed: Eccentric Anomaly, Mean Anomaly and Mean Anomaly At Epoc now display in degrees rather than radians.
Fixed: Optimised time formatting. (itwtx) Fixed: Optimised time formatting. (itwtx)
Fixed: TimeToAtmosphere checks that the Apoapsis is outside atmosphere. (Kerbas-ad-astra) 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 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: 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: 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. Fixed: Roll axis readout now shows the correct sign.
Removed: Time Formatter readout as it's not required anymore. Removed: Time Formatter readout as it's not required anymore.
   
1.0.18.0 1.0.18.0
Added: Orbital readouts - "Speed at Periapsis" and "Speed at Apoapsis". (Padishar) Added: Orbital readouts - "Speed at Periapsis" and "Speed at Apoapsis". (Padishar)
Added: Manoeuvre readouts - "Post-burn Apoapsis" and "Post-burn Periapsis". (Padishar) Added: Manoeuvre readouts - "Post-burn Apoapsis" and "Post-burn Periapsis". (Padishar)
Added: Orbital readout - "Time to Atmosphere". Added: Orbital readout - "Time to Atmosphere".
Fixed: Synched the minimum simulation time sliders and stopped them from snapping back after 999ms. (saybur) 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: 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: Physically insignificant part mass was not being correctly cascaded down through multiple parent parts.
Fixed: Intake air demand calculation not working. Fixed: Intake air demand calculation not working.
Fixed: Some build engineer settings labels do not scale with UI size. Fixed: Some build engineer settings labels do not scale with UI size.
   
1.0.17.0 1.0.17.0
Added: 'Mach Number' readout under the 'Surface' category and included it on the default surface HUD. 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: Stock sections in the Flight Engineer can now become HUDs.
Added 'Thermal' readouts category including: Added 'Thermal' readouts category including:
Internal Flux Internal Flux
Convection Flux Convection Flux
Radiation Flux Radiation Flux
Critical Part Name Critical Part Name
Critical Part Temperature Critical Part Temperature
Critical Part Skin Temperature Critical Part Skin Temperature
Critical Part Thermal Percentage of Max Temperature Critical Part Thermal Percentage of Max Temperature
Hottest Part Name Hottest Part Name
Hottest Part Temperature Hottest Part Temperature
Hottest Part Skin Temperature Hottest Part Skin Temperature
Coldest Part Name Coldest Part Name
Coldest Part Temperature Coldest Part Temperature
Coldest Part Skin Temperature Coldest Part Skin Temperature
   
Changed: Mach on the Build Engineer now accurate to 2 decimal places. 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: 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: Increased eccentricity readout to 5 decimal places.
Changed: Implemented Sarbian's object pooling. Changed: Implemented Sarbian's object pooling.
Changed: The default selected body is now assigned via 'Planitarium.Home'. 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. 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: 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: Longitude and Latitude readouts now use a KER formatter instead of Squad's incorrect implementation.
Fixed: Possible null reference in the Rendezvous Processor. Fixed: Possible null reference in the Rendezvous Processor.
Fixed: Fairing mass issues introduced with regards to simulation changes. Fixed: Fairing mass issues introduced with regards to simulation changes.
Fixed: Use of per-propellant fuel flow mode override. Fixed: Use of per-propellant fuel flow mode override.
Fixed: Burn times calculated for jet engines. Fixed: Burn times calculated for jet engines.
Fixed: Thrust issues introduced with Sarbian's simulation alterations. 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. 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 1.0.16.6, 02-05-15
Fixed: Separately staged fairing mass jettisons are now calculated in the editor. Fixed: Separately staged fairing mass jettisons are now calculated in the editor.
   
1.0.16.5, 02-05-2015 1.0.16.5, 02-05-2015
Fixed: Delta-V not being correctly calculated. Fixed: Delta-V not being correctly calculated.
Changed: Editor locking now uses the InputLockManager. Changed: Editor locking now uses the InputLockManager.
   
1.0.16.4, 01-05-2015 1.0.16.4, 01-05-2015
Fixed: Physically insignificant part mass is now accounted for. 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). Changed: Module mass accounted for as it now makes its way onto the launch pad (e.g. fairings).
   
Various optimisations: Various optimisations:
Object pooling. Object pooling.
Removed LINQ expressions. Removed LINQ expressions.
Converted foreach to for loops. Converted foreach to for loops.
   
1.0.16.3, 27-04-2015 1.0.16.3, 27-04-2015
Fixed issue with the toolbar icons not being created. Fixed issue with the toolbar icons not being created.
Removed superfluous 'm/s' on the mach slider in the build engineer. Removed superfluous 'm/s' on the mach slider in the build engineer.
   
1.0.16.2, 27-04-2015 1.0.16.2, 27-04-2015
Changed the atmospheric slider on the build engineer to default to 0km when changing bodies. 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 1.0.16.1, 26-04-2015, KSP Build #828
Merged Sarbian's mach adjustments. Merged Sarbian's mach adjustments.
Fixed bugs relating to thrust and atmosphere/velocity curves. 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 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 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. 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 1.0.16.0, 25-04-2015, KSP Build #821
Fixed errors relating to KSP 1.0 update. Fixed errors relating to KSP 1.0 update.
Fixed fuel simulation to account for new thrust system. Fixed fuel simulation to account for new thrust system.
Fixed atmospheric engines to use the new velocity curve. Fixed atmospheric engines to use the new velocity curve.
Fixed atmospheric readouts to work with the new atmospheric model. Fixed atmospheric readouts to work with the new atmospheric model.
   
1.0.15.2, 13-02-2015 1.0.15.2, 13-02-2015
Padishar's Fixes: Padishar's Fixes:
Fixed: Calculation of per-stage resource mass. Fixed: Calculation of per-stage resource mass.
   
1.0.15.1, 13-02-2015 1.0.15.1, 13-02-2015
Rebuild Rebuild
   
1.0.15.0, 08-02-2015 1.0.15.0, 08-02-2015
Padishar's Fixes: Padishar's Fixes:
Added: Support KIDS ISP thrust correction. Added: Support KIDS ISP thrust correction.
Fixed: Log spam for stage priority mode. Fixed: Log spam for stage priority mode.
Fixed: Locked tanks preventing simulation from staging. Fixed: Locked tanks preventing simulation from staging.
Fixed: No flow and all vessel modes to respect flow states. Fixed: No flow and all vessel modes to respect flow states.
   
1.0.14.1, 28-12-2014 1.0.14.1, 28-12-2014
Fixed: Missing texture on the ER-7500 model. 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.
   
// //
// Copyright (C) 2015 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/>.
// //
   
namespace KerbalEngineer.Editor namespace KerbalEngineer.Editor
{ {
using System; using System;
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;
   
[KSPAddon(KSPAddon.Startup.EditorAny, false)] [KSPAddon(KSPAddon.Startup.EditorAny, false)]
public class BuildAdvanced : MonoBehaviour public class BuildAdvanced : MonoBehaviour
{ {
public static float Altitude; public static float Altitude;
   
private static Rect compactModeRect = new Rect(0.0f, 5.0f, 0.0f, 20.0f); private static Rect compactModeRect = new Rect(0.0f, 5.0f, 0.0f, 20.0f);
private static Stage stage; private static Stage stage;
private static int stagesCount; private static int stagesCount;
private static int stagesLength; private static int stagesLength;
private static string title; private static string title;
   
private GUIStyle areaSettingStyle; private GUIStyle areaSettingStyle;
private GUIStyle areaStyle; private GUIStyle areaStyle;
private float atmosphericMach; private float atmosphericMach;
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 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;
   
/// <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 get
{ {
return compactMode; return compactMode;
} }
set set
{ {
compactMode = value; 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 get
{ {
return showAllStages; return showAllStages;
} }
set set
{ {
showAllStages = value; 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 get
{ {
return showAtmosphericDetails; return showAtmosphericDetails;
} }
set set
{ {
showAtmosphericDetails = value; 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 get
{ {
return showSettings; return showSettings;
} }
set set
{ {
showSettings = value; 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 get
{ {
return visible; return visible;
} }
set set
{ {
visible = value; visible = value;
} }
} }
   
protected void Awake() protected void Awake()
{ {
try try
{ {
Instance = this; Instance = this;
bodiesList = gameObject.AddComponent<DropDown>(); bodiesList = gameObject.AddComponent<DropDown>();
bodiesList.DrawCallback = DrawBodiesList; bodiesList.DrawCallback = DrawBodiesList;
Load(); Load();
   
SimManager.UpdateModSettings(); SimManager.UpdateModSettings();
SimManager.OnReady -= GetStageInfo; SimManager.OnReady -= GetStageInfo;
SimManager.OnReady += GetStageInfo; SimManager.OnReady += GetStageInfo;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex, "BuildAdvanced.Awake()"); 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"); Logger.Log("BuildAdvanced->OnDestroy");
   
try try
{ {
SettingHandler handler = new SettingHandler(); SettingHandler handler = new SettingHandler();
handler.Set("visible", visible); handler.Set("visible", visible);
handler.Set("windowPositionX", position.x); handler.Set("windowPositionX", position.x);
handler.Set("windowPositionY", position.y); handler.Set("windowPositionY", position.y);
handler.Set("compactMode", compactMode); handler.Set("compactMode", compactMode);
handler.Set("compactCollapseRight", compactCollapseRight); handler.Set("compactCollapseRight", compactCollapseRight);
handler.Set("showAllStages", showAllStages); handler.Set("showAllStages", showAllStages);
handler.Set("showAtmosphericDetails", showAtmosphericDetails); handler.Set("showAtmosphericDetails", showAtmosphericDetails);
handler.Set("showSettings", 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 -= OnSizeChanged; GuiDisplaySize.OnSizeChanged -= OnSizeChanged;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex, "BuildAdvanced.OnDestroy()"); Logger.Exception(ex, "BuildAdvanced.OnDestroy()");
} }
   
EditorLock(false); EditorLock(false);
} }
   
protected void OnGUI() protected void OnGUI()
{ {
try try
{ {
if (!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 (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.
title = !compactMode ? "KERBAL ENGINEER REDUX " + EngineerGlobals.ASSEMBLY_VERSION : "K.E.R. " + EngineerGlobals.ASSEMBLY_VERSION; 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.
stagesLength = stages.Length; stagesLength = stages.Length;
if (showAllStages) if (showAllStages)
{ {
stagesCount = stagesLength; stagesCount = stagesLength;
} }
if (showAllStages == false) if (showAllStages == false)
{ {
stagesCount = 0; stagesCount = 0;
for (int i = 0; i < stagesLength; ++i) for (int i = 0; i < stagesLength; ++i)
{ {
if (stages[i].deltaV > 0.0f) if (stages[i].deltaV > 0.0f)
{ {
stagesCount = stagesCount + 1; stagesCount = stagesCount + 1;
} }
} }
} }
   
if (hasChanged || stagesCount != numberOfStages) if (hasChanged || stagesCount != numberOfStages)
{ {
hasChanged = false; hasChanged = false;
numberOfStages = stagesCount; numberOfStages = stagesCount;
   
position.width = 0; position.width = 0;
position.height = 0; position.height = 0;
} }
   
GUI.skin = null; GUI.skin = null;
position = GUILayout.Window(GetInstanceID(), position, Window, title, windowStyle).ClampToScreen(); position = GUILayout.Window(GetInstanceID(), position, Window, title, windowStyle).ClampToScreen();
   
if (compactCheck > 0 && compactCollapseRight) if (compactCheck > 0 && compactCollapseRight)
{ {
position.x = compactRight - position.width; position.x = compactRight - position.width;
compactCheck--; compactCheck--;
} }
else if (compactCheck > 0) else if (compactCheck > 0)
{ {
compactCheck = 0; compactCheck = 0;
} }
   
// Check editor lock to manage click-through. // Check editor lock to manage click-through.
CheckEditorLock(); CheckEditorLock();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex, "BuildAdvanced.OnGUI()"); Logger.Exception(ex, "BuildAdvanced.OnGUI()");
} }
} }
   
protected void Start() protected void Start()
{ {
try try
{ {
InitialiseStyles(); InitialiseStyles();
GuiDisplaySize.OnSizeChanged += OnSizeChanged; GuiDisplaySize.OnSizeChanged += OnSizeChanged;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex, "BuildAdvanced.Start()"); Logger.Exception(ex, "BuildAdvanced.Start()");
} }
} }
   
protected void Update() protected void Update()
{ {
try try
{ {
if (Input.GetKeyDown(KeyBinder.EditorShowHide)) if (Input.GetKeyDown(KeyBinder.EditorShowHide))
{ {
visible = !visible; visible = !visible;
if (!visible) if (!visible)
{ {
EditorLock(false); EditorLock(false);
} }
} }
   
if (!visible || EditorLogic.fetch == null || EditorLogic.fetch.ship.parts.Count == 0) if (!visible || EditorLogic.fetch == null || EditorLogic.fetch.ship.parts.Count == 0)
{ {
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 (showAtmosphericDetails) if (showAtmosphericDetails)
{ {
SimManager.Atmosphere = CelestialBodies.SelectedBody.GetAtmospheres(Altitude); SimManager.Atmosphere = CelestialBodies.SelectedBody.GetAtmospheres(Altitude);
} }
else else
{ {
SimManager.Atmosphere = 0; SimManager.Atmosphere = 0;
} }
   
SimManager.Mach = atmosphericMach; 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 ((position.MouseIsOver() || bodiesList.Position.MouseIsOver()) && !isEditorLocked) if ((position.MouseIsOver() || bodiesList.Position.MouseIsOver()) && !isEditorLocked)
{ {
EditorLock(true); EditorLock(true);
} }
else if (!position.MouseIsOver() && !bodiesList.Position.MouseIsOver() && isEditorLocked) else if (!position.MouseIsOver() && !bodiesList.Position.MouseIsOver() && isEditorLocked)
{ {
EditorLock(false); EditorLock(false);
} }
} }
   
/// <summary> /// <summary>
/// Draws the atmospheric settings. /// Draws the atmospheric settings.
/// </summary> /// </summary>
private void DrawAtmosphericDetails() private void DrawAtmosphericDetails()
{ {
try try
{ {
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
GUILayout.BeginVertical(); GUILayout.BeginVertical();
GUILayout.Label("Altitude: " + (Altitude * 0.001f).ToString("F1") + "km", settingAtmoStyle, GUILayout.Width(125.0f * GuiDisplaySize.Offset)); GUILayout.Label("Altitude: " + (Altitude * 0.001f).ToString("F1") + "km", settingAtmoStyle, GUILayout.Width(125.0f * GuiDisplaySize.Offset));
GUI.skin = HighLogic.Skin; GUI.skin = HighLogic.Skin;
Altitude = GUILayout.HorizontalSlider(Altitude, 0.0f, (float)(CelestialBodies.SelectedBody.CelestialBody.atmosphereDepth)); Altitude = GUILayout.HorizontalSlider(Altitude, 0.0f, (float)(CelestialBodies.SelectedBody.CelestialBody.atmosphereDepth));
GUI.skin = null; GUI.skin = null;
GUILayout.EndVertical(); GUILayout.EndVertical();
   
GUILayout.Space(5.0f); GUILayout.Space(5.0f);
   
GUILayout.BeginVertical(); GUILayout.BeginVertical();
GUILayout.Label("Mach: " + atmosphericMach.ToString("F2"), settingAtmoStyle, GUILayout.Width(125.0f * GuiDisplaySize.Offset)); GUILayout.Label("Mach: " + atmosphericMach.ToString("F2"), settingAtmoStyle, GUILayout.Width(125.0f * GuiDisplaySize.Offset));
GUI.skin = HighLogic.Skin; GUI.skin = HighLogic.Skin;
atmosphericMach = GUILayout.HorizontalSlider(Mathf.Clamp(atmosphericMach, 0.0f, maxMach), 0.0f, maxMach); atmosphericMach = GUILayout.HorizontalSlider(Mathf.Clamp(atmosphericMach, 0.0f, maxMach), 0.0f, maxMach);
GUI.skin = null; GUI.skin = null;
GUILayout.EndVertical(); GUILayout.EndVertical();
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex, "BuildAdvanced.DrawAtmosphericDetails()"); Logger.Exception(ex, "BuildAdvanced.DrawAtmosphericDetails()");
} }
} }
   
private void DrawBodiesList() private void DrawBodiesList()
{ {
if (CelestialBodies.SystemBody == CelestialBodies.SelectedBody) if (CelestialBodies.SystemBody == CelestialBodies.SelectedBody)
{ {
DrawBody(CelestialBodies.SystemBody); DrawBody(CelestialBodies.SystemBody);
} }
else else
{ {
foreach (CelestialBodies.BodyInfo body in CelestialBodies.SystemBody.Children) foreach (CelestialBodies.BodyInfo body in CelestialBodies.SystemBody.Children)
{ {
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 ? bodiesButtonActiveStyle : 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);
Altitude = 0.0f; Altitude = 0.0f;
bodiesList.Resize = true; bodiesList.Resize = true;
} }
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
if (bodyInfo.Selected) if (bodyInfo.Selected)
{ {
for (int i = 0; i < bodyInfo.Children.Count; ++i) for (int i = 0; i < bodyInfo.Children.Count; ++i)
{ {
DrawBody(bodyInfo.Children[i], 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", titleStyle); GUILayout.Label("BURN", titleStyle);
for (int i = 0; i < stagesLength; ++i) for (int i = 0; i < stagesLength; ++i)
{ {
stage = stages[i]; stage = stages[i];
if (showAllStages || stage.deltaV > 0.0) if (showAllStages || stage.deltaV > 0.0)
{ {
GUILayout.Label(TimeFormatter.ConvertToString(stage.time), 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", titleStyle); GUILayout.Label("COST", titleStyle);
for (int i = 0; i < stagesLength; ++i) for (int i = 0; i < stagesLength; ++i)
{ {
stage = stages[i]; stage = stages[i];
if (showAllStages || stage.deltaV > 0.0) if (showAllStages || stage.deltaV > 0.0)
{ {
GUILayout.Label(Units.Cost(stage.cost, stage.totalCost), 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", titleStyle); GUILayout.Label("DELTA-V", titleStyle);
for (int i = 0; i < stagesLength; ++i) for (int i = 0; i < stagesLength; ++i)
{ {
stage = stages[i]; stage = stages[i];
if (showAllStages || stage.deltaV > 0.0) if (showAllStages || stage.deltaV > 0.0)
{ {
GUILayout.Label(stage.deltaV.ToString("N0") + " / " + stage.inverseTotalDeltaV.ToString("N0") + "m/s", 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", titleStyle); GUILayout.Label("ISP", titleStyle);
for (int i = 0; i < stagesLength; ++i) for (int i = 0; i < stagesLength; ++i)
{ {
stage = stages[i]; stage = stages[i];
if (showAllStages || stage.deltaV > 0.0) if (showAllStages || stage.deltaV > 0.0)
{ {
GUILayout.Label(stage.isp.ToString("F1") + "s", 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", titleStyle); GUILayout.Label("MASS", titleStyle);
for (int i = 0; i < stagesLength; ++i) for (int i = 0; i < stagesLength; ++i)
{ {
stage = stages[i]; stage = stages[i];
if (showAllStages || stage.deltaV > 0.0) if (showAllStages || stage.deltaV > 0.0)
{ {
GUILayout.Label(Units.ToMass(stage.mass, stage.totalMass), 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", titleStyle); GUILayout.Label("PARTS", titleStyle);
for (int i = 0; i < stagesLength; ++i) for (int i = 0; i < stagesLength; ++i)
{ {
stage = stages[i]; stage = stages[i];
if (showAllStages || stage.deltaV > 0.0) if (showAllStages || stage.deltaV > 0.0)
{ {
GUILayout.Label(stage.partCount + " / " + stage.totalPartCount, 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:", settingStyle); GUILayout.Label("Compact mode collapses to the:", settingStyle);
compactCollapseRight = !GUILayout.Toggle(!compactCollapseRight, "LEFT", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)); compactCollapseRight = !GUILayout.Toggle(!compactCollapseRight, "LEFT", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
compactCollapseRight = GUILayout.Toggle(compactCollapseRight, "RIGHT", 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:", settingStyle); GUILayout.Label("Simulate using vectored thrust values:", settingStyle);
SimManager.vectoredThrust = GUILayout.Toggle(SimManager.vectoredThrust, "ENABLED", 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("Verbose Simulation Log:", settingStyle); GUILayout.Label("Verbose Simulation Log:", settingStyle);
SimManager.logOutput = GUILayout.Toggle(SimManager.logOutput, "ENABLED", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)); SimManager.logOutput = GUILayout.Toggle(SimManager.logOutput, "ENABLED", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
GUILayout.Label("Build Engineer Overlay:", settingStyle); GUILayout.Label("Build Engineer Overlay:", settingStyle);
BuildOverlay.Visible = GUILayout.Toggle(BuildOverlay.Visible, "VISIBLE", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)); BuildOverlay.Visible = GUILayout.Toggle(BuildOverlay.Visible, "VISIBLE", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
BuildOverlayPartInfo.NamesOnly = GUILayout.Toggle(BuildOverlayPartInfo.NamesOnly, "NAMES ONLY", 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)); 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 activation mode:", settingStyle); GUILayout.Label("Flight Engineer activation mode:", settingStyle);
FlightEngineerCore.IsCareerMode = GUILayout.Toggle(FlightEngineerCore.IsCareerMode, "CAREER", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)); FlightEngineerCore.IsCareerMode = GUILayout.Toggle(FlightEngineerCore.IsCareerMode, "CAREER", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
FlightEngineerCore.IsCareerMode = !GUILayout.Toggle(!FlightEngineerCore.IsCareerMode, "PARTLESS", 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("Flight Engineer Career Limitations:", settingStyle); GUILayout.Label("Flight Engineer Career Limitations:", settingStyle);
FlightEngineerCore.IsKerbalLimited = GUILayout.Toggle(FlightEngineerCore.IsKerbalLimited, "KERBAL", 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)); FlightEngineerCore.IsTrackingStationLimited = GUILayout.Toggle(FlightEngineerCore.IsTrackingStationLimited, "TRACKING", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(); 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); GUILayout.Label("GUI Size: " + GuiDisplaySize.Increment, settingStyle);
if (GUILayout.Button("<", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset))) if (GUILayout.Button("<", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)))
{ {
GuiDisplaySize.Increment--; GuiDisplaySize.Increment--;
} }
if (GUILayout.Button(">", 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.TotalMilliseconds + "ms", settingStyle); GUILayout.Label("Minimum delay between simulations: " + SimManager.minSimTime.TotalMilliseconds + "ms", settingStyle);
GUI.skin = HighLogic.Skin; GUI.skin = HighLogic.Skin;
SimManager.minSimTime = TimeSpan.FromMilliseconds(GUILayout.HorizontalSlider((float)SimManager.minSimTime.TotalMilliseconds, 0, 2000.0f)); SimManager.minSimTime = TimeSpan.FromMilliseconds(GUILayout.HorizontalSlider((float)SimManager.minSimTime.TotalMilliseconds, 0, 2000.0f));
   
GUILayout.BeginHorizontal();  
if (GUILayout.Button("Editor Show/Hide Key: " + KeyBinder.EditorShowHide, buttonStyle, GUILayout.Width(200.0f * GuiDisplaySize.Offset)))  
{  
SelectKeyBindPopup.Show("Flight Show/Hide", KeyBinder.EditorShowHide, keyCode => KeyBinder.EditorShowHide = keyCode);  
}  
if (GUILayout.Button("Flight Show/Hide Key: " + KeyBinder.FlightShowHide, buttonStyle, GUILayout.Width(200.0f * GuiDisplaySize.Offset)))  
{  
SelectKeyBindPopup.Show("Flight Show/Hide", KeyBinder.FlightShowHide, keyCode => KeyBinder.FlightShowHide = keyCode);  
}  
GUILayout.EndHorizontal();  
   
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, titleStyle); GUILayout.Label(string.Empty, titleStyle);
for (int i = 0; i < stagesLength; ++i) for (int i = 0; i < stagesLength; ++i)
{ {
stage = stages[i]; stage = stages[i];
if (showAllStages || stage.deltaV > 0.0) if (showAllStages || stage.deltaV > 0.0)
{ {
GUILayout.Label("S" + stage.number, 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", titleStyle); GUILayout.Label("THRUST", titleStyle);
for (int i = 0; i < stagesLength; ++i) for (int i = 0; i < stagesLength; ++i)
{ {
stage = stages[i]; stage = stages[i];
if (showAllStages || stage.deltaV > 0.0) if (showAllStages || stage.deltaV > 0.0)
{ {
GUILayout.Label(stage.thrust.ToForce(), 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", titleStyle); GUILayout.Label("TORQUE", titleStyle);
for (int i = 0; i < stagesLength; ++i) for (int i = 0; i < stagesLength; ++i)
{ {
stage = stages[i]; stage = stages[i];
if (showAllStages || stage.deltaV > 0.0) if (showAllStages || stage.deltaV > 0.0)
{ {
GUILayout.Label(stage.maxThrustTorque.ToTorque(), 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)", titleStyle); GUILayout.Label("TWR (MAX)", titleStyle);
for (int i = 0; i < stagesLength; ++i) for (int i = 0; i < stagesLength; ++i)
{ {
stage = stages[i]; stage = stages[i];
if (showAllStages || stage.deltaV > 0.0) if (showAllStages || stage.deltaV > 0.0)
{ {
GUILayout.Label(stage.thrustToWeight.ToString("F2") + " (" + stage.maxThrustToWeight.ToString("F2") + ")", 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)
{ {
InputLockManager.SetControlLock(ControlTypes.All, "KER_BuildAdvanced"); InputLockManager.SetControlLock(ControlTypes.All, "KER_BuildAdvanced");
BuildOverlayPartInfo.Hidden = true; BuildOverlayPartInfo.Hidden = true;
isEditorLocked = true; isEditorLocked = true;
} }
else else
{ {
InputLockManager.SetControlLock(ControlTypes.None, "KER_BuildAdvanced"); InputLockManager.SetControlLock(ControlTypes.None, "KER_BuildAdvanced");
BuildOverlayPartInfo.Hidden = false; BuildOverlayPartInfo.Hidden = false;
isEditorLocked = false; isEditorLocked = false;
} }
} }
   
private void GetStageInfo() private void GetStageInfo()
{ {
stages = SimManager.Stages; stages = SimManager.Stages;
if (stages != null && stages.Length > 0) if (stages != null && stages.Length > 0)
{ {
maxMach = stages[stages.Length - 1].maxMach; 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()
{ {
windowStyle = new GUIStyle(HighLogic.Skin.window) windowStyle = new GUIStyle(HighLogic.Skin.window)
{ {
alignment = TextAnchor.UpperLeft alignment = TextAnchor.UpperLeft
}; };
   
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)
}; };
   
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)
}; };
   
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
}; };
   
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
}; };
   
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
}; };
   
settingStyle = new GUIStyle(titleStyle) settingStyle = new GUIStyle(titleStyle)
{ {
alignment = TextAnchor.MiddleLeft, alignment = TextAnchor.MiddleLeft,
stretchWidth = true, stretchWidth = true,
stretchHeight = true stretchHeight = true
}; };
   
settingAtmoStyle = new GUIStyle(titleStyle) settingAtmoStyle = new GUIStyle(titleStyle)
{ {
margin = new RectOffset(), margin = new RectOffset(),
padding = new RectOffset(), padding = new RectOffset(),
alignment = TextAnchor.UpperLeft alignment = TextAnchor.UpperLeft
}; };
   
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
}; };
   
bodiesButtonActiveStyle = new GUIStyle(bodiesButtonStyle) bodiesButtonActiveStyle = new GUIStyle(bodiesButtonStyle)
{ {
normal = bodiesButtonStyle.onNormal, normal = bodiesButtonStyle.onNormal,
hover = 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
{ {
SettingHandler handler = SettingHandler.Load("BuildAdvanced.xml"); SettingHandler handler = SettingHandler.Load("BuildAdvanced.xml");
handler.Get("visible", ref visible); handler.Get("visible", ref visible);
position.x = handler.Get("windowPositionX", position.x); position.x = handler.Get("windowPositionX", position.x);
position.y = handler.Get("windowPositionY", position.y); position.y = handler.Get("windowPositionY", position.y);
handler.Get("compactMode", ref compactMode); handler.Get("compactMode", ref compactMode);
handler.Get("compactCollapseRight", ref compactCollapseRight); handler.Get("compactCollapseRight", ref compactCollapseRight);
handler.Get("showAllStages", ref showAllStages); handler.Get("showAllStages", ref showAllStages);
handler.Get("showAtmosphericDetails", ref showAtmosphericDetails); handler.Get("showAtmosphericDetails", ref showAtmosphericDetails);
handler.Get("showSettings", ref 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()
{ {
InitialiseStyles(); InitialiseStyles();
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); 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(compactModeRect, compactMode, "COMPACT", buttonStyle) != compactMode) if (GUI.Toggle(compactModeRect, compactMode, "COMPACT", buttonStyle) != compactMode)
{ {
hasChanged = true; hasChanged = true;
compactCheck = 2; compactCheck = 2;
compactRight = position.xMax; compactRight = position.xMax;
compactMode = !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 (!compactMode) if (!compactMode)
{ {
if (GUI.Toggle(new Rect(position.width - 143.0f * GuiDisplaySize.Offset, 5.0f, 70.0f * GuiDisplaySize.Offset, 20.0f), showSettings, "SETTINGS", buttonStyle) != showSettings) if (GUI.Toggle(new Rect(position.width - 143.0f * GuiDisplaySize.Offset, 5.0f, 70.0f * GuiDisplaySize.Offset, 20.0f), showSettings, "SETTINGS", buttonStyle) != showSettings)
{ {
hasChanged = true; hasChanged = true;
showSettings = !showSettings; showSettings = !showSettings;
} }
   
if (GUI.Toggle(new Rect(position.width - 226.0f * GuiDisplaySize.Offset, 5.0f, 80.0f * GuiDisplaySize.Offset, 20.0f), showAllStages, "ALL STAGES", buttonStyle) != 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)
{ {
hasChanged = true; hasChanged = true;
showAllStages = !showAllStages; showAllStages = !showAllStages;
} }
   
if (GUI.Toggle(new Rect(position.width - 324.0f * GuiDisplaySize.Offset, 5.0f, 95.0f * GuiDisplaySize.Offset, 20.0f), showAtmosphericDetails, "ATMOSPHERIC", buttonStyle) != showAtmosphericDetails) if (GUI.Toggle(new Rect(position.width - 324.0f * GuiDisplaySize.Offset, 5.0f, 95.0f * GuiDisplaySize.Offset, 20.0f), showAtmosphericDetails, "ATMOSPHERIC", buttonStyle) != showAtmosphericDetails)
{ {
hasChanged = true; hasChanged = true;
showAtmosphericDetails = !showAtmosphericDetails; showAtmosphericDetails = !showAtmosphericDetails;
} }
   
bodiesListPosition = new Rect(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);
bodiesList.enabled = GUI.Toggle(bodiesListPosition, bodiesList.enabled, "BODY: " + CelestialBodies.SelectedBody.Name.ToUpper(), buttonStyle); bodiesList.enabled = GUI.Toggle(bodiesListPosition, bodiesList.enabled, "BODY: " + CelestialBodies.SelectedBody.Name.ToUpper(), buttonStyle);
bodiesList.SetPosition(bodiesListPosition.Translate(position)); bodiesList.SetPosition(bodiesListPosition.Translate(position));
} }
else else
{ {
if (GUI.Toggle(new Rect(position.width - 133.0f * GuiDisplaySize.Offset, 5.0f, 60.0f * GuiDisplaySize.Offset, 20.0f), showAtmosphericDetails, "ATMO", buttonStyle) != showAtmosphericDetails) 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; hasChanged = true;
showAtmosphericDetails = !showAtmosphericDetails; showAtmosphericDetails = !showAtmosphericDetails;
} }
} }
   
// Draw the main informational display box. // Draw the main informational display box.
if (!compactMode) if (!compactMode)
{ {
GUILayout.BeginHorizontal(areaStyle); GUILayout.BeginHorizontal(areaStyle);
DrawStageNumbers(); DrawStageNumbers();
DrawPartCount(); DrawPartCount();
DrawCost(); DrawCost();
DrawMass(); DrawMass();
DrawIsp(); DrawIsp();
DrawThrust(); DrawThrust();
DrawTorque(); DrawTorque();
DrawTwr(); DrawTwr();
DrawDeltaV(); DrawDeltaV();
DrawBurnTime(); DrawBurnTime();
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
if (showAtmosphericDetails && !compactMode) if (showAtmosphericDetails && !compactMode)
{ {
GUILayout.BeginVertical(areaSettingStyle); GUILayout.BeginVertical(areaSettingStyle);
DrawAtmosphericDetails(); DrawAtmosphericDetails();
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
if (showSettings) if (showSettings)
{ {
GUILayout.BeginVertical(areaSettingStyle); GUILayout.BeginVertical(areaSettingStyle);
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(areaStyle); GUILayout.BeginHorizontal(areaStyle);
DrawStageNumbers(); DrawStageNumbers();
DrawTwr(); DrawTwr();
DrawDeltaV(); DrawDeltaV();
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
   
GUI.DragWindow(); GUI.DragWindow();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex, "BuildAdvanced.Window()"); Logger.Exception(ex, "BuildAdvanced.Window()");
} }
} }
} }
} }
// //
// Copyright (C) 2015 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/>.
// //
   
namespace KerbalEngineer namespace KerbalEngineer
{ {
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
   
public static class EngineerGlobals public static class EngineerGlobals
{ {
/// <summary> /// <summary>
/// Current version of the Kerbal Engineer assembly. /// Current version of the Kerbal Engineer assembly.
/// </summary> /// </summary>
public const string ASSEMBLY_VERSION = "1.0.18.1"; public const string ASSEMBLY_VERSION = "1.0.19.2";
   
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;
   
/// <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 get
{ {
return assemblyFile ?? (assemblyFile = Assembly.GetExecutingAssembly().Location); 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 get
{ {
return assemblyName ?? (assemblyName = new FileInfo(AssemblyFile).Name); 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 get
{ {
return assemblyPath ?? (assemblyPath = AssemblyFile.Replace(new FileInfo(AssemblyFile).Name, "")); return assemblyPath ?? (assemblyPath = AssemblyFile.Replace(new FileInfo(AssemblyFile).Name, ""));
} }
} }
   
  /// <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) 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.ASSEMBLY_VERSION, 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
} }
} }
  namespace KerbalEngineer.Helpers
  {
  using System;
  using System.IO;
  using System.Text;
  using System.Xml.Serialization;
 
  public static class XmlHelper
  {
  /// <summary>
  /// Loads an object from disk.
  /// </summary>
  public static T LoadObject<T>(string path)
  {
  T obj = default(T);
 
  if (File.Exists(path))
  {
  try
  {
  using (StreamReader stream = new StreamReader(path, Encoding.UTF8))
  {
  obj = (T)new XmlSerializer(typeof(T)).Deserialize(stream);
  }
  }
  catch (Exception ex)
  {
  Logger.Exception(ex);
  }
  }
 
  return obj;
  }
 
  /// <summary>
  /// Loads and object from disk.
  /// </summary>
  public static bool LoadObject<T>(string path, out T obj)
  {
  obj = LoadObject<T>(path);
  return (obj != null);
  }
 
  /// <summary>
  /// Saves an object to disk.
  /// </summary>
  public static void SaveObject<T>(string path, T obj)
  {
  if (obj == null || string.IsNullOrEmpty(path))
  {
  return;
  }
 
  try
  {
  using (StreamWriter stream = new StreamWriter(path, false, Encoding.UTF8))
  {
  new XmlSerializer(typeof(T)).Serialize(stream, obj);
  }
  }
  catch (Exception ex)
  {
  Logger.Exception(ex);
  }
  }
  }
  }
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{39806613-E0B7-46E0-89A6-A569EC538CBB}</ProjectGuid> <ProjectGuid>{39806613-E0B7-46E0-89A6-A569EC538CBB}</ProjectGuid>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>KerbalEngineer</RootNamespace> <RootNamespace>KerbalEngineer</RootNamespace>
<AssemblyName>KerbalEngineer</AssemblyName> <AssemblyName>KerbalEngineer</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>false</DebugSymbols> <DebugSymbols>false</DebugSymbols>
<DebugType>none</DebugType> <DebugType>none</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>..\Output\KerbalEngineer\</OutputPath> <OutputPath>..\Output\KerbalEngineer\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<UseVSHostingProcess>false</UseVSHostingProcess> <UseVSHostingProcess>false</UseVSHostingProcess>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>none</DebugType> <DebugType>none</DebugType>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<OutputPath>..\Output\KerbalEngineer\</OutputPath> <OutputPath>..\Output\KerbalEngineer\</OutputPath>
<DefineConstants> <DefineConstants>
</DefineConstants> </DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<UseVSHostingProcess>false</UseVSHostingProcess> <UseVSHostingProcess>false</UseVSHostingProcess>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks> <AllowUnsafeBlocks>false</AllowUnsafeBlocks>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Control\IControlPanel.cs" /> <Compile Include="Control\IControlPanel.cs" />
<Compile Include="Control\Panels\BuildOverlayPanel.cs" /> <Compile Include="Control\Panels\BuildOverlayPanel.cs" />
<Compile Include="Control\Panels\BuildEngineerPanel.cs" /> <Compile Include="Control\Panels\BuildEngineerPanel.cs" />
<Compile Include="Editor\BuildAdvanced.cs" /> <Compile Include="Editor\BuildAdvanced.cs" />
<Compile Include="Editor\BuildOverlay.cs" /> <Compile Include="Editor\BuildOverlay.cs" />
<Compile Include="CelestialBodies.cs" /> <Compile Include="CelestialBodies.cs" />
<Compile Include="Editor\BuildOverlayPartInfo.cs" /> <Compile Include="Editor\BuildOverlayPartInfo.cs" />
<Compile Include="Editor\BuildOverlayResources.cs" /> <Compile Include="Editor\BuildOverlayResources.cs" />
<Compile Include="Editor\BuildOverlayVessel.cs" /> <Compile Include="Editor\BuildOverlayVessel.cs" />
<Compile Include="Editor\BuildToolbar.cs" /> <Compile Include="Editor\BuildToolbar.cs" />
<Compile Include="Editor\PartInfoItem.cs" /> <Compile Include="Editor\PartInfoItem.cs" />
<Compile Include="Editor\ResourceInfoItem.cs" /> <Compile Include="Editor\ResourceInfoItem.cs" />
<Compile Include="Extensions\FloatExtensions.cs" /> <Compile Include="Extensions\FloatExtensions.cs" />
<Compile Include="Extensions\OrbitExtensions.cs" /> <Compile Include="Extensions\OrbitExtensions.cs" />
<Compile Include="Extensions\StringExtensions.cs" /> <Compile Include="Extensions\StringExtensions.cs" />
<Compile Include="Flight\ActionMenuGui.cs" /> <Compile Include="Flight\ActionMenuGui.cs" />
<Compile Include="Flight\Presets\Preset.cs" /> <Compile Include="Flight\Presets\Preset.cs" />
<Compile Include="Flight\Readouts\Miscellaneous\SystemTime.cs" /> <Compile Include="Flight\Readouts\Miscellaneous\SystemTime.cs" />
<Compile Include="Flight\Readouts\Miscellaneous\VectoredThrustToggle.cs" /> <Compile Include="Flight\Readouts\Miscellaneous\VectoredThrustToggle.cs" />
<Compile Include="Flight\Readouts\Miscellaneous\Separator.cs" /> <Compile Include="Flight\Readouts\Miscellaneous\Separator.cs" />
<Compile Include="Flight\Readouts\Miscellaneous\GuiSizeAdjustor.cs" /> <Compile Include="Flight\Readouts\Miscellaneous\GuiSizeAdjustor.cs" />
<Compile Include="Flight\Readouts\Orbital\AngleToEquatorialDescendingNode.cs" /> <Compile Include="Flight\Readouts\Orbital\AngleToEquatorialDescendingNode.cs" />
<Compile Include="Flight\Readouts\Orbital\AngleToEquatorialAscendingNode.cs" /> <Compile Include="Flight\Readouts\Orbital\AngleToEquatorialAscendingNode.cs" />
<Compile Include="Flight\Readouts\Orbital\AngleToRetrograde.cs" /> <Compile Include="Flight\Readouts\Orbital\AngleToRetrograde.cs" />
<Compile Include="Flight\Readouts\Orbital\AngleToPrograde.cs" /> <Compile Include="Flight\Readouts\Orbital\AngleToPrograde.cs" />
<Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeRadialDeltaV.cs" /> <Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeRadialDeltaV.cs" />
<Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\ManoeuvreProcessor.cs" /> <Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\ManoeuvreProcessor.cs" />
<Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeTimeToHalfBurn.cs" /> <Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeTimeToHalfBurn.cs" />
<Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeTimeToManoeuvre.cs" /> <Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeTimeToManoeuvre.cs" />
<Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeHalfBurnTime.cs" /> <Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeHalfBurnTime.cs" />
<Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeBurnTime.cs" /> <Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeBurnTime.cs" />
<Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeAngleToRetrograde.cs" /> <Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeAngleToRetrograde.cs" />
<Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeNormalDeltaV.cs" /> <Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeNormalDeltaV.cs" />
<Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeAngleToPrograde.cs" /> <Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeAngleToPrograde.cs" />
<Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeTotalDeltaV.cs" /> <Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeTotalDeltaV.cs" />
<Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeProgradeDeltaV.cs" /> <Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\NodeProgradeDeltaV.cs" />
<Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\PostBurnApoapsis.cs" /> <Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\PostBurnApoapsis.cs" />
<Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\PostBurnPeriapsis.cs" /> <Compile Include="Flight\Readouts\Orbital\ManoeuvreNode\PostBurnPeriapsis.cs" />
<Compile Include="Flight\Readouts\Orbital\MeanAnomalyAtEpoc.cs" /> <Compile Include="Flight\Readouts\Orbital\MeanAnomalyAtEpoc.cs" />
<Compile Include="Flight\Readouts\Orbital\MeanAnomaly.cs" /> <Compile Include="Flight\Readouts\Orbital\MeanAnomaly.cs" />
<Compile Include="Flight\Readouts\Orbital\EccentricAnomaly.cs" /> <Compile Include="Flight\Readouts\Orbital\EccentricAnomaly.cs" />
<Compile Include="Flight\Readouts\Orbital\ArgumentOfPeriapsis.cs" /> <Compile Include="Flight\Readouts\Orbital\ArgumentOfPeriapsis.cs" />
<Compile Include="Flight\Readouts\Orbital\CurrentSoi.cs" /> <Compile Include="Flight\Readouts\Orbital\CurrentSoi.cs" />
<Compile Include="Flight\Readouts\Orbital\SemiMajorAxis.cs"> <Compile Include="Flight\Readouts\Orbital\SemiMajorAxis.cs">
<SubType>Code</SubType> <SubType>Code</SubType>
</Compile> </Compile>
<Compile Include="Flight\Readouts\Orbital\SpeedAtApoapsis.cs" /> <Compile Include="Flight\Readouts\Orbital\SpeedAtApoapsis.cs" />
<Compile Include="Flight\Readouts\Orbital\SpeedAtPeriapsis.cs"> <Compile Include="Flight\Readouts\Orbital\SpeedAtPeriapsis.cs">
<SubType>Code</SubType> <SubType>Code</SubType>
</Compile> </Compile>
<Compile Include="Flight\Readouts\Orbital\TimeToAtmosphere.cs" /> <Compile Include="Flight\Readouts\Orbital\TimeToAtmosphere.cs" />
<Compile Include="Flight\Readouts\Orbital\TrueAnomaly.cs" /> <Compile Include="Flight\Readouts\Orbital\TrueAnomaly.cs" />
<Compile Include="Flight\Readouts\Orbital\TimeToEquatorialAscendingNode.cs" /> <Compile Include="Flight\Readouts\Orbital\TimeToEquatorialAscendingNode.cs" />
<Compile Include="Flight\Readouts\Orbital\TimeToEquatorialDescendingNode.cs" /> <Compile Include="Flight\Readouts\Orbital\TimeToEquatorialDescendingNode.cs" />
<Compile Include="Flight\Readouts\Rendezvous\RelativeSpeed.cs" /> <Compile Include="Flight\Readouts\Rendezvous\RelativeSpeed.cs" />
<Compile Include="Flight\Readouts\Rendezvous\RelativeVelocity.cs" /> <Compile Include="Flight\Readouts\Rendezvous\RelativeVelocity.cs" />
<Compile Include="Flight\Readouts\Rendezvous\SemiMinorAxis.cs" /> <Compile Include="Flight\Readouts\Rendezvous\SemiMinorAxis.cs" />
<Compile Include="Flight\Readouts\Rendezvous\SemiMajorAxis.cs" /> <Compile Include="Flight\Readouts\Rendezvous\SemiMajorAxis.cs" />
<Compile Include="Flight\Readouts\Rendezvous\TimeToRelativeDescendingNode.cs" /> <Compile Include="Flight\Readouts\Rendezvous\TimeToRelativeDescendingNode.cs" />
<Compile Include="Flight\Readouts\Rendezvous\TimeToRelativeAscendingNode.cs" /> <Compile Include="Flight\Readouts\Rendezvous\TimeToRelativeAscendingNode.cs" />
<Compile Include="Flight\Readouts\Surface\ImpactBiome.cs" /> <Compile Include="Flight\Readouts\Surface\ImpactBiome.cs" />
<Compile Include="Flight\Readouts\Surface\Slope.cs" /> <Compile Include="Flight\Readouts\Surface\Slope.cs" />
<Compile Include="Flight\Readouts\Surface\Biome.cs" /> <Compile Include="Flight\Readouts\Surface\Biome.cs" />
<Compile Include="Flight\Readouts\Surface\HorizontalAcceleration.cs" /> <Compile Include="Flight\Readouts\Surface\HorizontalAcceleration.cs" />
<Compile Include="Flight\Readouts\Surface\VerticalAcceleration.cs" /> <Compile Include="Flight\Readouts\Surface\VerticalAcceleration.cs" />
<Compile Include="Flight\Readouts\Surface\MachNumber.cs" /> <Compile Include="Flight\Readouts\Surface\MachNumber.cs" />
<Compile Include="Flight\Readouts\Thermal\CoolestSkinTemperature.cs" /> <Compile Include="Flight\Readouts\Thermal\CoolestSkinTemperature.cs" />
<Compile Include="Flight\Readouts\Thermal\CriticalPart.cs" /> <Compile Include="Flight\Readouts\Thermal\CriticalPart.cs" />
<Compile Include="Flight\Readouts\Thermal\CoolestPart.cs" /> <Compile Include="Flight\Readouts\Thermal\CoolestPart.cs" />
<Compile Include="Flight\Readouts\Thermal\CoolestTemperature.cs" /> <Compile Include="Flight\Readouts\Thermal\CoolestTemperature.cs" />
<Compile Include="Flight\Readouts\Thermal\CriticalThermalPercentage.cs" /> <Compile Include="Flight\Readouts\Thermal\CriticalThermalPercentage.cs" />
<Compile Include="Flight\Readouts\Thermal\CriticalSkinTemperature.cs" /> <Compile Include="Flight\Readouts\Thermal\CriticalSkinTemperature.cs" />
<Compile Include="Flight\Readouts\Thermal\CriticalTemperature.cs" /> <Compile Include="Flight\Readouts\Thermal\CriticalTemperature.cs" />
<Compile Include="Flight\Readouts\Thermal\HottestSkinTemperature.cs" /> <Compile Include="Flight\Readouts\Thermal\HottestSkinTemperature.cs" />
<Compile Include="Flight\Readouts\Thermal\InternalFlux.cs" /> <Compile Include="Flight\Readouts\Thermal\InternalFlux.cs" />
<Compile Include="Flight\Readouts\Thermal\RadiationFlux.cs" /> <Compile Include="Flight\Readouts\Thermal\RadiationFlux.cs" />
<Compile Include="Flight\Readouts\Thermal\ConvectionFlux.cs" /> <Compile Include="Flight\Readouts\Thermal\ConvectionFlux.cs" />
<Compile Include="Flight\Readouts\Thermal\HottestTemperature.cs" /> <Compile Include="Flight\Readouts\Thermal\HottestTemperature.cs" />
<Compile Include="Flight\Readouts\Thermal\HottestPart.cs" /> <Compile Include="Flight\Readouts\Thermal\HottestPart.cs" />
<Compile Include="Flight\Readouts\Thermal\ThermalProcessor.cs" /> <Compile Include="Flight\Readouts\Thermal\ThermalProcessor.cs" />
<Compile Include="Flight\Readouts\Vessel\Name.cs" /> <Compile Include="Flight\Readouts\Vessel\Name.cs" />
<Compile Include="Flight\Readouts\Vessel\AttitudeProcessor.cs" /> <Compile Include="Flight\Readouts\Vessel\AttitudeProcessor.cs" />
<Compile Include="Flight\Readouts\Vessel\DeltaVCurrentTotal.cs" /> <Compile Include="Flight\Readouts\Vessel\DeltaVCurrentTotal.cs" />
<Compile Include="Flight\Readouts\Vessel\PitchRate.cs" /> <Compile Include="Flight\Readouts\Vessel\PitchRate.cs" />
<Compile Include="Flight\Readouts\Vessel\HeadingRate.cs" /> <Compile Include="Flight\Readouts\Vessel\HeadingRate.cs" />
<Compile Include="Flight\Readouts\Vessel\RollRate.cs" /> <Compile Include="Flight\Readouts\Vessel\RollRate.cs" />
<Compile Include="Flight\Readouts\Vessel\Roll.cs" /> <Compile Include="Flight\Readouts\Vessel\Roll.cs" />
<Compile Include="Flight\Readouts\Vessel\Pitch.cs" /> <Compile Include="Flight\Readouts\Vessel\Pitch.cs" />
<Compile Include="Flight\Readouts\Vessel\Heading.cs" /> <Compile Include="Flight\Readouts\Vessel\Heading.cs" />
<Compile Include="Flight\Readouts\Vessel\PartCount.cs" /> <Compile Include="Flight\Readouts\Vessel\PartCount.cs" />
<Compile Include="Flight\Readouts\Vessel\SuicideBurnDeltaV.cs" /> <Compile Include="Flight\Readouts\Vessel\SuicideBurnDeltaV.cs" />
<Compile Include="Flight\Readouts\Vessel\SuicideBurnAltitude.cs" /> <Compile Include="Flight\Readouts\Vessel\SuicideBurnAltitude.cs" />
<Compile Include="Flight\Readouts\Vessel\SuicideBurnDistance.cs" /> <Compile Include="Flight\Readouts\Vessel\SuicideBurnDistance.cs" />
<Compile Include="Flight\Readouts\Vessel\DeltaVCurrent.cs" /> <Compile Include="Flight\Readouts\Vessel\DeltaVCurrent.cs" />
<Compile Include="Flight\Readouts\Vessel\IntakeAirUsage.cs" /> <Compile Include="Flight\Readouts\Vessel\IntakeAirUsage.cs" />
<Compile Include="Flight\Readouts\Vessel\IntakeAirDemandSupply.cs" /> <Compile Include="Flight\Readouts\Vessel\IntakeAirDemandSupply.cs" />
<Compile Include="Flight\Readouts\Vessel\IntakeAirSupply.cs" /> <Compile Include="Flight\Readouts\Vessel\IntakeAirSupply.cs" />
<Compile Include="Flight\Readouts\Vessel\IntakeAirDemand.cs" /> <Compile Include="Flight\Readouts\Vessel\IntakeAirDemand.cs" />
<Compile Include="Flight\Readouts\Miscellaneous\SimulationDelay.cs" /> <Compile Include="Flight\Readouts\Miscellaneous\SimulationDelay.cs" />
<Compile Include="Flight\Readouts\Vessel\SimulationProcessor.cs" /> <Compile Include="Flight\Readouts\Vessel\SimulationProcessor.cs" />
<Compile Include="Flight\Readouts\Vessel\Acceleration.cs" /> <Compile Include="Flight\Readouts\Vessel\Acceleration.cs" />
<Compile Include="Flight\Presets\PresetLibrary.cs" /> <Compile Include="Flight\Presets\PresetLibrary.cs" />
<Compile Include="Flight\Readouts\Vessel\SuicideBurnProcessor.cs" /> <Compile Include="Flight\Readouts\Vessel\SuicideBurnProcessor.cs" />
<Compile Include="Flight\Readouts\Vessel\SurfaceThrustToWeight.cs" /> <Compile Include="Flight\Readouts\Vessel\SurfaceThrustToWeight.cs" />
<Compile Include="Flight\Readouts\Surface\Situation.cs" /> <Compile Include="Flight\Readouts\Surface\Situation.cs" />
<Compile Include="Flight\Readouts\Vessel\ThrustOffsetAngle.cs" /> <Compile Include="Flight\Readouts\Vessel\ThrustOffsetAngle.cs" />
<Compile Include="Flight\Readouts\Vessel\ThrustTorque.cs" /> <Compile Include="Flight\Readouts\Vessel\ThrustTorque.cs" />
<Compile Include="GuiDisplaySize.cs" /> <Compile Include="GuiDisplaySize.cs" />
<Compile Include="Helpers\AngleHelper.cs" /> <Compile Include="Helpers\AngleHelper.cs" />
<Compile Include="Helpers\Averager.cs" /> <Compile Include="Helpers\Averager.cs" />
<Compile Include="Helpers\ForceAccumulator.cs" /> <Compile Include="Helpers\ForceAccumulator.cs" />
<Compile Include="Helpers\TextureHelper.cs" /> <Compile Include="Helpers\TextureHelper.cs" />
<Compile Include="Helpers\Units.cs" /> <Compile Include="Helpers\Units.cs" />
<Compile Include="Helpers\TimeFormatter.cs" /> <Compile Include="Helpers\TimeFormatter.cs" />
<Compile Include="KeyBinder.cs" /> <Compile Include="Helpers\XmlHelper.cs" />
  <Compile Include="KeyBinding\KeyBinder.cs" />
<Compile Include="Control\ControlCentre.cs" /> <Compile Include="Control\ControlCentre.cs" />
  <Compile Include="KeyBinding\KeyBindingsObject.cs" />
<Compile Include="UIControls\DropDown.cs" /> <Compile Include="UIControls\DropDown.cs" />
<Compile Include="Logger.cs" /> <Compile Include="Logger.cs" />
<Compile Include="EngineerGlobals.cs" /> <Compile Include="EngineerGlobals.cs" />
<Compile Include="Extensions\DoubleExtensions.cs" /> <Compile Include="Extensions\DoubleExtensions.cs" />
<Compile Include="Extensions\PartExtensions.cs" /> <Compile Include="Extensions\PartExtensions.cs" />
<Compile Include="Extensions\PartResourceExtensions.cs" /> <Compile Include="Extensions\PartResourceExtensions.cs" />
<Compile Include="Extensions\RectExtensions.cs" /> <Compile Include="Extensions\RectExtensions.cs" />
<Compile Include="Flight\ActionMenu.cs" /> <Compile Include="Flight\ActionMenu.cs" />
<Compile Include="Flight\DisplayStack.cs" /> <Compile Include="Flight\DisplayStack.cs" />
<Compile Include="Flight\FlightEngineerCore.cs" /> <Compile Include="Flight\FlightEngineerCore.cs" />
<Compile Include="Flight\FlightEngineerModule.cs" /> <Compile Include="Flight\FlightEngineerModule.cs" />
<Compile Include="Flight\IUpdatable.cs" /> <Compile Include="Flight\IUpdatable.cs" />
<Compile Include="Flight\IUpdateRequest.cs" /> <Compile Include="Flight\IUpdateRequest.cs" />
<Compile Include="Flight\Readouts\Orbital\ApoapsisHeight.cs" /> <Compile Include="Flight\Readouts\Orbital\ApoapsisHeight.cs" />
<Compile Include="Flight\Readouts\Orbital\Eccentricity.cs" /> <Compile Include="Flight\Readouts\Orbital\Eccentricity.cs" />
<Compile Include="Flight\Readouts\Orbital\Inclination.cs" /> <Compile Include="Flight\Readouts\Orbital\Inclination.cs" />
<Compile Include="Flight\Readouts\Orbital\LongitudeOfAscendingNode.cs" /> <Compile Include="Flight\Readouts\Orbital\LongitudeOfAscendingNode.cs" />
<Compile Include="Flight\Readouts\Orbital\LongitudeOfPeriapsis.cs" /> <Compile Include="Flight\Readouts\Orbital\LongitudeOfPeriapsis.cs" />
<Compile Include="Flight\Readouts\Orbital\OrbitalPeriod.cs" /> <Compile Include="Flight\Readouts\Orbital\OrbitalPeriod.cs" />
<Compile Include="Flight\Readouts\Orbital\OrbitalSpeed.cs" /> <Compile Include="Flight\Readouts\Orbital\OrbitalSpeed.cs" />
<Compile Include="Flight\Readouts\Orbital\PeriapsisHeight.cs" /> <Compile Include="Flight\Readouts\Orbital\PeriapsisHeight.cs" />
<Compile Include="Flight\Readouts\Orbital\SemiMinorAxis.cs" /> <Compile Include="Flight\Readouts\Orbital\SemiMinorAxis.cs" />
<Compile Include="Flight\Readouts\Orbital\TimeToApoapsis.cs" /> <Compile Include="Flight\Readouts\Orbital\TimeToApoapsis.cs" />
<Compile Include="Flight\Readouts\Orbital\TimeToPeriapsis.cs" /> <Compile Include="Flight\Readouts\Orbital\TimeToPeriapsis.cs" />
<Compile Include="Flight\Readouts\ReadoutCategory.cs" /> <Compile Include="Flight\Readouts\ReadoutCategory.cs" />
<Compile Include="Flight\Readouts\ReadoutLibrary.cs" /> <Compile Include="Flight\Readouts\ReadoutLibrary.cs" />
<Compile Include="Flight\Readouts\ReadoutModule.cs" /> <Compile Include="Flight\Readouts\ReadoutModule.cs" />
<Compile Include="Flight\Readouts\Rendezvous\TimeToPeriapsis.cs" /> <Compile Include="Flight\Readouts\Rendezvous\TimeToPeriapsis.cs" />
<Compile Include="Flight\Readouts\Rendezvous\TimeToApoapsis.cs" /> <Compile Include="Flight\Readouts\Rendezvous\TimeToApoapsis.cs" />
<Compile Include="Flight\Readouts\Rendezvous\PeriapsisHeight.cs" /> <Compile Include="Flight\Readouts\Rendezvous\PeriapsisHeight.cs" />
<Compile Include="Flight\Readouts\Rendezvous\ApoapsisHeight.cs" /> <Compile Include="Flight\Readouts\Rendezvous\ApoapsisHeight.cs" />
<Compile Include="Flight\Readouts\Rendezvous\InterceptAngle.cs" /> <Compile Include="Flight\Readouts\Rendezvous\InterceptAngle.cs" />
<Compile Include="Flight\Readouts\Rendezvous\OrbitalPeriod.cs" /> <Compile Include="Flight\Readouts\Rendezvous\OrbitalPeriod.cs" />
<Compile Include="Flight\Readouts\Rendezvous\Distance.cs" /> <Compile Include="Flight\Readouts\Rendezvous\Distance.cs" />
<Compile Include="Flight\Readouts\Rendezvous\AltitudeSeaLevel.cs" /> <Compile Include="Flight\Readouts\Rendezvous\AltitudeSeaLevel.cs" />
<Compile Include="Flight\Readouts\Rendezvous\AngleToRelativeDescendingNode.cs" /> <Compile Include="Flight\Readouts\Rendezvous\AngleToRelativeDescendingNode.cs" />
<Compile Include="Flight\Readouts\Rendezvous\AngleToRelativeAscendingNode.cs" /> <Compile Include="Flight\Readouts\Rendezvous\AngleToRelativeAscendingNode.cs" />
<Compile Include="Flight\Readouts\Rendezvous\PhaseAngle.cs" /> <Compile Include="Flight\Readouts\Rendezvous\PhaseAngle.cs" />
<Compile Include="Flight\Readouts\Rendezvous\RelativeInclination.cs" /> <Compile Include="Flight\Readouts\Rendezvous\RelativeInclination.cs" />
<Compile Include="Flight\Readouts\Rendezvous\RendezvousProcessor.cs" /> <Compile Include="Flight\Readouts\Rendezvous\RendezvousProcessor.cs" />
<Compile Include="Flight\Readouts\Rendezvous\TargetSelector.cs" /> <Compile Include="Flight\Readouts\Rendezvous\TargetSelector.cs" />
<Compile Include="Flight\Readouts\Surface\AltitudeSeaLevel.cs" /> <Compile Include="Flight\Readouts\Surface\AltitudeSeaLevel.cs" />
<Compile Include="Flight\Readouts\Surface\AltitudeTerrain.cs" /> <Compile Include="Flight\Readouts\Surface\AltitudeTerrain.cs" />
<Compile Include="Flight\Readouts\Surface\ImpactLatitude.cs" /> <Compile Include="Flight\Readouts\Surface\ImpactLatitude.cs" />
<Compile Include="Flight\Readouts\Surface\ImpactAltitude.cs" /> <Compile Include="Flight\Readouts\Surface\ImpactAltitude.cs" />
<Compile Include="Flight\Readouts\Surface\ImpactLongitude.cs" /> <Compile Include="Flight\Readouts\Surface\ImpactLongitude.cs" />
<Compile Include="Flight\Readouts\Surface\ImpactTime.cs" /> <Compile Include="Flight\Readouts\Surface\ImpactTime.cs" />
<Compile Include="Flight\Readouts\Surface\AtmosphericProcessor.cs" /> <Compile Include="Flight\Readouts\Surface\AtmosphericProcessor.cs" />
<Compile Include="Flight\Readouts\Surface\AtmosphericEfficiency.cs" /> <Compile Include="Flight\Readouts\Surface\AtmosphericEfficiency.cs" />
<Compile Include="Flight\Readouts\Surface\GeeForce.cs" /> <Compile Include="Flight\Readouts\Surface\GeeForce.cs" />
<Compile Include="Flight\Readouts\Surface\HorizontalSpeed.cs" /> <Compile Include="Flight\Readouts\Surface\HorizontalSpeed.cs" />
<Compile Include="Flight\Readouts\Surface\ImpactProcessor.cs" /> <Compile Include="Flight\Readouts\Surface\ImpactProcessor.cs" />
<Compile Include="Flight\Readouts\Surface\Latitude.cs" /> <Compile Include="Flight\Readouts\Surface\Latitude.cs" />
<Compile Include="Flight\Readouts\Surface\Longitude.cs" /> <Compile Include="Flight\Readouts\Surface\Longitude.cs" />
<Compile Include="Flight\Readouts\Surface\TerminalVelocity.cs" /> <Compile Include="Flight\Readouts\Surface\TerminalVelocity.cs" />
<Compile Include="Flight\Readouts\Surface\VerticalSpeed.cs" /> <Compile Include="Flight\Readouts\Surface\VerticalSpeed.cs" />
<Compile Include="Flight\Readouts\Vessel\DeltaVStaged.cs" /> <Compile Include="Flight\Readouts\Vessel\DeltaVStaged.cs" />
<Compile Include="Flight\Readouts\Vessel\DeltaVTotal.cs" /> <Compile Include="Flight\Readouts\Vessel\DeltaVTotal.cs" />
<Compile Include="Flight\Readouts\Vessel\Mass.cs" /> <Compile Include="Flight\Readouts\Vessel\Mass.cs" />
<Compile Include="Flight\Readouts\Vessel\Thrust.cs" /> <Compile Include="Flight\Readouts\Vessel\Thrust.cs" />
<Compile Include="Flight\Readouts\Vessel\SpecificImpulse.cs" /> <Compile Include="Flight\Readouts\Vessel\SpecificImpulse.cs" />
<Compile Include="Flight\Readouts\Vessel\ThrustToWeight.cs" /> <Compile Include="Flight\Readouts\Vessel\ThrustToWeight.cs" />
<Compile Include="Flight\Sections\SectionEditor.cs" /> <Compile Include="Flight\Sections\SectionEditor.cs" />
<Compile Include="Flight\Sections\SectionLibrary.cs" /> <Compile Include="Flight\Sections\SectionLibrary.cs" />
<Compile Include="Flight\Sections\SectionModule.cs" /> <Compile Include="Flight\Sections\SectionModule.cs" />
<Compile Include="Flight\Sections\SectionWindow.cs" /> <Compile Include="Flight\Sections\SectionWindow.cs" />
<Compile Include="LogMsg.cs" /> <Compile Include="LogMsg.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Settings\SettingHandler.cs" /> <Compile Include="Settings\SettingHandler.cs" />
<Compile Include="Settings\SettingItem.cs" /> <Compile Include="Settings\SettingItem.cs" />
<Compile Include="TapeDriveAnimator.cs" /> <Compile Include="TapeDriveAnimator.cs" />
<Compile Include="UIControls\SelectKeyBindPopup.cs" /> <Compile Include="KeyBinding\KeyBindPopup.cs" />
<Compile Include="UIControls\WindowObject.cs" /> <Compile Include="UIControls\WindowObject.cs" />
<Compile Include="VesselSimulator\AttachNodeSim.cs" /> <Compile Include="VesselSimulator\AttachNodeSim.cs" />
<Compile Include="VesselSimulator\EngineSim.cs" /> <Compile Include="VesselSimulator\EngineSim.cs" />
<Compile Include="Helpers\Pool.cs" /> <Compile Include="Helpers\Pool.cs" />
<Compile Include="VesselSimulator\PartSim.cs" /> <Compile Include="VesselSimulator\PartSim.cs" />
<Compile Include="VesselSimulator\ResourceContainer.cs" /> <Compile Include="VesselSimulator\ResourceContainer.cs" />
<Compile Include="VesselSimulator\SimManager.cs" /> <Compile Include="VesselSimulator\SimManager.cs" />
<Compile Include="VesselSimulator\Simulation.cs" /> <Compile Include="VesselSimulator\Simulation.cs" />
<Compile Include="VesselSimulator\Stage.cs" /> <Compile Include="VesselSimulator\Stage.cs" />
<Compile Include="Flight\Readouts\Rendezvous\RelativeRadialVelocity.cs" /> <Compile Include="Flight\Readouts\Rendezvous\RelativeRadialVelocity.cs" />
<Compile Include="Flight\Readouts\Rendezvous\TimeToRendezvous.cs" /> <Compile Include="Flight\Readouts\Rendezvous\TimeToRendezvous.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Assembly-CSharp"> <Reference Include="Assembly-CSharp">
<HintPath>..\Game\KSP_Data\Managed\Assembly-CSharp.dll</HintPath> <HintPath>..\..\Game\KSP_Data\Managed\Assembly-CSharp.dll</HintPath>
<Private>False</Private> <Private>False</Private>
</Reference> </Reference>
<Reference Include="System"> <Reference Include="System">
<HintPath>..\Game\KSP_Data\Managed\System.dll</HintPath> <HintPath>..\Game\KSP_Data\Managed\System.dll</HintPath>
<Private>False</Private> <Private>False</Private>
</Reference> </Reference>
<Reference Include="System.Xml"> <Reference Include="System.Xml">
<HintPath>..\Game\KSP_Data\Managed\System.Xml.dll</HintPath> <HintPath>..\Game\KSP_Data\Managed\System.Xml.dll</HintPath>
<Private>False</Private> <Private>False</Private>
</Reference> </Reference>
<Reference Include="UnityEngine"> <Reference Include="UnityEngine">
<HintPath>..\Game\KSP_Data\Managed\UnityEngine.dll</HintPath> <HintPath>..\..\Game\KSP_Data\Managed\UnityEngine.dll</HintPath>
<Private>False</Private> <Private>False</Private>
</Reference> </Reference>
</ItemGroup> </ItemGroup>
<ItemGroup /> <ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="PostBuildMacros"> <Target Name="PostBuildMacros">
<GetAssemblyIdentity AssemblyFiles="$(TargetPath)"> <GetAssemblyIdentity AssemblyFiles="$(TargetPath)">
<Output TaskParameter="Assemblies" ItemName="Targets" /> <Output TaskParameter="Assemblies" ItemName="Targets" />
</GetAssemblyIdentity> </GetAssemblyIdentity>
<ItemGroup> <ItemGroup>
<VersionNumber Include="@(Targets->'%(Version)')" /> <VersionNumber Include="@(Targets->'%(Version)')" />
</ItemGroup> </ItemGroup>
</Target> </Target>
<PropertyGroup> <PropertyGroup>
<PostBuildEventDependsOn> <PostBuildEventDependsOn>
$(PostBuildEventDependsOn); $(PostBuildEventDependsOn);
PostBuildMacros; PostBuildMacros;
</PostBuildEventDependsOn> </PostBuildEventDependsOn>
<PostBuildEvent>xcopy "$(SolutionDir)Output\*" "$(SolutionDir)Game\GameData\*" /E /Y <PostBuildEvent>xcopy "$(SolutionDir)Output\*" "$(SolutionDir)..\Game\GameData\*" /E /Y
del "$(SolutionDir)Release\*" /Q del "$(SolutionDir)Release\*" /Q
xcopy "$(SolutionDir)Documents\*" "$(SolutionDir)Release\Documents\*" /E /Y xcopy "$(SolutionDir)Documents\*" "$(SolutionDir)Release\Documents\*" /E /Y
7z.exe a -tzip -mx3 "$(SolutionDir)Release\$(ProjectName)-@(VersionNumber).zip" "$(SolutionDir)Output\*" 7z.exe a -tzip -mx3 "$(SolutionDir)Release\$(ProjectName)-@(VersionNumber).zip" "$(SolutionDir)Output\*"
7z.exe a -tzip -mx3 "$(SolutionDir)Release\$(ProjectName)-@(VersionNumber).zip" "$(SolutionDir)Documents\*"</PostBuildEvent> 7z.exe a -tzip -mx3 "$(SolutionDir)Release\$(ProjectName)-@(VersionNumber).zip" "$(SolutionDir)Documents\*"</PostBuildEvent>
</PropertyGroup> </PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets. Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild"> <Target Name="BeforeBuild">
</Target> </Target>
<Target Name="AfterBuild"> <Target Name="AfterBuild">
</Target> </Target>
--> -->
</Project> </Project>
//  
// 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/>.  
//  
 
using UnityEngine;  
 
namespace KerbalEngineer  
{  
public class KeyBinder  
{  
public static KeyCode EditorShowHide { get; set; }  
 
public static KeyCode FlightShowHide { get; set; }  
 
static KeyBinder()  
{  
EditorShowHide = FlightShowHide = KeyCode.Backslash;  
}  
}  
}  
  //
  // 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.KeyBinding
  {
  using System;
  using Extensions;
  using UnityEngine;
 
  public class KeyBindPopup : MonoBehaviour
  {
  private const string LOCK_ID = "KER_KeyBindPopup";
  private static Rect position = new Rect(Screen.width, Screen.height, 250.0f, 0.0f);
  private static bool hasCentred;
  private static KeyBindPopup instance;
  private readonly Array availableBindings = Enum.GetValues(typeof(KeyCode));
 
  /// <summary>
  /// Gets the delegate to be invoked when accepted button is clicked.
  /// </summary>
  public Action<KeyCode> AcceptClicked { get; private set; }
 
  /// <summary>
  /// Gets the name of the binding to change.
  /// </summary>
  public string Name { get; private set; }
 
  /// <summary>
  /// Gets the selected binding.
  /// </summary>
  public KeyCode Binding { get; private set; }
 
  /// <summary>
  /// Gets whether a key bind popup is already open.
  /// </summary>
  public static bool IsOpen
  {
  get
  {
  return (instance != null);
  }
  }
 
  /// <summary>
  /// Gets and sets the input lock state.
  /// </summary>
  public bool InputLock
  {
  get
  {
  return InputLockManager.GetControlLock(LOCK_ID) != ControlTypes.None;
  }
  set
  {
  if (value)
  {
  InputLockManager.SetControlLock(ControlTypes.All, LOCK_ID);
  }
  else
  {
  InputLockManager.SetControlLock(ControlTypes.None, LOCK_ID);
  }
  }
  }
 
  /// <summary>
  /// Shows a key bind popup allowing the user to select a key for binding.
  /// </summary>
  public static void Show(string name, KeyCode currentBinding, Action<KeyCode> acceptClicked)
  {
  if (instance == null)
  {
  instance = new GameObject("SelectKeyBind").AddComponent<KeyBindPopup>();
  }
 
  instance.Name = name;
  instance.Binding = currentBinding;
  instance.AcceptClicked = acceptClicked;
  }
 
  /// <summary>
  /// Handles the accept button click event.
  /// </summary>
  public void OnAccept()
  {
  if (AcceptClicked != null)
  {
  AcceptClicked.Invoke(Binding);
  }
  Destroy(gameObject);
  }
 
  /// <summary>
  /// Handles the cancel button click event.
  /// </summary>
  public void OnCancel()
  {
  Destroy(gameObject);
  }
 
  /// <summary>
  /// Called by unity when the component is created.
  /// </summary>
  protected virtual void Awake()
  {
  if (instance == null)
  {
  instance = this;
  }
  else if (instance != this)
  {
  OnCancel();
  }
  }
 
  /// <summary>
  /// Called by unity when the component is destroyed.
  /// </summary>
  protected virtual void OnDestroy()
  {
  InputLock = false;
  }
 
  /// <summary>
  /// Called by unity each frame to render the GUI.
  /// </summary>
  protected virtual void OnGUI()
  {
  position = GUILayout.Window(GetInstanceID(), position, RenderWindow, "Select Key Bind", HighLogic.Skin.window).ClampToScreen();
  CentreWindow();
  }
 
  /// <summary>
  /// Called by unity every frame.
  /// </summary>
  protected virtual void Update()
  {
  CentreWindow();
  UpdateBinding();
  UpdateInputLock();
  }
 
  /// <summary>
  /// Centres the window on the screen.
  /// </summary>
  private static void CentreWindow()
  {
  if (hasCentred == false && position.width > 0.0f && position.height > 0.0f)
  {
  hasCentred = true;
  position.center = new Vector2(Screen.width * 0.5f, Screen.height * 0.5f);
  }
  }
 
  /// <summary>
  /// Renders the window content.
  /// </summary>
  private void RenderWindow(int id)
  {
  GUILayout.Label("Press the desired key to change it.");
 
  // Binding labels.
  GUILayout.BeginVertical(HighLogic.Skin.textArea);
  GUILayout.Label("Key Bind: " + Name);
  GUILayout.Label("Selected: " + Binding);
  GUILayout.EndVertical();
 
  // Window buttons.
  GUILayout.BeginHorizontal();
  if (GUILayout.Button("Cancel", HighLogic.Skin.button))
  {
  OnCancel();
  }
 
  if (GUILayout.Button("Accept", HighLogic.Skin.button))
  {
  OnAccept();
  }
  GUILayout.EndHorizontal();
 
  // Make the window to be draggable.
  GUI.DragWindow();
  }
 
  /// <summary>
  /// Updates the binding selected by the user.
  /// </summary>
  private void UpdateBinding()
  {
  for (int i = 0; i < availableBindings.Length; ++i)
  {
  KeyCode keyCode = (KeyCode)availableBindings.GetValue(i);
 
  if (keyCode == KeyCode.Mouse0)
  {
  continue;
  }
 
  if (Input.GetKeyDown(keyCode))
  {
  if (Input.GetKeyDown(keyCode))
  {
  Binding = keyCode;
  }
  }
  }
  }
 
  /// <summary>
  /// Updates the input lock.
  /// </summary>
  private void UpdateInputLock()
  {
  bool mouseOver = position.MouseIsOver();
  bool inputLock = InputLock;
 
  if (mouseOver && inputLock == false)
  {
  InputLock = true;
  }
  else if (mouseOver == false && inputLock)
  {
  InputLock = false;
  }
  }
  }
  }
  //
  // 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.KeyBinding
  {
  using System;
  using System.IO;
  using Extensions;
  using Helpers;
  using UnityEngine;
 
  public class KeyBinder : MonoBehaviour
  {
  private const string LOCK_ID = "KER_KeyBinder";
  private static readonly string filePath = Path.Combine(EngineerGlobals.SettingsPath, "KeyBinds.xml");
  private static KeyBindingsObject bindings;
  private static Rect position = new Rect(Screen.width, Screen.height, 500.0f, 0.0f);
  private static bool hasCentred;
 
  static KeyBinder()
  {
  Load();
  }
 
  /// <summary>
  /// Gets whether the key binder window is open.
  /// </summary>
  public static bool IsOpen { get; private set; }
 
  /// <summary>
  /// Gets and sets the key bindings object.
  /// </summary>
  public static KeyBindingsObject Bindings
  {
  get
  {
  if (bindings == null)
  {
  bindings = new KeyBindingsObject();
  }
  return bindings;
  }
  private set
  {
  if (value != null)
  {
  bindings = value;
  }
  }
  }
 
  /// <summary>
  /// Gets and sets the editor show/hide binding.
  /// </summary>
  public static KeyCode EditorShowHide
  {
  get
  {
  return Bindings.EditorShowHide;
  }
  set
  {
  Bindings.EditorShowHide = value;
  Save();
  }
  }
 
  /// <summary>
  /// Gets and sets the flight show/hide binding.
  /// </summary>
  public static KeyCode FlightShowHide
  {
  get
  {
  return Bindings.FlightShowHide;
  }
  set
  {
  Bindings.FlightShowHide = value;
  Save();
  }
  }
 
  /// <summary>
  /// Gets and sets the input lock state.
  /// </summary>
  public bool InputLock
  {
  get
  {
  return InputLockManager.GetControlLock(LOCK_ID) != ControlTypes.None;
  }
  set
  {
  if (value)
  {
  InputLockManager.SetControlLock(ControlTypes.All, LOCK_ID);
  }
  else
  {
  InputLockManager.SetControlLock(ControlTypes.None, LOCK_ID);
  }
  }
  }
 
  /// <summary>
  /// Loads the key bindings from disk.
  /// </summary>
  public static void Load()
  {
  Bindings = XmlHelper.LoadObject<KeyBindingsObject>(filePath);
  }
 
  /// <summary>
  /// Saves the key bindings to disk.
  /// </summary>
  public static void Save()
  {
  XmlHelper.SaveObject(filePath, Bindings);
  }
 
  /// <summary>
  /// Shows the key binding window.
  /// </summary>
  public static void Show()
  {
  if (IsOpen)
  {
  return;
  }
 
  new GameObject("KeyBinder").AddComponent<KeyBinder>();
  }
 
  /// <summary>
  /// Called by unity when component is created.
  /// </summary>
  protected virtual void Awake()
  {
  if (IsOpen)
  {
  Destroy(gameObject);
  }
  else
  {
  IsOpen = true;
  position.height = 0.0f;
  }
  }
 
  /// <summary>
  /// Called by unity when component is destroyed.
  /// </summary>
  protected virtual void OnDestroy()
  {
  IsOpen = false;
  InputLock = false;
  }
 
  /// <summary>
  /// Called by unity to draw the GUI.
  /// </summary>
  protected virtual void OnGUI()
  {
  position = GUILayout.Window(GetInstanceID(), position, RenderWindow, "Kerbal Engineer Redux - Key Bindings", HighLogic.Skin.window).ClampToScreen();
  CentreWindow();
  }
 
  /// <summary>
  /// Called by unity every frame.
  /// </summary>
  protected virtual void Update()
  {
  UpdateInputLock();
  }
 
  /// <summary>
  /// Renders a key bind option.
  /// </summary>
  private static void RenderKeyBind(string name, KeyCode currentBinding, Action<KeyCode> acceptClicked)
  {
  GUILayout.BeginHorizontal();
  GUILayout.Label(name);
  if (GUILayout.Button(currentBinding.ToString(), HighLogic.Skin.button, GUILayout.Width(100.0f)))
  {
  KeyBindPopup.Show(name, currentBinding, acceptClicked);
  }
  GUILayout.EndHorizontal();
  }
 
  /// <summary>
  /// Centres the window on screen.
  /// </summary>
  private void CentreWindow()
  {
  if (hasCentred == false && position.width > 0.0f && position.height > 0.0f)
  {
  hasCentred = true;
  position.center = new Vector2(Screen.width * 0.5f, Screen.height * 0.5f);
  }
  }
 
  /// <summary>
  /// Renders the GUI window contents.
  /// </summary>
  private void RenderWindow(int id)
  {
  GUILayout.BeginVertical(HighLogic.Skin.textArea);
  RenderKeyBind("Editor Show/Hide", EditorShowHide, binding => EditorShowHide = binding);
  RenderKeyBind("Flight Show/Hide", FlightShowHide, binding => FlightShowHide = binding);
  GUILayout.EndVertical();
 
  if (GUILayout.Button("Close", HighLogic.Skin.button))
  {
  Destroy(gameObject);
  }
 
  GUI.DragWindow();
  }
 
  /// <summary>
  /// Updates the input lock.
  /// </summary>
  private void UpdateInputLock()
  {
  bool mouseOver = position.MouseIsOver();
  bool inputLock = InputLock;
 
  if (mouseOver && inputLock == false)
  {
  InputLock = true;
  }
  else if (mouseOver == false && inputLock)
  {
  InputLock = false;
  }
  }
  }
  }
  //
  // 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.KeyBinding
  {
  using System.Xml.Serialization;
  using UnityEngine;
 
  public class KeyBindingsObject
  {
  public KeyCode EditorShowHide { get; set; }
 
  public KeyCode FlightShowHide { get; set; }
  }
  }
//  
// 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.UIControls  
{  
using System;  
using UnityEngine;  
 
public class SelectKeyBindPopup : MonoBehaviour  
{  
private readonly Array availableBindings = Enum.GetValues(typeof(KeyCode));  
private bool isCentred;  
private Rect position = new Rect(0.0f, 0.0f, 250.0f, 0.0f);  
 
/// <summary>  
/// Gets whether a key bind popup is already open.  
/// </summary>  
public static bool IsOpen { get; private set; }  
 
/// <summary>  
/// Gets the delegate to be invoked when accepted button is clicked.  
/// </summary>  
public Action<KeyCode> AcceptClicked { get; private set; }  
 
/// <summary>  
/// Gets the name of the binding to change.  
/// </summary>  
public string Name { get; private set; }  
 
/// <summary>  
/// Gets the selected binding.  
/// </summary>  
public KeyCode Binding { get; private set; }  
 
/// <summary>  
/// Shows a key bind popup allowing the user to select a key for binding.  
/// </summary>  
public static void Show(string name, KeyCode currentBinding, Action<KeyCode> acceptClicked)  
{  
if (IsOpen)  
{  
return;  
}  
 
SelectKeyBindPopup selectKeyBindPopup = new GameObject("SelectKeyBind").AddComponent<SelectKeyBindPopup>();  
selectKeyBindPopup.Name = name;  
selectKeyBindPopup.Binding = currentBinding;  
selectKeyBindPopup.AcceptClicked = acceptClicked;  
}  
 
/// <summary>  
/// Handles the accept button click event.  
/// </summary>  
public void OnAccept()  
{  
if (AcceptClicked != null)  
{  
AcceptClicked.Invoke(Binding);  
}  
Destroy(gameObject);  
}  
 
/// <summary>  
/// Handles the cancel button click event.  
/// </summary>  
public void OnCancel()  
{  
Destroy(gameObject);  
}  
 
/// <summary>  
/// Called by unity when the component is created.  
/// </summary>  
protected virtual void Awake()  
{  
if (IsOpen)  
{  
OnCancel();  
}  
else  
{  
IsOpen = true;  
}  
}  
 
/// <summary>  
/// Called by unity when the component is destroyed.  
/// </summary>  
protected virtual void OnDestroy()  
{  
IsOpen = false;  
}  
 
/// <summary>  
/// Called by unity each frame to render the GUI.  
/// </summary>  
protected virtual void OnGUI()  
{  
position = GUILayout.Window(GetInstanceID(), position, RenderWindow, "Select Key Bind", HighLogic.Skin.window);  
CentreWindow();  
}  
 
/// <summary>  
/// Called by unity every frame.  
/// </summary>  
protected virtual void Update()  
{  
CentreWindow();  
UpdateBinding();  
}  
 
/// <summary>  
/// Centres the window on the screen.  
/// </summary>  
private void CentreWindow()  
{  
if (isCentred == false && position.width > 0.0f && position.height > 0.0f)  
{  
isCentred = true;  
position.center = new Vector2(Screen.width * 0.5f, Screen.height * 0.5f);  
}  
}  
 
/// <summary>  
/// Renders the window content.  
/// </summary>  
private void RenderWindow(int id)  
{  
// Binding labels.  
GUILayout.BeginVertical(HighLogic.Skin.textArea);  
GUILayout.Label("Key Bind: " + Name);  
GUILayout.Label("Selected: " + Binding);  
GUILayout.EndVertical();  
 
// Window buttons.  
GUILayout.BeginHorizontal();  
if (GUILayout.Button("Cancel", HighLogic.Skin.button))  
{  
OnCancel();  
}  
 
if (GUILayout.Button("Accept", HighLogic.Skin.button))  
{  
OnAccept();  
}  
GUILayout.EndHorizontal();  
 
// Make the window to be draggable.  
GUI.DragWindow();  
}  
 
/// <summary>  
/// Updates the binding selected by the user.  
/// </summary>  
private void UpdateBinding()  
{  
for (int i = 0; i < availableBindings.Length; ++i)  
{  
KeyCode keyCode = (KeyCode)availableBindings.GetValue(i);  
 
if (keyCode == KeyCode.Mouse0)  
{  
continue;  
}  
 
if (Input.GetKeyDown(keyCode))  
{  
Binding = keyCode;  
}  
}  
}  
}  
}  
// //
// 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.VesselSimulator namespace KerbalEngineer.VesselSimulator
{ {
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using Editor; using Editor;
using Helpers; using Helpers;
using UnityEngine; using UnityEngine;
   
public class EngineSim public class EngineSim
{ {
private static readonly Pool<EngineSim> pool = new Pool<EngineSim>(Create, Reset); private static readonly Pool<EngineSim> pool = new Pool<EngineSim>(Create, Reset);
   
private readonly ResourceContainer resourceConsumptions = new ResourceContainer(); private readonly ResourceContainer resourceConsumptions = new ResourceContainer();
private readonly ResourceContainer resourceFlowModes = new ResourceContainer(); private readonly ResourceContainer resourceFlowModes = new ResourceContainer();
   
public double actualThrust = 0; public double actualThrust = 0;
public bool isActive = false; public bool isActive = false;
public double isp = 0; public double isp = 0;
public PartSim partSim; public PartSim partSim;
public List<AppliedForce> appliedForces = new List<AppliedForce>(); public List<AppliedForce> appliedForces = new List<AppliedForce>();
public float maxMach; public float maxMach;
   
public double thrust = 0; public double thrust = 0;
   
// Add thrust vector to account for directional losses // Add thrust vector to account for directional losses
public Vector3 thrustVec; public Vector3 thrustVec;
   
private static EngineSim Create() private static EngineSim Create()
{ {
return new EngineSim(); return new EngineSim();
} }
   
private static void Reset(EngineSim engineSim) private static void Reset(EngineSim engineSim)
{ {
engineSim.resourceConsumptions.Reset(); engineSim.resourceConsumptions.Reset();
engineSim.resourceFlowModes.Reset(); engineSim.resourceFlowModes.Reset();
engineSim.actualThrust = 0; engineSim.actualThrust = 0;
engineSim.isActive = false; engineSim.isActive = false;
engineSim.isp = 0; engineSim.isp = 0;
for (int i = 0; i < engineSim.appliedForces.Count; i++) for (int i = 0; i < engineSim.appliedForces.Count; i++)
{ {
engineSim.appliedForces[i].Release(); engineSim.appliedForces[i].Release();
} }
engineSim.appliedForces.Clear(); engineSim.appliedForces.Clear();
engineSim.thrust = 0; engineSim.thrust = 0;
engineSim.maxMach = 0f; engineSim.maxMach = 0f;
} }
   
public void Release() public void Release()
{ {
pool.Release(this); pool.Release(this);
} }
   
public static EngineSim New(PartSim theEngine, public static EngineSim New(PartSim theEngine,
double atmosphere, double atmosphere,
float machNumber, float machNumber,
float maxFuelFlow, float maxFuelFlow,
float minFuelFlow, float minFuelFlow,
float thrustPercentage, float thrustPercentage,
Vector3 vecThrust, Vector3 vecThrust,
FloatCurve atmosphereCurve, FloatCurve atmosphereCurve,
bool atmChangeFlow, bool atmChangeFlow,
FloatCurve atmCurve, FloatCurve atmCurve,
FloatCurve velCurve, FloatCurve velCurve,
float currentThrottle, float currentThrottle,
float IspG, float IspG,
bool throttleLocked, bool throttleLocked,
List<Propellant> propellants, List<Propellant> propellants,
bool active, bool active,
float resultingThrust, float resultingThrust,
List<Transform> thrustTransforms, List<Transform> thrustTransforms,
LogMsg log) LogMsg log)
{ {
EngineSim engineSim = pool.Borrow(); EngineSim engineSim = pool.Borrow();
   
engineSim.isp = 0.0; engineSim.isp = 0.0;
engineSim.maxMach = 0.0f; engineSim.maxMach = 0.0f;
engineSim.actualThrust = 0.0; engineSim.actualThrust = 0.0;
engineSim.partSim = theEngine; engineSim.partSim = theEngine;
engineSim.isActive = active; engineSim.isActive = active;
engineSim.thrustVec = vecThrust; engineSim.thrustVec = vecThrust;
engineSim.resourceConsumptions.Reset(); engineSim.resourceConsumptions.Reset();
engineSim.resourceFlowModes.Reset(); engineSim.resourceFlowModes.Reset();
engineSim.appliedForces.Clear(); engineSim.appliedForces.Clear();
   
double flowRate = 0.0; double flowRate = 0.0;
if (engineSim.partSim.hasVessel) if (engineSim.partSim.hasVessel)
{ {
if (log != null) log.buf.AppendLine("hasVessel is true"); if (log != null) log.buf.AppendLine("hasVessel is true");
   
float flowModifier = GetFlowModifier(atmChangeFlow, atmCurve, engineSim.partSim.part.atmDensity, velCurve, machNumber, ref engineSim.maxMach); float flowModifier = GetFlowModifier(atmChangeFlow, atmCurve, engineSim.partSim.part.atmDensity, velCurve, machNumber, ref engineSim.maxMach);
engineSim.isp = atmosphereCurve.Evaluate((float)atmosphere); engineSim.isp = atmosphereCurve.Evaluate((float)atmosphere);
engineSim.thrust = GetThrust(Mathf.Lerp(minFuelFlow, maxFuelFlow, GetThrustPercent(thrustPercentage)) * flowModifier, engineSim.isp); engineSim.thrust = GetThrust(Mathf.Lerp(minFuelFlow, maxFuelFlow, GetThrustPercent(thrustPercentage)) * flowModifier, engineSim.isp);
engineSim.actualThrust = engineSim.isActive ? resultingThrust : 0.0; engineSim.actualThrust = engineSim.isActive ? resultingThrust : 0.0;
if (log != null) if (log != null)
{ {
log.buf.AppendFormat("flowMod = {0:g6}\n", flowModifier); log.buf.AppendFormat("flowMod = {0:g6}\n", flowModifier);
log.buf.AppendFormat("isp = {0:g6}\n", engineSim.isp); log.buf.AppendFormat("isp = {0:g6}\n", engineSim.isp);
log.buf.AppendFormat("thrust = {0:g6}\n", engineSim.thrust); log.buf.AppendFormat("thrust = {0:g6}\n", engineSim.thrust);
log.buf.AppendFormat("actual = {0:g6}\n", engineSim.actualThrust); log.buf.AppendFormat("actual = {0:g6}\n", engineSim.actualThrust);
} }
   
if (throttleLocked) if (throttleLocked)
{ {
if (log != null) log.buf.AppendLine("throttleLocked is true, using thrust for flowRate"); if (log != null) log.buf.AppendLine("throttleLocked is true, using thrust for flowRate");
flowRate = GetFlowRate(engineSim.thrust, engineSim.isp); flowRate = GetFlowRate(engineSim.thrust, engineSim.isp);
} }
else else
{ {
if (currentThrottle > 0.0f && engineSim.partSim.isLanded == false) if (currentThrottle > 0.0f && engineSim.partSim.isLanded == false)
{ {
if (log != null) log.buf.AppendLine("throttled up and not landed, using actualThrust for flowRate"); if (log != null) log.buf.AppendLine("throttled up and not landed, using actualThrust for flowRate");
flowRate = GetFlowRate(engineSim.actualThrust, engineSim.isp); flowRate = GetFlowRate(engineSim.actualThrust, engineSim.isp);
} }
else else
{ {
if (log != null) log.buf.AppendLine("throttled down or landed, using thrust for flowRate"); if (log != null) log.buf.AppendLine("throttled down or landed, using thrust for flowRate");
flowRate = GetFlowRate(engineSim.thrust, engineSim.isp); flowRate = GetFlowRate(engineSim.thrust, engineSim.isp);
} }
} }
} }
else else
{ {
if (log != null) log.buf.AppendLine("hasVessel is false"); if (log != null) log.buf.AppendLine("hasVessel is false");
float flowModifier = GetFlowModifier(atmChangeFlow, atmCurve, CelestialBodies.SelectedBody.GetDensity(BuildAdvanced.Altitude), velCurve, machNumber, ref engineSim.maxMach); float flowModifier = GetFlowModifier(atmChangeFlow, atmCurve, CelestialBodies.SelectedBody.GetDensity(BuildAdvanced.Altitude), velCurve, machNumber, ref engineSim.maxMach);
engineSim.isp = atmosphereCurve.Evaluate((float)atmosphere); engineSim.isp = atmosphereCurve.Evaluate((float)atmosphere);
engineSim.thrust = GetThrust(Mathf.Lerp(minFuelFlow, maxFuelFlow, GetThrustPercent(thrustPercentage)) * flowModifier, engineSim.isp); engineSim.thrust = GetThrust(Mathf.Lerp(minFuelFlow, maxFuelFlow, GetThrustPercent(thrustPercentage)) * flowModifier, engineSim.isp);
engineSim.actualThrust = 0d; engineSim.actualThrust = 0d;
if (log != null) if (log != null)
{ {
log.buf.AppendFormat("flowMod = {0:g6}\n", flowModifier); log.buf.AppendFormat("flowMod = {0:g6}\n", flowModifier);
log.buf.AppendFormat("isp = {0:g6}\n", engineSim.isp); log.buf.AppendFormat("isp = {0:g6}\n", engineSim.isp);
log.buf.AppendFormat("thrust = {0:g6}\n", engineSim.thrust); log.buf.AppendFormat("thrust = {0:g6}\n", engineSim.thrust);
log.buf.AppendFormat("actual = {0:g6}\n", engineSim.actualThrust); log.buf.AppendFormat("actual = {0:g6}\n", engineSim.actualThrust);
} }
   
if (log != null) log.buf.AppendLine("no vessel, using thrust for flowRate"); if (log != null) log.buf.AppendLine("no vessel, using thrust for flowRate");
flowRate = GetFlowRate(engineSim.thrust, engineSim.isp); flowRate = GetFlowRate(engineSim.thrust, engineSim.isp);
} }
   
if (log != null) log.buf.AppendFormat("flowRate = {0:g6}\n", flowRate); if (log != null) log.buf.AppendFormat("flowRate = {0:g6}\n", flowRate);
   
float flowMass = 0f; float flowMass = 0f;
for (int i = 0; i < propellants.Count; ++i) for (int i = 0; i < propellants.Count; ++i)
{ {
Propellant propellant = propellants[i]; Propellant propellant = propellants[i];
if (!propellant.ignoreForIsp) if (!propellant.ignoreForIsp)
flowMass += propellant.ratio * ResourceContainer.GetResourceDensity(propellant.id); flowMass += propellant.ratio * ResourceContainer.GetResourceDensity(propellant.id);
} }
   
if (log != null) log.buf.AppendFormat("flowMass = {0:g6}\n", flowMass); if (log != null) log.buf.AppendFormat("flowMass = {0:g6}\n", flowMass);
   
for (int i = 0; i < propellants.Count; ++i) for (int i = 0; i < propellants.Count; ++i)
{ {
Propellant propellant = propellants[i]; Propellant propellant = propellants[i];
   
if (propellant.name == "ElectricCharge" || propellant.name == "IntakeAir") if (propellant.name == "ElectricCharge" || propellant.name == "IntakeAir")
{ {
continue; continue;
} }
   
double consumptionRate = propellant.ratio * flowRate / flowMass; double consumptionRate = propellant.ratio * flowRate / flowMass;
if (log != null) log.buf.AppendFormat( if (log != null) log.buf.AppendFormat(
"Add consumption({0}, {1}:{2:d}) = {3:g6}\n", "Add consumption({0}, {1}:{2:d}) = {3:g6}\n",
ResourceContainer.GetResourceName(propellant.id), ResourceContainer.GetResourceName(propellant.id),
theEngine.name, theEngine.name,
theEngine.partId, theEngine.partId,
consumptionRate); consumptionRate);
engineSim.resourceConsumptions.Add(propellant.id, consumptionRate); engineSim.resourceConsumptions.Add(propellant.id, consumptionRate);
engineSim.resourceFlowModes.Add(propellant.id, (double)propellant.GetFlowMode()); engineSim.resourceFlowModes.Add(propellant.id, (double)propellant.GetFlowMode());
} }
   
double thrustPerThrustTransform = engineSim.thrust / thrustTransforms.Count; double thrustPerThrustTransform = engineSim.thrust / thrustTransforms.Count;
for (int i = 0; i < thrustTransforms.Count; i++) for (int i = 0; i < thrustTransforms.Count; i++)
{ {
Transform thrustTransform = thrustTransforms[i]; Transform thrustTransform = thrustTransforms[i];
Vector3d direction = thrustTransform.forward.normalized; Vector3d direction = thrustTransform.forward.normalized;
Vector3d position = thrustTransform.position; Vector3d position = thrustTransform.position;
   
AppliedForce appliedForce = AppliedForce.New(direction * thrustPerThrustTransform, position); AppliedForce appliedForce = AppliedForce.New(direction * thrustPerThrustTransform, position);
engineSim.appliedForces.Add(appliedForce); engineSim.appliedForces.Add(appliedForce);
} }
   
return engineSim; return engineSim;
} }
   
public ResourceContainer ResourceConsumptions public ResourceContainer ResourceConsumptions
{ {
get get
{ {
return resourceConsumptions; return resourceConsumptions;
} }
} }
   
public static double GetExhaustVelocity(double isp) public static double GetExhaustVelocity(double isp)
{ {
return isp * Units.GRAVITY; return isp * Units.GRAVITY;
} }
   
public static float GetFlowModifier(bool atmChangeFlow, FloatCurve atmCurve, double atmDensity, FloatCurve velCurve, float machNumber, ref float maxMach) public static float GetFlowModifier(bool atmChangeFlow, FloatCurve atmCurve, double atmDensity, FloatCurve velCurve, float machNumber, ref float maxMach)
{ {
float flowModifier = 1.0f; float flowModifier = 1.0f;
if (atmChangeFlow) if (atmChangeFlow)
{ {
flowModifier = (float)(atmDensity / 1.225); flowModifier = (float)(atmDensity / 1.225);
if (atmCurve != null) if (atmCurve != null)
{ {
flowModifier = atmCurve.Evaluate(flowModifier); flowModifier = atmCurve.Evaluate(flowModifier);
} }
} }
if (velCurve != null) if (velCurve != null)
{ {
flowModifier = flowModifier * velCurve.Evaluate(machNumber); flowModifier = flowModifier * velCurve.Evaluate(machNumber);
maxMach = velCurve.maxTime; maxMach = velCurve.maxTime;
} }
if (flowModifier < float.Epsilon) if (flowModifier < float.Epsilon)
{ {
flowModifier = float.Epsilon; flowModifier = float.Epsilon;
} }
return flowModifier; return flowModifier;
} }
   
public static double GetFlowRate(double thrust, double isp) public static double GetFlowRate(double thrust, double isp)
{ {
return thrust / GetExhaustVelocity(isp); return thrust / GetExhaustVelocity(isp);
} }
   
public static float GetThrottlePercent(float currentThrottle, float thrustPercentage) public static float GetThrottlePercent(float currentThrottle, float thrustPercentage)
{ {
return currentThrottle * GetThrustPercent(thrustPercentage); return currentThrottle * GetThrustPercent(thrustPercentage);
} }
   
public static double GetThrust(double flowRate, double isp) public static double GetThrust(double flowRate, double isp)
{ {
return flowRate * GetExhaustVelocity(isp); return flowRate * GetExhaustVelocity(isp);
} }
   
public static float GetThrustPercent(float thrustPercentage) public static float GetThrustPercent(float thrustPercentage)
{ {
return thrustPercentage * 0.01f; return thrustPercentage * 0.01f;
} }
   
public void DumpEngineToBuffer(StringBuilder buffer, String prefix) public void DumpEngineToBuffer(StringBuilder buffer, String prefix)
{ {
buffer.Append(prefix); buffer.Append(prefix);
buffer.AppendFormat("[thrust = {0:g6}, actual = {1:g6}, isp = {2:g6}\n", thrust, actualThrust, isp); buffer.AppendFormat("[thrust = {0:g6}, actual = {1:g6}, isp = {2:g6}\n", thrust, actualThrust, isp);
} }
   
// A dictionary to hold a set of parts for each resource // A dictionary to hold a set of parts for each resource
Dictionary<int, HashSet<PartSim>> sourcePartSets = new Dictionary<int, HashSet<PartSim>>(); Dictionary<int, HashSet<PartSim>> sourcePartSets = new Dictionary<int, HashSet<PartSim>>();
   
Dictionary<int, HashSet<PartSim>> stagePartSets = new Dictionary<int, HashSet<PartSim>>(); Dictionary<int, HashSet<PartSim>> stagePartSets = new Dictionary<int, HashSet<PartSim>>();
   
HashSet<PartSim> visited = new HashSet<PartSim>(); HashSet<PartSim> visited = new HashSet<PartSim>();
   
public void DumpSourcePartSets(String msg) public void DumpSourcePartSets(String msg)
{ {
MonoBehaviour.print("DumpSourcePartSets " + msg); MonoBehaviour.print("DumpSourcePartSets " + msg);
foreach (int type in sourcePartSets.Keys) foreach (int type in sourcePartSets.Keys)
{ {
MonoBehaviour.print("SourcePartSet for " + ResourceContainer.GetResourceName(type)); MonoBehaviour.print("SourcePartSet for " + ResourceContainer.GetResourceName(type));
HashSet<PartSim> sourcePartSet = sourcePartSets[type]; HashSet<PartSim> sourcePartSet = sourcePartSets[type];
if (sourcePartSet.Count > 0) if (sourcePartSet.Count > 0)
{ {
foreach (PartSim partSim in sourcePartSet) foreach (PartSim partSim in sourcePartSet)
{ {
MonoBehaviour.print("Part " + partSim.name + ":" + partSim.partId); MonoBehaviour.print("Part " + partSim.name + ":" + partSim.partId);
} }
} }
else else
{ {
MonoBehaviour.print("No parts"); MonoBehaviour.print("No parts");
} }
} }
} }
   
public bool SetResourceDrains(List<PartSim> allParts, List<PartSim> allFuelLines, HashSet<PartSim> drainingParts) public bool SetResourceDrains(List<PartSim> allParts, List<PartSim> allFuelLines, HashSet<PartSim> drainingParts)
{ {
LogMsg log = null; LogMsg log = null;
//DumpSourcePartSets("before clear"); //DumpSourcePartSets("before clear");
foreach (HashSet<PartSim> sourcePartSet in sourcePartSets.Values) foreach (HashSet<PartSim> sourcePartSet in sourcePartSets.Values)
{ {
sourcePartSet.Clear(); sourcePartSet.Clear();
} }
//DumpSourcePartSets("after clear"); //DumpSourcePartSets("after clear");
   
for (int index = 0; index < this.resourceConsumptions.Types.Count; index++) for (int index = 0; index < this.resourceConsumptions.Types.Count; index++)
{ {
int type = this.resourceConsumptions.Types[index]; int type = this.resourceConsumptions.Types[index];
   
HashSet<PartSim> sourcePartSet; HashSet<PartSim> sourcePartSet;
if (!sourcePartSets.TryGetValue(type, out sourcePartSet)) if (!sourcePartSets.TryGetValue(type, out sourcePartSet))
{ {
sourcePartSet = new HashSet<PartSim>(); sourcePartSet = new HashSet<PartSim>();
sourcePartSets.Add(type, sourcePartSet); sourcePartSets.Add(type, sourcePartSet);
} }
   
switch ((ResourceFlowMode)this.resourceFlowModes[type]) switch ((ResourceFlowMode)this.resourceFlowModes[type])
{ {
case ResourceFlowMode.NO_FLOW: case ResourceFlowMode.NO_FLOW:
if (partSim.resources[type] > SimManager.RESOURCE_MIN && partSim.resourceFlowStates[type] != 0) if (partSim.resources[type] > SimManager.RESOURCE_MIN && partSim.resourceFlowStates[type] != 0)
{ {
//sourcePartSet = new HashSet<PartSim>(); //sourcePartSet = new HashSet<PartSim>();
//MonoBehaviour.print("SetResourceDrains(" + name + ":" + partId + ") setting sources to just this"); //MonoBehaviour.print("SetResourceDrains(" + name + ":" + partId + ") setting sources to just this");
sourcePartSet.Add(partSim); sourcePartSet.Add(partSim);
} }
break; break;
   
case ResourceFlowMode.ALL_VESSEL: case ResourceFlowMode.ALL_VESSEL:
  case ResourceFlowMode.ALL_VESSEL_BALANCE:
for (int i = 0; i < allParts.Count; i++) for (int i = 0; i < allParts.Count; i++)
{ {
PartSim aPartSim = allParts[i]; PartSim aPartSim = allParts[i];
if (aPartSim.resources[type] > SimManager.RESOURCE_MIN && aPartSim.resourceFlowStates[type] != 0) if (aPartSim.resources[type] > SimManager.RESOURCE_MIN && aPartSim.resourceFlowStates[type] != 0)
{ {
sourcePartSet.Add(aPartSim); sourcePartSet.Add(aPartSim);
} }
} }
break; break;
   
case ResourceFlowMode.STAGE_PRIORITY_FLOW: case ResourceFlowMode.STAGE_PRIORITY_FLOW:
  case ResourceFlowMode.STAGE_PRIORITY_FLOW_BALANCE:
   
foreach (HashSet<PartSim> stagePartSet in stagePartSets.Values) foreach (HashSet<PartSim> stagePartSet in stagePartSets.Values)
{ {
stagePartSet.Clear(); stagePartSet.Clear();
} }
var maxStage = -1; var maxStage = -1;
   
//Logger.Log(type); //Logger.Log(type);
for (int i = 0; i < allParts.Count; i++) for (int i = 0; i < allParts.Count; i++)
{ {
var aPartSim = allParts[i]; var aPartSim = allParts[i];
if (aPartSim.resources[type] <= SimManager.RESOURCE_MIN || aPartSim.resourceFlowStates[type] == 0) if (aPartSim.resources[type] <= SimManager.RESOURCE_MIN || aPartSim.resourceFlowStates[type] == 0)
{ {
continue; continue;
} }
   
int stage = aPartSim.DecouplerCount(); int stage = aPartSim.DecouplerCount();
if (stage > maxStage) if (stage > maxStage)
{ {
maxStage = stage; maxStage = stage;
} }
   
HashSet<PartSim> tempPartSet; HashSet<PartSim> tempPartSet;
if (!stagePartSets.TryGetValue(stage, out tempPartSet)) if (!stagePartSets.TryGetValue(stage, out tempPartSet))
{ {
tempPartSet = new HashSet<PartSim>(); tempPartSet = new HashSet<PartSim>();
stagePartSets.Add(stage, tempPartSet); stagePartSets.Add(stage, tempPartSet);
} }
tempPartSet.Add(aPartSim); tempPartSet.Add(aPartSim);
} }
   
for (int j = maxStage; j >= 0; j--) for (int j = maxStage; j >= 0; j--)
{ {
HashSet<PartSim> stagePartSet; HashSet<PartSim> stagePartSet;
if (stagePartSets.TryGetValue(j, out stagePartSet) && stagePartSet.Count > 0) if (stagePartSets.TryGetValue(j, out stagePartSet) && stagePartSet.Count > 0)
{ {
// We have to copy the contents of the set here rather than copying the set reference or // We have to copy the contents of the set here rather than copying the set reference or
// bad things (tm) happen // bad things (tm) happen
foreach (PartSim aPartSim in stagePartSet) foreach (PartSim aPartSim in stagePartSet)
{ {
sourcePartSet.Add(aPartSim); sourcePartSet.Add(aPartSim);
} }
break; break;
} }
} }
break; break;
   
case ResourceFlowMode.STACK_PRIORITY_SEARCH: case ResourceFlowMode.STACK_PRIORITY_SEARCH:
  case ResourceFlowMode.STAGE_STACK_FLOW:
  case ResourceFlowMode.STAGE_STACK_FLOW_BALANCE:
visited.Clear(); visited.Clear();
   
if (SimManager.logOutput) if (SimManager.logOutput)
{ {
log = new LogMsg(); log = new LogMsg();
log.buf.AppendLine("Find " + ResourceContainer.GetResourceName(type) + " sources for " + partSim.name + ":" + partSim.partId); log.buf.AppendLine("Find " + ResourceContainer.GetResourceName(type) + " sources for " + partSim.name + ":" + partSim.partId);
} }
partSim.GetSourceSet(type, allParts, visited, sourcePartSet, log, ""); partSim.GetSourceSet(type, allParts, visited, sourcePartSet, log, "");
if (SimManager.logOutput) if (SimManager.logOutput)
{ {
MonoBehaviour.print(log.buf); MonoBehaviour.print(log.buf);
} }
break; break;
   
default: default:
MonoBehaviour.print("SetResourceDrains(" + partSim.name + ":" + partSim.partId + ") Unexpected flow type for " + ResourceContainer.GetResourceName(type) + ")"); MonoBehaviour.print("SetResourceDrains(" + partSim.name + ":" + partSim.partId + ") Unexpected flow type for " + ResourceContainer.GetResourceName(type) + ")");
break; break;
} }
   
if (SimManager.logOutput) if (SimManager.logOutput)
{ {
if (sourcePartSet.Count > 0) if (sourcePartSet.Count > 0)
{ {
log = new LogMsg(); log = new LogMsg();
log.buf.AppendLine("Source parts for " + ResourceContainer.GetResourceName(type) + ":"); log.buf.AppendLine("Source parts for " + ResourceContainer.GetResourceName(type) + ":");
foreach (PartSim partSim in sourcePartSet) foreach (PartSim partSim in sourcePartSet)
{ {
log.buf.AppendLine(partSim.name + ":" + partSim.partId); log.buf.AppendLine(partSim.name + ":" + partSim.partId);
} }
MonoBehaviour.print(log.buf); MonoBehaviour.print(log.buf);
} }
} }
   
//DumpSourcePartSets("after " + ResourceContainer.GetResourceName(type)); //DumpSourcePartSets("after " + ResourceContainer.GetResourceName(type));
} }
// If we don't have sources for all the needed resources then return false without setting up any drains // If we don't have sources for all the needed resources then return false without setting up any drains
for (int i = 0; i < this.resourceConsumptions.Types.Count; i++) for (int i = 0; i < this.resourceConsumptions.Types.Count; i++)
{ {
int type = this.resourceConsumptions.Types[i]; int type = this.resourceConsumptions.Types[i];
HashSet<PartSim> sourcePartSet; HashSet<PartSim> sourcePartSet;
if (!sourcePartSets.TryGetValue(type, out sourcePartSet) || sourcePartSet.Count == 0) if (!sourcePartSets.TryGetValue(type, out sourcePartSet) || sourcePartSet.Count == 0)
{ {
if (SimManager.logOutput) if (SimManager.logOutput)
{ {
MonoBehaviour.print("No source of " + ResourceContainer.GetResourceName(type)); MonoBehaviour.print("No source of " + ResourceContainer.GetResourceName(type));
} }
   
isActive = false; isActive = false;
return false; return false;
} }
} }
   
// Now we set the drains on the members of the sets and update the draining parts set // Now we set the drains on the members of the sets and update the draining parts set
for (int i = 0; i < this.resourceConsumptions.Types.Count; i++) for (int i = 0; i < this.resourceConsumptions.Types.Count; i++)
{ {
int type = this.resourceConsumptions.Types[i]; int type = this.resourceConsumptions.Types[i];
HashSet<PartSim> sourcePartSet = sourcePartSets[type]; HashSet<PartSim> sourcePartSet = sourcePartSets[type];
// Loop through the members of the set // Loop through the members of the set
double amount = resourceConsumptions[type] / sourcePartSet.Count; double amount = resourceConsumptions[type] / sourcePartSet.Count;
foreach (PartSim partSim in sourcePartSet) foreach (PartSim partSim in sourcePartSet)
{ {
if (SimManager.logOutput) if (SimManager.logOutput)
{ {
MonoBehaviour.print( MonoBehaviour.print(
"Adding drain of " + amount + " " + ResourceContainer.GetResourceName(type) + " to " + partSim.name + ":" + "Adding drain of " + amount + " " + ResourceContainer.GetResourceName(type) + " to " + partSim.name + ":" +
partSim.partId); partSim.partId);
} }
   
partSim.resourceDrains.Add(type, amount); partSim.resourceDrains.Add(type, amount);
drainingParts.Add(partSim); drainingParts.Add(partSim);
} }
} }
return true; return true;
} }
} }
} }
// //
// 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.VesselSimulator namespace KerbalEngineer.VesselSimulator
{ {
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using CompoundParts; using CompoundParts;
using Extensions; using Extensions;
using UnityEngine; using UnityEngine;
   
public class PartSim public class PartSim
{ {
private static readonly Pool<PartSim> pool = new Pool<PartSim>(Create, Reset); private static readonly Pool<PartSim> pool = new Pool<PartSim>(Create, Reset);
   
private readonly List<AttachNodeSim> attachNodes = new List<AttachNodeSim>(); private readonly List<AttachNodeSim> attachNodes = new List<AttachNodeSim>();
   
public double realMass; public double realMass;
public double baseMass; public double baseMass;
public double baseMassForCoM; public double baseMassForCoM;
public Vector3d centerOfMass; public Vector3d centerOfMass;
public double baseCost; public double baseCost;
public int decoupledInStage; public int decoupledInStage;
public bool fuelCrossFeed; public bool fuelCrossFeed;
public List<PartSim> fuelTargets = new List<PartSim>(); public List<PartSim> fuelTargets = new List<PartSim>();
public bool hasModuleEngines; public bool hasModuleEngines;
public bool hasMultiModeEngine; public bool hasMultiModeEngine;
   
public bool hasVessel; public bool hasVessel;
public String initialVesselName; public String initialVesselName;
public int inverseStage; public int inverseStage;
public bool isDecoupler; public bool isDecoupler;
public bool isEngine; public bool isEngine;
public bool isFuelLine; public bool isFuelLine;
public bool isFuelTank; public bool isFuelTank;
public bool isLanded; public bool isLanded;
public bool isNoPhysics; public bool isNoPhysics;
public bool isSepratron; public bool isSepratron;
public bool isFairing; public bool isFairing;
public float fairingMass; public float fairingMass;
public int stageIndex; public int stageIndex;
public String name; public String name;
public String noCrossFeedNodeKey; public String noCrossFeedNodeKey;
public PartSim parent; public PartSim parent;
public AttachModes parentAttach; public AttachModes parentAttach;
public Part part; // This is only set while the data structures are being initialised public Part part; // This is only set while the data structures are being initialised
public int partId = 0; public int partId = 0;
public ResourceContainer resourceDrains = new ResourceContainer(); public ResourceContainer resourceDrains = new ResourceContainer();
public ResourceContainer resourceFlowStates = new ResourceContainer(); public ResourceContainer resourceFlowStates = new ResourceContainer();
public ResourceContainer resources = new ResourceContainer(); public ResourceContainer resources = new ResourceContainer();
public double startMass = 0d; public double startMass = 0d;
public String vesselName; public String vesselName;
public VesselType vesselType; public VesselType vesselType;
   
private static PartSim Create() private static PartSim Create()
{ {
return new PartSim(); return new PartSim();
} }
   
private static void Reset(PartSim partSim) private static void Reset(PartSim partSim)
{ {
for (int i = 0; i < partSim.attachNodes.Count; i++) for (int i = 0; i < partSim.attachNodes.Count; i++)
{ {
partSim.attachNodes[i].Release(); partSim.attachNodes[i].Release();
} }
partSim.attachNodes.Clear(); partSim.attachNodes.Clear();
partSim.fuelTargets.Clear(); partSim.fuelTargets.Clear();
partSim.resourceDrains.Reset(); partSim.resourceDrains.Reset();
partSim.resourceFlowStates.Reset(); partSim.resourceFlowStates.Reset();
partSim.resources.Reset(); partSim.resources.Reset();
partSim.baseCost = 0d; partSim.baseCost = 0d;
partSim.baseMass = 0d; partSim.baseMass = 0d;
partSim.baseMassForCoM = 0d; partSim.baseMassForCoM = 0d;
partSim.startMass = 0d; partSim.startMass = 0d;
} }
   
public void Release() public void Release()
{ {
pool.Release(this); pool.Release(this);
} }
   
public static PartSim New(Part thePart, int id, double atmosphere, LogMsg log) public static PartSim New(Part thePart, int id, double atmosphere, LogMsg log)
{ {
PartSim partSim = pool.Borrow(); PartSim partSim = pool.Borrow();
   
partSim.part = thePart; partSim.part = thePart;
partSim.centerOfMass = thePart.transform.TransformPoint(thePart.CoMOffset); partSim.centerOfMass = thePart.transform.TransformPoint(thePart.CoMOffset);
partSim.partId = id; partSim.partId = id;
partSim.name = partSim.part.partInfo.name; partSim.name = partSim.part.partInfo.name;
   
if (log != null) log.buf.AppendLine("Create PartSim for " + partSim.name); if (log != null) log.buf.AppendLine("Create PartSim for " + partSim.name);
   
partSim.parent = null; partSim.parent = null;
partSim.parentAttach = partSim.part.attachMode; partSim.parentAttach = partSim.part.attachMode;
partSim.fuelCrossFeed = partSim.part.fuelCrossFeed; partSim.fuelCrossFeed = partSim.part.fuelCrossFeed;
partSim.noCrossFeedNodeKey = partSim.part.NoCrossFeedNodeKey; partSim.noCrossFeedNodeKey = partSim.part.NoCrossFeedNodeKey;
partSim.decoupledInStage = partSim.DecoupledInStage(partSim.part); partSim.decoupledInStage = partSim.DecoupledInStage(partSim.part);
partSim.isFuelLine = partSim.part.HasModule<CModuleFuelLine>(); partSim.isFuelLine = partSim.part.HasModule<CModuleFuelLine>();
partSim.isFuelTank = partSim.part is FuelTank; partSim.isFuelTank = partSim.part is FuelTank;
partSim.isSepratron = partSim.IsSepratron(); partSim.isSepratron = partSim.IsSepratron();
partSim.isFairing = partSim.IsFairing(partSim.part); partSim.isFairing = partSim.IsFairing(partSim.part);
partSim.inverseStage = partSim.part.inverseStage; partSim.inverseStage = partSim.part.inverseStage;
//MonoBehaviour.print("inverseStage = " + inverseStage); //MonoBehaviour.print("inverseStage = " + inverseStage);
   
partSim.baseCost = partSim.part.GetCostDry(); partSim.baseCost = partSim.part.GetCostDry();
   
if (log != null) if (log != null)
{ {
log.buf.AppendLine("Parent part = " + (partSim.part.parent == null ? "null" : partSim.part.parent.partInfo.name)); log.buf.AppendLine("Parent part = " + (partSim.part.parent == null ? "null" : partSim.part.parent.partInfo.name));
log.buf.AppendLine("physicalSignificance = " + partSim.part.physicalSignificance); log.buf.AppendLine("physicalSignificance = " + partSim.part.physicalSignificance);
log.buf.AppendLine("PhysicsSignificance = " + partSim.part.PhysicsSignificance); log.buf.AppendLine("PhysicsSignificance = " + partSim.part.PhysicsSignificance);
} }
   
// Work out if the part should have no physical significance // Work out if the part should have no physical significance
// The root part is never "no physics" // The root part is never "no physics"
partSim.isNoPhysics = partSim.part.physicalSignificance == Part.PhysicalSignificance.NONE || partSim.isNoPhysics = partSim.part.physicalSignificance == Part.PhysicalSignificance.NONE ||
partSim.part.PhysicsSignificance == 1; partSim.part.PhysicsSignificance == 1;
   
if (partSim.part.HasModule<LaunchClamp>()) if (partSim.part.HasModule<LaunchClamp>())
{ {
partSim.realMass = 0d; partSim.realMass = 0d;
if (log != null) log.buf.AppendLine("Ignoring mass of launch clamp"); if (log != null) log.buf.AppendLine("Ignoring mass of launch clamp");
} }
else else
{ {
partSim.realMass = partSim.part.mass; partSim.realMass = partSim.part.mass;
if (log != null) log.buf.AppendLine("Using part.mass of " + partSim.part.mass); if (log != null) log.buf.AppendLine("Using part.mass of " + partSim.part.mass);
} }
   
if (partSim.isFairing) if (partSim.isFairing)
{ {
partSim.fairingMass = partSim.part.GetModuleMass((float)partSim.realMass); partSim.fairingMass = partSim.part.GetModuleMass((float)partSim.realMass);
} }
   
for (int i = 0; i < partSim.part.Resources.Count; i++) for (int i = 0; i < partSim.part.Resources.Count; i++)
{ {
PartResource resource = partSim.part.Resources[i]; PartResource resource = partSim.part.Resources[i];
   
// Make sure it isn't NaN as this messes up the part mass and hence most of the values // Make sure it isn't NaN as this messes up the part mass and hence most of the values
// This can happen if a resource capacity is 0 and tweakable // This can happen if a resource capacity is 0 and tweakable
if (!Double.IsNaN(resource.amount)) if (!Double.IsNaN(resource.amount))
{ {
if (log != null) if (log != null)
log.buf.AppendLine(resource.resourceName + " = " + resource.amount); log.buf.AppendLine(resource.resourceName + " = " + resource.amount);
   
partSim.resources.Add(resource.info.id, resource.amount); partSim.resources.Add(resource.info.id, resource.amount);
partSim.resourceFlowStates.Add(resource.info.id, resource.flowState ? 1 : 0); partSim.resourceFlowStates.Add(resource.info.id, resource.flowState ? 1 : 0);
} }
else else
{ {
if (log != null) log.buf.AppendLine(resource.resourceName + " is NaN. Skipping."); if (log != null) log.buf.AppendLine(resource.resourceName + " is NaN. Skipping.");
} }
} }
   
partSim.hasVessel = (partSim.part.vessel != null); partSim.hasVessel = (partSim.part.vessel != null);
partSim.isLanded = partSim.hasVessel && partSim.part.vessel.Landed; partSim.isLanded = partSim.hasVessel && partSim.part.vessel.Landed;
if (partSim.hasVessel) if (partSim.hasVessel)
{ {
partSim.vesselName = partSim.part.vessel.vesselName; partSim.vesselName = partSim.part.vessel.vesselName;
partSim.vesselType = partSim.part.vesselType; partSim.vesselType = partSim.part.vesselType;
} }
partSim.initialVesselName = partSim.part.initialVesselName; partSim.initialVesselName = partSim.part.initialVesselName;
   
partSim.hasMultiModeEngine = partSim.part.HasModule<MultiModeEngine>(); partSim.hasMultiModeEngine = partSim.part.HasModule<MultiModeEngine>();
partSim.hasModuleEngines = partSim.part.HasModule<ModuleEngines>(); partSim.hasModuleEngines = partSim.part.HasModule<ModuleEngines>();
   
partSim.isEngine = partSim.hasMultiModeEngine || partSim.hasModuleEngines; partSim.isEngine = partSim.hasMultiModeEngine || partSim.hasModuleEngines;
   
if (log != null) log.buf.AppendLine("Created " + partSim.name + ". Decoupled in stage " + partSim.decoupledInStage); if (log != null) log.buf.AppendLine("Created " + partSim.name + ". Decoupled in stage " + partSim.decoupledInStage);
   
return partSim; return partSim;
} }
   
public ResourceContainer ResourceDrains public ResourceContainer ResourceDrains
{ {
get get
{ {
return resourceDrains; return resourceDrains;
} }
} }
   
public ResourceContainer Resources public ResourceContainer Resources
{ {
get get
{ {
return resources; return resources;
} }
} }
   
public void CreateEngineSims(List<EngineSim> allEngines, double atmosphere, double mach, bool vectoredThrust, bool fullThrust, LogMsg log) public void CreateEngineSims(List<EngineSim> allEngines, double atmosphere, double mach, bool vectoredThrust, bool fullThrust, LogMsg log)
{ {
if (log != null) if (log != null)
{ {
log.buf.AppendLine("CreateEngineSims for " + this.name); log.buf.AppendLine("CreateEngineSims for " + this.name);
for (int i = 0; i < this.part.Modules.Count; i++) for (int i = 0; i < this.part.Modules.Count; i++)
{ {
PartModule partMod = this.part.Modules[i]; PartModule partMod = this.part.Modules[i];
log.buf.AppendLine("Module: " + partMod.moduleName); log.buf.AppendLine("Module: " + partMod.moduleName);
} }
} }
   
if (hasMultiModeEngine) if (hasMultiModeEngine)
{ {
// A multi-mode engine has multiple ModuleEngines but only one is active at any point // A multi-mode engine has multiple ModuleEngines but only one is active at any point
// The mode of the engine is the engineID of the ModuleEngines that is active // The mode of the engine is the engineID of the ModuleEngines that is active
string mode = part.GetModule<MultiModeEngine>().mode; string mode = part.GetModule<MultiModeEngine>().mode;
   
List<ModuleEngines> engines = part.GetModules<ModuleEngines>(); List<ModuleEngines> engines = part.GetModules<ModuleEngines>();
for (int i = 0; i < engines.Count; ++i) for (int i = 0; i < engines.Count; ++i)
{ {
ModuleEngines engine = engines[i]; ModuleEngines engine = engines[i];
if (engine.engineID == mode) if (engine.engineID == mode)
{ {
if (log != null) log.buf.AppendLine("Module: " + engine.moduleName); if (log != null) log.buf.AppendLine("Module: " + engine.moduleName);
   
Vector3 thrustvec = this.CalculateThrustVector(vectoredThrust ? engine.thrustTransforms : null, log); Vector3 thrustvec = this.CalculateThrustVector(vectoredThrust ? engine.thrustTransforms : null, log);
   
EngineSim engineSim = EngineSim.New( EngineSim engineSim = EngineSim.New(
this, this,
atmosphere, atmosphere,
(float)mach, (float)mach,
engine.maxFuelFlow, engine.maxFuelFlow,
engine.minFuelFlow, engine.minFuelFlow,
engine.thrustPercentage, engine.thrustPercentage,
thrustvec, thrustvec,
engine.atmosphereCurve, engine.atmosphereCurve,
engine.atmChangeFlow, engine.atmChangeFlow,
engine.useAtmCurve ? engine.atmCurve : null, engine.useAtmCurve ? engine.atmCurve : null,
engine.useVelCurve ? engine.velCurve : null, engine.useVelCurve ? engine.velCurve : null,
engine.currentThrottle, engine.currentThrottle,
engine.g, engine.g,
engine.throttleLocked || fullThrust, engine.throttleLocked || fullThrust,
engine.propellants, engine.propellants,
engine.isOperational, engine.isOperational,
engine.resultingThrust, engine.resultingThrust,
engine.thrustTransforms, engine.thrustTransforms,
log); log);
allEngines.Add(engineSim); allEngines.Add(engineSim);
} }
} }
} }
else if (hasModuleEngines) else if (hasModuleEngines)
{ {
List<ModuleEngines> engines = part.GetModules<ModuleEngines>(); List<ModuleEngines> engines = part.GetModules<ModuleEngines>();
for (int i = 0; i < engines.Count; ++i) for (int i = 0; i < engines.Count; ++i)
{ {
ModuleEngines engine = engines[i]; ModuleEngines engine = engines[i];
if (log != null) log.buf.AppendLine("Module: " + engine.moduleName); if (log != null) log.buf.AppendLine("Module: " + engine.moduleName);
   
Vector3 thrustvec = this.CalculateThrustVector(vectoredThrust ? engine.thrustTransforms : null, log); Vector3 thrustvec = this.CalculateThrustVector(vectoredThrust ? engine.thrustTransforms : null, log);
   
EngineSim engineSim = EngineSim.New( EngineSim engineSim = EngineSim.New(
this, this,
atmosphere, atmosphere,
(float)mach, (float)mach,
engine.maxFuelFlow, engine.maxFuelFlow,
engine.minFuelFlow, engine.minFuelFlow,
engine.thrustPercentage, engine.thrustPercentage,
thrustvec, thrustvec,
engine.atmosphereCurve, engine.atmosphereCurve,
engine.atmChangeFlow, engine.atmChangeFlow,
engine.useAtmCurve ? engine.atmCurve : null, engine.useAtmCurve ? engine.atmCurve : null,
engine.useVelCurve ? engine.velCurve : null, engine.useVelCurve ? engine.velCurve : null,
engine.currentThrottle, engine.currentThrottle,
engine.g, engine.g,
engine.throttleLocked || fullThrust, engine.throttleLocked || fullThrust,
engine.propellants, engine.propellants,
engine.isOperational, engine.isOperational,
engine.resultingThrust, engine.resultingThrust,
engine.thrustTransforms, engine.thrustTransforms,
log); log);
allEngines.Add(engineSim); allEngines.Add(engineSim);
} }
} }
   
if (log != null) if (log != null)
{ {
log.Flush(); log.Flush();
} }
} }
   
public int DecouplerCount() public int DecouplerCount()
{ {
int count = 0; int count = 0;
PartSim partSim = this; PartSim partSim = this;
while (partSim != null) while (partSim != null)
{ {
if (partSim.isDecoupler) if (partSim.isDecoupler)
{ {
count++; count++;
} }
   
partSim = partSim.parent; partSim = partSim.parent;
} }
return count; return count;
} }
   
public void DrainResources(double time) public void DrainResources(double time)
{ {
//MonoBehaviour.print("DrainResources(" + name + ":" + partId + ", " + time + ")"); //MonoBehaviour.print("DrainResources(" + name + ":" + partId + ", " + time + ")");
for (int i = 0; i < resourceDrains.Types.Count; ++i) for (int i = 0; i < resourceDrains.Types.Count; ++i)
{ {
int type = resourceDrains.Types[i]; int type = resourceDrains.Types[i];
   
//MonoBehaviour.print("draining " + (time * resourceDrains[type]) + " " + ResourceContainer.GetResourceName(type)); //MonoBehaviour.print("draining " + (time * resourceDrains[type]) + " " + ResourceContainer.GetResourceName(type));
resources.Add(type, -time * resourceDrains[type]); resources.Add(type, -time * resourceDrains[type]);
//MonoBehaviour.print(ResourceContainer.GetResourceName(type) + " left = " + resources[type]); //MonoBehaviour.print(ResourceContainer.GetResourceName(type) + " left = " + resources[type]);
} }
} }
   
public String DumpPartAndParentsToBuffer(StringBuilder buffer, String prefix) public String DumpPartAndParentsToBuffer(StringBuilder buffer, String prefix)
{ {
if (parent != null) if (parent != null)
{ {
prefix = parent.DumpPartAndParentsToBuffer(buffer, prefix) + " "; prefix = parent.DumpPartAndParentsToBuffer(buffer, prefix) + " ";
} }
   
DumpPartToBuffer(buffer, prefix); DumpPartToBuffer(buffer, prefix);
   
return prefix; return prefix;
} }
   
public void DumpPartToBuffer(StringBuilder buffer, String prefix, List<PartSim> allParts = null) public void DumpPartToBuffer(StringBuilder buffer, String prefix, List<PartSim> allParts = null)
{ {
buffer.Append(prefix); buffer.Append(prefix);
buffer.Append(name); buffer.Append(name);
buffer.AppendFormat(":[id = {0:d}, decouple = {1:d}, invstage = {2:d}", partId, decoupledInStage, inverseStage); buffer.AppendFormat(":[id = {0:d}, decouple = {1:d}, invstage = {2:d}", partId, decoupledInStage, inverseStage);
   
//buffer.AppendFormat(", vesselName = '{0}'", vesselName); //buffer.AppendFormat(", vesselName = '{0}'", vesselName);
//buffer.AppendFormat(", vesselType = {0}", SimManager.GetVesselTypeString(vesselType)); //buffer.AppendFormat(", vesselType = {0}", SimManager.GetVesselTypeString(vesselType));
//buffer.AppendFormat(", initialVesselName = '{0}'", initialVesselName); //buffer.AppendFormat(", initialVesselName = '{0}'", initialVesselName);
   
buffer.AppendFormat(", isNoPhys = {0}", isNoPhysics); buffer.AppendFormat(", isNoPhys = {0}", isNoPhysics);
buffer.AppendFormat(", baseMass = {0}", baseMass); buffer.AppendFormat(", baseMass = {0}", baseMass);
buffer.AppendFormat(", baseMassForCoM = {0}", baseMassForCoM); buffer.AppendFormat(", baseMassForCoM = {0}", baseMassForCoM);
   
buffer.AppendFormat(", fuelCF = {0}", fuelCrossFeed); buffer.AppendFormat(", fuelCF = {0}", fuelCrossFeed);
buffer.AppendFormat(", noCFNKey = '{0}'", noCrossFeedNodeKey); buffer.AppendFormat(", noCFNKey = '{0}'", noCrossFeedNodeKey);
   
buffer.AppendFormat(", isSep = {0}", isSepratron); buffer.AppendFormat(", isSep = {0}", isSepratron);
   
for (int i = 0; i < resources.Types.Count; i++) for (int i = 0; i < resources.Types.Count; i++)
{ {
int type = resources.Types[i]; int type = resources.Types[i];
buffer.AppendFormat(", {0} = {1:g6}", ResourceContainer.GetResourceName(type), resources[type]); buffer.AppendFormat(", {0} = {1:g6}", ResourceContainer.GetResourceName(type), resources[type]);
} }
   
if (attachNodes.Count > 0) if (attachNodes.Count > 0)
{ {
buffer.Append(", attached = <"); buffer.Append(", attached = <");
attachNodes[0].DumpToBuffer(buffer); attachNodes[0].DumpToBuffer(buffer);
for (int i = 1; i < attachNodes.Count; i++) for (int i = 1; i < attachNodes.Count; i++)
{ {
buffer.Append(", "); buffer.Append(", ");
attachNodes[i].DumpToBuffer(buffer); attachNodes[i].DumpToBuffer(buffer);
} }
buffer.Append(">"); buffer.Append(">");
} }
   
// Add more info here // Add more info here
   
buffer.Append("]\n"); buffer.Append("]\n");
   
if (allParts != null) if (allParts != null)
{ {
String newPrefix = prefix + " "; String newPrefix = prefix + " ";
for (int i = 0; i < allParts.Count; i++) for (int i = 0; i < allParts.Count; i++)
{ {
PartSim partSim = allParts[i]; PartSim partSim = allParts[i];
if (partSim.parent == this) if (partSim.parent == this)
partSim.DumpPartToBuffer(buffer, newPrefix, allParts); partSim.DumpPartToBuffer(buffer, newPrefix, allParts);
} }
} }
} }
   
public bool EmptyOf(HashSet<int> types) public bool EmptyOf(HashSet<int> types)
{ {
foreach (int type in types) foreach (int type in types)
{ {
if (resources.HasType(type) && resourceFlowStates[type] != 0 && resources[type] > SimManager.RESOURCE_PART_EMPTY_THRESH) if (resources.HasType(type) && resourceFlowStates[type] != 0 && resources[type] > SimManager.RESOURCE_PART_EMPTY_THRESH)
return false; return false;
} }
   
return true; return true;
} }
   
public double GetMass(int currentStage, bool forCoM = false) public double GetMass(int currentStage, bool forCoM = false)
{ {
if (decoupledInStage >= currentStage) if (decoupledInStage >= currentStage)
return 0d; return 0d;
   
double mass = forCoM ? baseMassForCoM : baseMass; double mass = forCoM ? baseMassForCoM : baseMass;
   
for (int i = 0; i < resources.Types.Count; ++i) for (int i = 0; i < resources.Types.Count; ++i)
{ {
mass += resources.GetResourceMass(resources.Types[i]); mass += resources.GetResourceMass(resources.Types[i]);
} }
   
if (hasVessel == false && isFairing && currentStage > inverseStage) if (hasVessel == false && isFairing && currentStage > inverseStage)
{ {
mass += fairingMass; mass += fairingMass;
} }
else if (hasVessel && isFairing && currentStage <= inverseStage) else if (hasVessel && isFairing && currentStage <= inverseStage)
{ {
mass -= fairingMass; mass -= fairingMass;
} }
   
return mass; return mass;
} }
   
public double GetCost(int currentStage) public double GetCost(int currentStage)
{ {
if (decoupledInStage >= currentStage) if (decoupledInStage >= currentStage)
return 0d; return 0d;
   
double cost = baseCost; double cost = baseCost;
   
for (int i = 0; i < resources.Types.Count; ++i) for (int i = 0; i < resources.Types.Count; ++i)
{ {
cost += resources.GetResourceCost(resources.Types[i]); cost += resources.GetResourceCost(resources.Types[i]);
} }
   
return cost; return cost;
} }
   
public void ReleasePart() public void ReleasePart()
{ {
this.part = null; this.part = null;
} }
   
// All functions below this point must not rely on the part member (it may be null) // All functions below this point must not rely on the part member (it may be null)
// //
   
public void GetSourceSet(int type, List<PartSim> allParts, HashSet<PartSim> visited, HashSet<PartSim> allSources, LogMsg log, String indent) public void GetSourceSet(int type, List<PartSim> allParts, HashSet<PartSim> visited, HashSet<PartSim> allSources, LogMsg log, String indent)
{ {
if (log != null) if (log != null)
{ {
log.buf.AppendLine(indent + "GetSourceSet(" + ResourceContainer.GetResourceName(type) + ") for " + name + ":" + partId); log.buf.AppendLine(indent + "GetSourceSet(" + ResourceContainer.GetResourceName(type) + ") for " + name + ":" + partId);
indent += " "; indent += " ";
} }
   
// Rule 1: Each part can be only visited once, If it is visited for second time in particular search it returns as is. // Rule 1: Each part can be only visited once, If it is visited for second time in particular search it returns as is.
if (visited.Contains(this)) if (visited.Contains(this))
{ {
if (log != null) log.buf.AppendLine(indent + "Returning empty set, already visited (" + name + ":" + partId + ")"); if (log != null) log.buf.AppendLine(indent + "Returning empty set, already visited (" + name + ":" + partId + ")");
return; return;
} }
   
if (log != null) log.buf.AppendLine(indent + "Adding this to visited"); if (log != null) log.buf.AppendLine(indent + "Adding this to visited");
   
visited.Add(this); visited.Add(this);
   
// Rule 2: Part performs scan on start of every fuel pipe ending in it. This scan is done in order in which pipes were installed. // Rule 2: Part performs scan on start of every fuel pipe ending in it. This scan is done in order in which pipes were installed.
// Then it makes an union of fuel tank sets each pipe scan returned. If the resulting list is not empty, it is returned as result. // Then it makes an union of fuel tank sets each pipe scan returned. If the resulting list is not empty, it is returned as result.
//MonoBehaviour.print("for each fuel line"); //MonoBehaviour.print("for each fuel line");
   
int lastCount = allSources.Count; int lastCount = allSources.Count;
   
for (int i = 0; i < this.fuelTargets.Count; i++) for (int i = 0; i < this.fuelTargets.Count; i++)
{ {
PartSim partSim = this.fuelTargets[i]; PartSim partSim = this.fuelTargets[i];
if (partSim != null) if (partSim != null)
{ {
if (visited.Contains(partSim)) if (visited.Contains(partSim))
{ {
if (log != null) log.buf.AppendLine(indent + "Fuel target already visited, skipping (" + partSim.name + ":" + partSim.partId + ")"); if (log != null) log.buf.AppendLine(indent + "Fuel target already visited, skipping (" + partSim.name + ":" + partSim.partId + ")");
} }
else else
{ {
if (log != null) log.buf.AppendLine(indent + "Adding fuel target as source (" + partSim.name + ":" + partSim.partId + ")"); if (log != null) log.buf.AppendLine(indent + "Adding fuel target as source (" + partSim.name + ":" + partSim.partId + ")");
   
partSim.GetSourceSet(type, allParts, visited, allSources, log, indent); partSim.GetSourceSet(type, allParts, visited, allSources, log, indent);
} }
} }
} }
   
if (allSources.Count > lastCount) if (allSources.Count > lastCount)
{ {
if (log != null) log.buf.AppendLine(indent + "Returning " + (allSources.Count - lastCount) + " fuel target sources (" + this.name + ":" + this.partId + ")"); if (log != null) log.buf.AppendLine(indent + "Returning " + (allSources.Count - lastCount) + " fuel target sources (" + this.name + ":" + this.partId + ")");
return; return;
} }
   
   
// Rule 3: This rule has been removed and merged with rules 4 and 7 to fix issue with fuel tanks with disabled crossfeed // Rule 3: This rule has been removed and merged with rules 4 and 7 to fix issue with fuel tanks with disabled crossfeed
   
// Rule 4: Part performs scan on each of its axially mounted neighbors. // Rule 4: Part performs scan on each of its axially mounted neighbors.
// Couplers (bicoupler, tricoupler, ...) are an exception, they only scan one attach point on the single attachment side, // Couplers (bicoupler, tricoupler, ...) are an exception, they only scan one attach point on the single attachment side,
// skip the points on the side where multiple points are. [Experiment] // skip the points on the side where multiple points are. [Experiment]
// Again, the part creates union of scan lists from each of its neighbor and if it is not empty, returns this list. // Again, the part creates union of scan lists from each of its neighbor and if it is not empty, returns this list.
// The order in which mount points of a part are scanned appears to be fixed and defined by the part specification file. [Experiment] // The order in which mount points of a part are scanned appears to be fixed and defined by the part specification file. [Experiment]
if (fuelCrossFeed) if (fuelCrossFeed)
{ {
lastCount = allSources.Count; lastCount = allSources.Count;
//MonoBehaviour.print("for each attach node"); //MonoBehaviour.print("for each attach node");
for (int i = 0; i < this.attachNodes.Count; i++) for (int i = 0; i < this.attachNodes.Count; i++)
{ {
AttachNodeSim attachSim = this.attachNodes[i]; AttachNodeSim attachSim = this.attachNodes[i];
if (attachSim.attachedPartSim != null) if (attachSim.attachedPartSim != null)
{ {
if (attachSim.nodeType == AttachNode.NodeType.Stack) if (attachSim.nodeType == AttachNode.NodeType.Stack)
{ {
if ( if ((string.IsNullOrEmpty(noCrossFeedNodeKey) == false && attachSim.id.Contains(noCrossFeedNodeKey)) == false)
!(this.noCrossFeedNodeKey != null && this.noCrossFeedNodeKey.Length > 0 &&  
attachSim.id.Contains(this.noCrossFeedNodeKey)))  
{ {
if (visited.Contains(attachSim.attachedPartSim)) if (visited.Contains(attachSim.attachedPartSim))
{ {
if (log != null) log.buf.AppendLine(indent + "Attached part already visited, skipping (" + attachSim.attachedPartSim.name + ":" + attachSim.attachedPartSim.partId + ")"); if (log != null) log.buf.AppendLine(indent + "Attached part already visited, skipping (" + attachSim.attachedPartSim.name + ":" + attachSim.attachedPartSim.partId + ")");
} }
else else
{ {
if (log != null) log.buf.AppendLine(indent + "Adding attached part as source (" + attachSim.attachedPartSim.name + ":" + attachSim.attachedPartSim.partId + ")"); if (log != null) log.buf.AppendLine(indent + "Adding attached part as source (" + attachSim.attachedPartSim.name + ":" + attachSim.attachedPartSim.partId + ")");
   
attachSim.attachedPartSim.GetSourceSet(type, allParts, visited, allSources, log, indent); attachSim.attachedPartSim.GetSourceSet(type, allParts, visited, allSources, log, indent);
} }
} }
} }
} }
} }
   
if (allSources.Count > lastCount) if (allSources.Count > lastCount)
{ {
if (log != null) log.buf.AppendLine(indent + "Returning " + (allSources.Count - lastCount) + " attached sources (" + this.name + ":" + this.partId + ")"); if (log != null) log.buf.AppendLine(indent + "Returning " + (allSources.Count - lastCount) + " attached sources (" + this.name + ":" + this.partId + ")");
return; return;
} }
} }
   
// Rule 5: If the part is fuel container for searched type of fuel (i.e. it has capability to contain that type of fuel and the fuel // Rule 5: If the part is fuel container for searched type of fuel (i.e. it has capability to contain that type of fuel and the fuel
// type was not disabled [Experiment]) and it contains fuel, it returns itself. // type was not disabled [Experiment]) and it contains fuel, it returns itself.
// Rule 6: If the part is fuel container for searched type of fuel (i.e. it has capability to contain that type of fuel and the fuel // Rule 6: If the part is fuel container for searched type of fuel (i.e. it has capability to contain that type of fuel and the fuel
// type was not disabled) but it does not contain the requested fuel, it returns empty list. [Experiment] // type was not disabled) but it does not contain the requested fuel, it returns empty list. [Experiment]
if (resources.HasType(type) && resourceFlowStates[type] != 0) if (resources.HasType(type) && resourceFlowStates[type] > 0.0)
{ {
if (resources[type] > SimManager.RESOURCE_MIN) if (resources[type] > SimManager.RESOURCE_MIN)
{ {
allSources.Add(this); allSources.Add(this);
   
if (log != null) log.buf.AppendLine(indent + "Returning enabled tank as only source (" + name + ":" + partId + ")"); if (log != null) log.buf.AppendLine(indent + "Returning enabled tank as only source (" + name + ":" + partId + ")");
} }
   
return; return;
} }
else else
{ {
if (log != null) log.buf.AppendLine(indent + "Not fuel tank or disabled. HasType = " + resources.HasType(type) + " FlowState = " + resourceFlowStates[type]); if (log != null) log.buf.AppendLine(indent + "Not fuel tank or disabled. HasType = " + resources.HasType(type) + " FlowState = " + resourceFlowStates[type]);
} }
   
// Rule 7: If the part is radially attached to another part and it is child of that part in the ship's tree structure, it scans its // Rule 7: If the part is radially attached to another part and it is child of that part in the ship's tree structure, it scans its
// parent and returns whatever the parent scan returned. [Experiment] [Experiment] // parent and returns whatever the parent scan returned. [Experiment] [Experiment]
if (parent != null && parentAttach == AttachModes.SRF_ATTACH) if (parent != null && parentAttach == AttachModes.SRF_ATTACH)
{ {
if (fuelCrossFeed) if (fuelCrossFeed)
{ {
if (visited.Contains(parent)) if (visited.Contains(parent))
{ {
if (log != null) log.buf.AppendLine(indent + "Parent part already visited, skipping (" + parent.name + ":" + parent.partId + ")"); if (log != null) log.buf.AppendLine(indent + "Parent part already visited, skipping (" + parent.name + ":" + parent.partId + ")");
} }
else else
{ {
lastCount = allSources.Count; lastCount = allSources.Count;
this.parent.GetSourceSet(type, allParts, visited, allSources, log, indent); this.parent.GetSourceSet(type, allParts, visited, allSources, log, indent);
if (allSources.Count > lastCount) if (allSources.Count > lastCount)
{ {
if (log != null) log.buf.AppendLine(indent + "Returning " + (allSources.Count - lastCount) + " parent sources (" + this.name + ":" + this.partId + ")"); if (log != null) log.buf.AppendLine(indent + "Returning " + (allSources.Count - lastCount) + " parent sources (" + this.name + ":" + this.partId + ")");
return; return;
} }
} }
} }
} }
   
// Rule 8: If all preceding rules failed, part returns empty list. // Rule 8: If all preceding rules failed, part returns empty list.
if (log != null) log.buf.AppendLine(indent + "Returning empty set, no sources found (" + name + ":" + partId + ")"); if (log != null) log.buf.AppendLine(indent + "Returning empty set, no sources found (" + name + ":" + partId + ")");
   
return; return;
} }
   
public double GetStartMass() public double GetStartMass()
{ {
return startMass; return startMass;
} }
   
public void RemoveAttachedParts(HashSet<PartSim> partSims) public void RemoveAttachedParts(HashSet<PartSim> partSims)
{ {
// Loop through the attached parts // Loop through the attached parts
for (int i = 0; i < this.attachNodes.Count; i++) for (int i = 0; i < this.attachNodes.Count; i++)
{ {
AttachNodeSim attachSim = this.attachNodes[i]; AttachNodeSim attachSim = this.attachNodes[i];
// If the part is in the set then "remove" it by clearing the PartSim reference // If the part is in the set then "remove" it by clearing the PartSim reference
if (partSims.Contains(attachSim.attachedPartSim)) if (partSims.Contains(attachSim.attachedPartSim))
{ {
attachSim.attachedPartSim = null; attachSim.attachedPartSim = null;
} }
} }
   
// Loop through the fuel targets (fuel line sources) // Loop through the fuel targets (fuel line sources)
for (int i = 0; i < this.fuelTargets.Count; i++) for (int i = 0; i < this.fuelTargets.Count; i++)
{ {
PartSim fuelTargetSim = this.fuelTargets[i]; PartSim fuelTargetSim = this.fuelTargets[i];
// If the part is in the set then "remove" it by clearing the PartSim reference // If the part is in the set then "remove" it by clearing the PartSim reference
if (fuelTargetSim != null && partSims.Contains(fuelTargetSim)) if (fuelTargetSim != null && partSims.Contains(fuelTargetSim))
{ {
this.fuelTargets[i] = null; this.fuelTargets[i] = null;
} }
} }
} }
   
public void SetupAttachNodes(Dictionary<Part, PartSim> partSimLookup, LogMsg log) public void SetupAttachNodes(Dictionary<Part, PartSim> partSimLookup, LogMsg log)
{ {
if (log != null) log.buf.AppendLine("SetupAttachNodes for " + name + ":" + partId + ""); if (log != null) log.buf.AppendLine("SetupAttachNodes for " + name + ":" + partId + "");
   
attachNodes.Clear(); attachNodes.Clear();
   
for (int i = 0; i < part.attachNodes.Count; ++i) for (int i = 0; i < part.attachNodes.Count; ++i)
{ {
AttachNode attachNode = part.attachNodes[i]; AttachNode attachNode = part.attachNodes[i];
   
if (log != null) log.buf.AppendLine("AttachNode " + attachNode.id + " = " + (attachNode.attachedPart != null ? attachNode.attachedPart.partInfo.name : "null")); if (log != null) log.buf.AppendLine("AttachNode " + attachNode.id + " = " + (attachNode.attachedPart != null ? attachNode.attachedPart.partInfo.name : "null"));
   
if (attachNode.attachedPart != null && attachNode.id != "Strut") if (attachNode.attachedPart != null && attachNode.id != "Strut")
{ {
PartSim attachedSim; PartSim attachedSim;
if (partSimLookup.TryGetValue(attachNode.attachedPart, out attachedSim)) if (partSimLookup.TryGetValue(attachNode.attachedPart, out attachedSim))
{ {
if (log != null) log.buf.AppendLine("Adding attached node " + attachedSim.name + ":" + attachedSim.partId + ""); if (log != null) log.buf.AppendLine("Adding attached node " + attachedSim.name + ":" + attachedSim.partId + "");
   
attachNodes.Add(AttachNodeSim.New(attachedSim, attachNode.id, attachNode.nodeType)); attachNodes.Add(AttachNodeSim.New(attachedSim, attachNode.id, attachNode.nodeType));
} }
else else
{ {
if (log != null) log.buf.AppendLine("No PartSim for attached part (" + attachNode.attachedPart.partInfo.name + ")"); if (log != null) log.buf.AppendLine("No PartSim for attached part (" + attachNode.attachedPart.partInfo.name + ")");
} }
} }
} }
   
for (int i = 0; i < part.fuelLookupTargets.Count; ++i) for (int i = 0; i < part.fuelLookupTargets.Count; ++i)
{ {
Part p = part.fuelLookupTargets[i]; Part p = part.fuelLookupTargets[i];
   
if (p != null) if (p != null)
{ {
PartSim targetSim; PartSim targetSim;
if (partSimLookup.TryGetValue(p, out targetSim)) if (partSimLookup.TryGetValue(p, out targetSim))
{ {
if (log != null) log.buf.AppendLine("Fuel target: " + targetSim.name + ":" + targetSim.partId); if (log != null) log.buf.AppendLine("Fuel target: " + targetSim.name + ":" + targetSim.partId);
   
fuelTargets.Add(targetSim); fuelTargets.Add(targetSim);
} }
else else
{ {
if (log != null) log.buf.AppendLine("No PartSim for fuel target (" + p.name + ")"); if (log != null) log.buf.AppendLine("No PartSim for fuel target (" + p.name + ")");
} }
} }
} }
} }
   
public void SetupParent(Dictionary<Part, PartSim> partSimLookup, LogMsg log) public void SetupParent(Dictionary<Part, PartSim> partSimLookup, LogMsg log)
{ {
if (part.parent != null) if (part.parent != null)
{ {
parent = null; parent = null;
if (partSimLookup.TryGetValue(part.parent, out parent)) if (partSimLookup.TryGetValue(part.parent, out parent))
{ {
if (log != null) log.buf.AppendLine("Parent part is " + parent.name + ":" + parent.partId); if (log != null) log.buf.AppendLine("Parent part is " + parent.name + ":" + parent.partId);
} }
else else
{ {
if (log != null) log.buf.AppendLine("No PartSim for parent part (" + part.parent.partInfo.name + ")"); if (log != null) log.buf.AppendLine("No PartSim for parent part (" + part.parent.partInfo.name + ")");
} }
} }
} }
   
public double TimeToDrainResource() public double TimeToDrainResource()
{ {
//MonoBehaviour.print("TimeToDrainResource(" + name + ":" + partId + ")"); //MonoBehaviour.print("TimeToDrainResource(" + name + ":" + partId + ")");
double time = double.MaxValue; double time = double.MaxValue;
   
for (int i = 0; i < resourceDrains.Types.Count; ++i) for (int i = 0; i < resourceDrains.Types.Count; ++i)
{ {
int type = resourceDrains.Types[i]; int type = resourceDrains.Types[i];
   
if (resourceDrains[type] > 0) if (resourceDrains[type] > 0)
{ {
time = Math.Min(time, resources[type] / resourceDrains[type]); time = Math.Min(time, resources[type] / resourceDrains[type]);
//MonoBehaviour.print("type = " + ResourceContainer.GetResourceName(type) + " amount = " + resources[type] + " rate = " + resourceDrains[type] + " time = " + time); //MonoBehaviour.print("type = " + ResourceContainer.GetResourceName(type) + " amount = " + resources[type] + " rate = " + resourceDrains[type] + " time = " + time);
} }
} }
   
//if (time < double.MaxValue) //if (time < double.MaxValue)
// MonoBehaviour.print("TimeToDrainResource(" + name + ":" + partId + ") = " + time); // MonoBehaviour.print("TimeToDrainResource(" + name + ":" + partId + ") = " + time);
return time; return time;
} }
   
private Vector3 CalculateThrustVector(List<Transform> thrustTransforms, LogMsg log) private Vector3 CalculateThrustVector(List<Transform> thrustTransforms, LogMsg log)
{ {
if (thrustTransforms == null) if (thrustTransforms == null)
{ {
return Vector3.forward; return Vector3.forward;
} }
   
Vector3 thrustvec = Vector3.zero; Vector3 thrustvec = Vector3.zero;
for (int i = 0; i < thrustTransforms.Count; ++i) for (int i = 0; i < thrustTransforms.Count; ++i)
{ {
Transform trans = thrustTransforms[i]; Transform trans = thrustTransforms[i];
   
if (log != null) log.buf.AppendFormat("Transform = ({0:g6}, {1:g6}, {2:g6}) length = {3:g6}\n", trans.forward.x, trans.forward.y, trans.forward.z, trans.forward.magnitude); if (log != null) log.buf.AppendFormat("Transform = ({0:g6}, {1:g6}, {2:g6}) length = {3:g6}\n", trans.forward.x, trans.forward.y, trans.forward.z, trans.forward.magnitude);
   
thrustvec -= trans.forward; thrustvec -= trans.forward;
} }
   
if (log != null) log.buf.AppendFormat("ThrustVec = ({0:g6}, {1:g6}, {2:g6}) length = {3:g6}\n", thrustvec.x, thrustvec.y, thrustvec.z, thrustvec.magnitude); if (log != null) log.buf.AppendFormat("ThrustVec = ({0:g6}, {1:g6}, {2:g6}) length = {3:g6}\n", thrustvec.x, thrustvec.y, thrustvec.z, thrustvec.magnitude);
   
thrustvec.Normalize(); thrustvec.Normalize();
   
if (log != null) log.buf.AppendFormat("ThrustVecN = ({0:g6}, {1:g6}, {2:g6}) length = {3:g6}\n", thrustvec.x, thrustvec.y, thrustvec.z, thrustvec.magnitude); if (log != null) log.buf.AppendFormat("ThrustVecN = ({0:g6}, {1:g6}, {2:g6}) length = {3:g6}\n", thrustvec.x, thrustvec.y, thrustvec.z, thrustvec.magnitude);
   
return thrustvec; return thrustvec;
} }
   
private int DecoupledInStage(Part thePart, int stage = -1) private int DecoupledInStage(Part thePart, int stage = -1)
{ {
if (IsDecoupler(thePart) && thePart.inverseStage > stage) if (IsDecoupler(thePart) && thePart.inverseStage > stage)
stage = thePart.inverseStage; stage = thePart.inverseStage;
   
if (thePart.parent != null) if (thePart.parent != null)
stage = DecoupledInStage(thePart.parent, stage); stage = DecoupledInStage(thePart.parent, stage);
   
return stage; return stage;
} }
   
private bool IsActiveDecoupler(Part thePart) private bool IsActiveDecoupler(Part thePart)
{ {
return thePart.FindModulesImplementing<ModuleDecouple>().Any(mod => !mod.isDecoupled) || return thePart.FindModulesImplementing<ModuleDecouple>().Any(mod => !mod.isDecoupled) ||
thePart.FindModulesImplementing<ModuleAnchoredDecoupler>().Any(mod => !mod.isDecoupled); thePart.FindModulesImplementing<ModuleAnchoredDecoupler>().Any(mod => !mod.isDecoupled);
} }
   
private bool IsDecoupler(Part thePart) private bool IsDecoupler(Part thePart)
{ {
return thePart.HasModule<ModuleDecouple>() || return thePart.HasModule<ModuleDecouple>() ||
thePart.HasModule<ModuleAnchoredDecoupler>(); thePart.HasModule<ModuleAnchoredDecoupler>();
} }
   
private bool IsFairing(Part thePart) private bool IsFairing(Part thePart)
{ {
return thePart.HasModule<ModuleProceduralFairing>(); return thePart.HasModule<ModuleProceduralFairing>();
} }
   
private bool IsSepratron() private bool IsSepratron()
{ {
if (!part.ActivatesEvenIfDisconnected) if (!part.ActivatesEvenIfDisconnected)
{ {
return false; return false;
} }
   
if (part is SolidRocket) if (part is SolidRocket)
{ {
return true; return true;
} }
   
IEnumerable<ModuleEngines> modList = part.Modules.OfType<ModuleEngines>(); IEnumerable<ModuleEngines> modList = part.Modules.OfType<ModuleEngines>();
if (modList.Count() == 0) if (modList.Count() == 0)
{ {
return false; return false;
} }
   
if (modList.First().throttleLocked) if (modList.First().throttleLocked)
{ {
return true; return true;
} }
   
return false; return false;
} }
} }
} }
 Binary files a/Output/KerbalEngineer/KerbalEngineer.dll and b/Output/KerbalEngineer/KerbalEngineer.dll differ
{ {
"NAME":"Kerbal Engineer Redux", "NAME":"Kerbal Engineer Redux",
"URL":"http://ksp-avc.cybutek.net/version.php?id=6", "URL":"http://ksp-avc.cybutek.net/version.php?id=6",
"VERSION": "VERSION":
{ {
"MAJOR":1, "MAJOR":1,
"MINOR":0, "MINOR":0,
"PATCH":18, "PATCH":19,
"BUILD":0 "BUILD":2
}, },
"KSP_VERSION": "KSP_VERSION":
{ {
"MAJOR":1, "MAJOR":1,
"MINOR":0, "MINOR":0,
"PATCH":4 "PATCH":5
} }
} }