Merge branch 'seybur-master' #43
Merge branch 'seybur-master' #43

 Binary files a/Assets/CurseLogo.png and b/Assets/CurseLogo.png differ
 Binary files a/Assets/CurseLogo.psd and b/Assets/CurseLogo.psd differ
1.0.9.3 1.0.17.1
  Fixed: Synched the minimum simulation time sliders and stopped them from snapping back after 999ms. (saybur)
   
  1.0.17.0
  Added: 'Mach Number' readout under the 'Surface' category and included it on the default surface HUD.
  Added: Stock sections in the Flight Engineer can now become HUDs.
  Added 'Thermal' readouts category including:
  Internal Flux
  Convection Flux
  Radiation Flux
  Critical Part Name
  Critical Part Temperature
  Critical Part Skin Temperature
  Critical Part Thermal Percentage of Max Temperature
  Hottest Part Name
  Hottest Part Temperature
  Hottest Part Skin Temperature
  Coldest Part Name
  Coldest Part Temperature
  Coldest Part Skin Temperature
   
  Changed: Mach on the Build Engineer now accurate to 2 decimal places.
  Changed: Max mach in the Build Engineer defaults to 1.00 even when no jet engines are present.
  Changed: Increased eccentricity readout to 5 decimal places.
  Changed: Implemented Sarbian's object pooling.
  Changed: The default selected body is now assigned via 'Planitarium.Home'.
  Changed: HUDs to clamp fully inside the screen instead of allowing them to run off the edge by a certain amount.
  Fixed: Physically insignificant part mass is now associated with the parent part.
  Fixed: Longitude and Latitude readouts now use a KER formatter instead of Squad's incorrect implementation.
  Fixed: Possible null reference in the Rendezvous Processor.
  Fixed: Fairing mass issues introduced with regards to simulation changes.
  Fixed: Use of per-propellant fuel flow mode override.
  Fixed: Burn times calculated for jet engines.
  Fixed: Thrust issues introduced with Sarbian's simulation alterations.
  Fixed: Issue where HUDs positioned close to the top/bottom of the screen could be pushed out of position.
   
  1.0.16.6, 02-05-15
  Fixed: Separately staged fairing mass jettisons are now calculated in the editor.
   
  1.0.16.5, 02-05-2015
  Fixed: Delta-V not being correctly calculated.
  Changed: Editor locking now uses the InputLockManager.
   
  1.0.16.4, 01-05-2015
  Fixed: Physically insignificant part mass is now accounted for.
  Changed: Module mass accounted for as it now makes its way onto the launch pad (e.g. fairings).
   
  Various optimisations:
  Object pooling.
  Removed LINQ expressions.
  Converted foreach to for loops.
   
  1.0.16.3, 27-04-2015
  Fixed issue with the toolbar icons not being created.
  Removed superfluous 'm/s' on the mach slider in the build engineer.
   
  1.0.16.2, 27-04-2015
  Changed the atmospheric slider on the build engineer to default to 0km when changing bodies.
   
  1.0.16.1, 26-04-2015, KSP Build #828
  Merged Sarbian's mach adjustments.
  Fixed bugs relating to thrust and atmosphere/velocity curves.
  Changed the atmospheric slider on the Build Engineer to work based on altitude.
  Changed the atmospheric slider to clamp to the maximum altitude for the selected body.
  Changed the velocity slider to clamp to the maximum usable mach value for the current vessel.
   
  1.0.16.0, 25-04-2015, KSP Build #821
  Fixed errors relating to KSP 1.0 update.
  Fixed fuel simulation to account for new thrust system.
  Fixed atmospheric engines to use the new velocity curve.
  Fixed atmospheric readouts to work with the new atmospheric model.
   
  1.0.15.2, 13-02-2015
  Padishar's Fixes:
  Fixed: Calculation of per-stage resource mass.
   
  1.0.15.1, 13-02-2015
  Rebuild
   
  1.0.15.0, 08-02-2015
  Padishar's Fixes:
  Added: Support KIDS ISP thrust correction.
  Fixed: Log spam for stage priority mode.
  Fixed: Locked tanks preventing simulation from staging.
  Fixed: No flow and all vessel modes to respect flow states.
   
  1.0.14.1, 28-12-2014
  Fixed: Missing texture on the ER-7500 model.
   
  1.0.14.0, 28-12-2014
  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.
  - Tracking station level 3 enables Flight Engineer everywhere.
   
  Added: New readouts to the orbital category:
  - Mean Anomaly at Epoc
   
  Added: New readouts to the miscellaneous category:
  - System Time
   
  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.
  Fixed: Bug where STAGE_PRIORITY_FLOW resources would not be corrently disabled/enabled.
  Fixed: Issue with the formatting large Mass and Cost values.
  Fixed: Error when loading the Engineer7500 part model.
   
  1.0.13.1, 16-12-2014
  Fixed: Issue with manoeuvre node readouts and low tier tracking station.
   
  1.0.13.0, 16-12-2014
  Updated for KSP version 0.90
   
  Added: New readouts to the vessel category:
  - Heading Rate
  - Pitch Rate
  - Roll Rate
   
  Changed: Simulation to look for fuel lines that use CModuleFuelLine module.
  Fixed: Editor Overlay now loads the saved visibility value properly.
  Fixed: Altitude (Terrain) will no longer give a reading below sea level.
  Fixed: Suicide burn now uses radar altitude that clamps to sea level.
   
  1.0.12.0, 01-12-2014
  Added: Setting in Build Engineer to enable/disable vectored thrust calculations.
  Added: Thrust torque field in Build Engineer (courtesy of mic_e).
  Added: New readouts to the vessel category:
  - Thrust Offset Angle (courtesy of mic_e)
  - Thrust Torque (courtesy of mic_e)
  - Part Count: stage/total
  - Heading
  - Pitch
  - Roll
   
  Added: New readouts to the surface category:
  - Situation
   
  Added: New readouts to the miscellaneous category:
  - Vectored Thrust Toggle
   
  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 would not show updates when the delay was set lower than the frame rate.
   
  1.0.11.3, 11-11-2014
  Changed: Gravity measurements for Isp to 9.82.
   
  1.0.11.2, 10-11-2014
  Changed: Gravity measurements for Isp calculations from 9.81 to 9.8066 for accuracy.
  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.
   
  1.0.11.1, 07-11-2014
  Changed: Build Engineer now shows stage part count as well as total.
  Changed: Build Overlay Vessel tab data:
  DeltaV: stage / total
  Mass: stage / total
  TWR: start (max) <- shows for bottom stage only.
  Parts: stage / total
   
  Fixed: Issue with the vessel tab vanishing from the editor.
   
  1.0.11.0, 06-11-2014
  Added: New readouts to the orbital category:
  - Current SOI
  - Manoeuvre Node DeltaV (Prograde)
  - Manoeuvre Node DeltaV (Normal)
  - Manoeuvre Node DeltaV (Radial)
  - Manoeuvre Node DeltaV (Total)
  - Manoeuvre Node Burn Time
  - Manoeuvre Node Half Burn Time
  - Manoeuvre Node Angle to Prograde
  - Manoeuvre Node Angle to Retrograde
  - Time to Manoeuvre Node
  - Time to Manoeuvre Burn
   
  Added: Readout help strings by ClassyJakey.
   
  Fixed: Issue with separators in HUDs.
  Fixed: Issue with HUDs with backgrounds that have no displayed lines.
   
  Padishar's Fixes:
  Fixed: Issue with multicouplers when attached to parent by bottom node.
  Fixed: Issue with sepratrons on solid rocket boosters.
   
  1.0.10.0, 19-10-2014
  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
  reset the Flight Engineer sections to their default values and enable the new HUD functionality.
   
  Added: New reaouts to the vessel category:
  - Suicide Burn Altitude (height above terrain to start burn)
  - Suicide Burn Distance (distance to suicide burn altitude)
  - Suicide Burn DeltaV (velocity change required to zero vertical speed)
  *** F5 for safety and use at your own risk! ***
   
  Added: HUD type sections to the Flight Engineer.
  Added: HUD sections can have a smoked background for easy visibility.
  Added: 'Switch to Target' button on the Target Selector readout.
  Changed: The default installed readouts to reduce new user brain melt.
  Fixed: Flight Engineer not saving its hidden state.
  Fixed: Bug in the phase angle calculations.
  Fixed: Bug where the Build Engineer would stay locked after hiding with the shortcut key.
   
  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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 1.0.0.0, 24-07-2014
Initial release for public testing. Initial release for public testing.
  GNU GENERAL PUBLIC LICENSE
  Version 3, 29 June 2007
 
  Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
  Everyone is permitted to copy and distribute verbatim copies
  of this license document, but changing it is not allowed.
 
  Preamble
 
  The GNU General Public License is a free, copyleft license for
  software and other kinds of works.
 
  The licenses for most software and other practical works are designed
  to take away your freedom to share and change the works. By contrast,
  the GNU General Public License is intended to guarantee your freedom to
  share and change all versions of a program--to make sure it remains free
  software for all its users. We, the Free Software Foundation, use the
  GNU General Public License for most of our software; it applies also to
  any other work released this way by its authors. You can apply it to
  your programs, too.
 
  When we speak of free software, we are referring to freedom, not
  price. Our General Public Licenses are designed to make sure that you
  have the freedom to distribute copies of free software (and charge for
  them if you wish), that you receive source code or can get it if you
  want it, that you can change the software or use pieces of it in new
  free programs, and that you know you can do these things.
 
  To protect your rights, we need to prevent others from denying you
  these rights or asking you to surrender the rights. Therefore, you have
  certain responsibilities if you distribute copies of the software, or if
  you modify it: responsibilities to respect the freedom of others.
 
  For example, if you distribute copies of such a program, whether
  gratis or for a fee, you must pass on to the recipients the same
  freedoms that you received. You must make sure that they, too, receive
  or can get the source code. And you must show them these terms so they
  know their rights.
 
  Developers that use the GNU GPL protect your rights with two steps:
  (1) assert copyright on the software, and (2) offer you this License
  giving you legal permission to copy, distribute and/or modify it.
 
  For the developers' and authors' protection, the GPL clearly explains
  that there is no warranty for this free software. For both users' and
  authors' sake, the GPL requires that modified versions be marked as
  changed, so that their problems will not be attributed erroneously to
  authors of previous versions.
 
  Some devices are designed to deny users access to install or run
  modified versions of the software inside them, although the manufacturer
  can do so. This is fundamentally incompatible with the aim of
  protecting users' freedom to change the software. The systematic
  pattern of such abuse occurs in the area of products for individuals to
  use, which is precisely where it is most unacceptable. Therefore, we
  have designed this version of the GPL to prohibit the practice for those
  products. If such problems arise substantially in other domains, we
  stand ready to extend this provision to those domains in future versions
  of the GPL, as needed to protect the freedom of users.
 
  Finally, every program is threatened constantly by software patents.
  States should not allow patents to restrict development and use of
  software on general-purpose computers, but in those that do, we wish to
  avoid the special danger that patents applied to a free program could
  make it effectively proprietary. To prevent this, the GPL assures that
  patents cannot be used to render the program non-free.
 
  The precise terms and conditions for copying, distribution and
  modification follow.
 
  TERMS AND CONDITIONS
 
  0. Definitions.
 
  "This License" refers to version 3 of the GNU General Public License.
 
  "Copyright" also means copyright-like laws that apply to other kinds of
  works, such as semiconductor masks.
 
  "The Program" refers to any copyrightable work licensed under this
  License. Each licensee is addressed as "you". "Licensees" and
  "recipients" may be individuals or organizations.
 
  To "modify" a work means to copy from or adapt all or part of the work
  in a fashion requiring copyright permission, other than the making of an
  exact copy. The resulting work is called a "modified version" of the
  earlier work or a work "based on" the earlier work.
 
  A "covered work" means either the unmodified Program or a work based
  on the Program.
 
  To "propagate" a work means to do anything with it that, without
  permission, would make you directly or secondarily liable for
  infringement under applicable copyright law, except executing it on a
  computer or modifying a private copy. Propagation includes copying,
  distribution (with or without modification), making available to the
  public, and in some countries other activities as well.
 
  To "convey" a work means any kind of propagation that enables other
  parties to make or receive copies. Mere interaction with a user through
  a computer network, with no transfer of a copy, is not conveying.
 
  An interactive user interface displays "Appropriate Legal Notices"
  to the extent that it includes a convenient and prominently visible
  feature that (1) displays an appropriate copyright notice, and (2)
  tells the user that there is no warranty for the work (except to the
  extent that warranties are provided), that licensees may convey the
  work under this License, and how to view a copy of this License. If
  the interface presents a list of user commands or options, such as a
  menu, a prominent item in the list meets this criterion.
 
  1. Source Code.
 
  The "source code" for a work means the preferred form of the work
  for making modifications to it. "Object code" means any non-source
  form of a work.
 
  A "Standard Interface" means an interface that either is an official
  standard defined by a recognized standards body, or, in the case of
  interfaces specified for a particular programming language, one that
  is widely used among developers working in that language.
 
  The "System Libraries" of an executable work include anything, other
  than the work as a whole, that (a) is included in the normal form of
  packaging a Major Component, but which is not part of that Major
  Component, and (b) serves only to enable use of the work with that
  Major Component, or to implement a Standard Interface for which an
  implementation is available to the public in source code form. A
  "Major Component", in this context, means a major essential component
  (kernel, window system, and so on) of the specific operating system
  (if any) on which the executable work runs, or a compiler used to
  produce the work, or an object code interpreter used to run it.
 
  The "Corresponding Source" for a work in object code form means all
  the source code needed to generate, install, and (for an executable
  work) run the object code and to modify the work, including scripts to
  control those activities. However, it does not include the work's
  System Libraries, or general-purpose tools or generally available free
  programs which are used unmodified in performing those activities but
  which are not part of the work. For example, Corresponding Source
  includes interface definition files associated with source files for
  the work, and the source code for shared libraries and dynamically
  linked subprograms that the work is specifically designed to require,
  such as by intimate data communication or control flow between those
  subprograms and other parts of the work.
 
  The Corresponding Source need not include anything that users
  can regenerate automatically from other parts of the Corresponding
  Source.
 
  The Corresponding Source for a work in source code form is that
  same work.
 
  2. Basic Permissions.
 
  All rights granted under this License are granted for the term of
  copyright on the Program, and are irrevocable provided the stated
  conditions are met. This License explicitly affirms your unlimited
  permission to run the unmodified Program. The output from running a
  covered work is covered by this License only if the output, given its
  content, constitutes a covered work. This License acknowledges your
  rights of fair use or other equivalent, as provided by copyright law.
 
  You may make, run and propagate covered works that you do not
  convey, without conditions so long as your license otherwise remains
  in force. You may convey covered works to others for the sole purpose
  of having them make modifications exclusively for you, or provide you
  with facilities for running those works, provided that you comply with
  the terms of this License in conveying all material for which you do
  not control copyright. Those thus making or running the covered works
  for you must do so exclusively on your behalf, under your direction
  and control, on terms that prohibit them from making any copies of
  your copyrighted material outside their relationship with you.
 
  Conveying under any other circumstances is permitted solely under
  the conditions stated below. Sublicensing is not allowed; section 10
  makes it unnecessary.
 
  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
 
  No covered work shall be deemed part of an effective technological
  measure under any applicable law fulfilling obligations under article
  11 of the WIPO copyright treaty adopted on 20 December 1996, or
  similar laws prohibiting or restricting circumvention of such
  measures.
 
  When you convey a covered work, you waive any legal power to forbid
  circumvention of technological measures to the extent such circumvention
  is effected by exercising rights under this License with respect to
  the covered work, and you disclaim any intention to limit operation or
  modification of the work as a means of enforcing, against the work's
  users, your or third parties' legal rights to forbid circumvention of
  technological measures.
 
  4. Conveying Verbatim Copies.
 
  You may convey verbatim copies of the Program's source code as you
  receive it, in any medium, provided that you conspicuously and
  appropriately publish on each copy an appropriate copyright notice;
  keep intact all notices stating that this License and any
  non-permissive terms added in accord with section 7 apply to the code;
  keep intact all notices of the absence of any warranty; and give all
  recipients a copy of this License along with the Program.
 
  You may charge any price or no price for each copy that you convey,
  and you may offer support or warranty protection for a fee.
 
  5. Conveying Modified Source Versions.
 
  You may convey a work based on the Program, or the modifications to
  produce it from the Program, in the form of source code under the
  terms of section 4, provided that you also meet all of these conditions:
 
  a) The work must carry prominent notices stating that you modified
  it, and giving a relevant date.
 
  b) The work must carry prominent notices stating that it is
  released under this License and any conditions added under section
  7. This requirement modifies the requirement in section 4 to
  "keep intact all notices".
 
  c) You must license the entire work, as a whole, under this
  License to anyone who comes into possession of a copy. This
  License will therefore apply, along with any applicable section 7
  additional terms, to the whole of the work, and all its parts,
  regardless of how they are packaged. This License gives no
  permission to license the work in any other way, but it does not
  invalidate such permission if you have separately received it.
 
  d) If the work has interactive user interfaces, each must display
  Appropriate Legal Notices; however, if the Program has interactive
  interfaces that do not display Appropriate Legal Notices, your
  work need not make them do so.
 
  A compilation of a covered work with other separate and independent
  works, which are not by their nature extensions of the covered work,
  and which are not combined with it such as to form a larger program,
  in or on a volume of a storage or distribution medium, is called an
  "aggregate" if the compilation and its resulting copyright are not
  used to limit the access or legal rights of the compilation's users
  beyond what the individual works permit. Inclusion of a covered work
  in an aggregate does not cause this License to apply to the other
  parts of the aggregate.
 
  6. Conveying Non-Source Forms.
 
  You may convey a covered work in object code form under the terms
  of sections 4 and 5, provided that you also convey the
  machine-readable Corresponding Source under the terms of this License,
  in one of these ways:
 
  a) Convey the object code in, or embodied in, a physical product
  (including a physical distribution medium), accompanied by the
  Corresponding Source fixed on a durable physical medium
  customarily used for software interchange.
 
  b) Convey the object code in, or embodied in, a physical product
  (including a physical distribution medium), accompanied by a
  written offer, valid for at least three years and valid for as
  long as you offer spare parts or customer support for that product
  model, to give anyone who possesses the object code either (1) a
  copy of the Corresponding Source for all the software in the
  product that is covered by this License, on a durable physical
  medium customarily used for software interchange, for a price no
  more than your reasonable cost of physically performing this
  conveying of source, or (2) access to copy the
  Corresponding Source from a network server at no charge.
 
  c) Convey individual copies of the object code with a copy of the
  written offer to provide the Corresponding Source. This
  alternative is allowed only occasionally and noncommercially, and
  only if you received the object code with such an offer, in accord
  with subsection 6b.
 
  d) Convey the object code by offering access from a designated
  place (gratis or for a charge), and offer equivalent access to the
  Corresponding Source in the same way through the same place at no
  further charge. You need not require recipients to copy the
  Corresponding Source along with the object code. If the place to
  copy the object code is a network server, the Corresponding Source
  may be on a different server (operated by you or a third party)
  that supports equivalent copying facilities, provided you maintain
  clear directions next to the object code saying where to find the
  Corresponding Source. Regardless of what server hosts the
  Corresponding Source, you remain obligated to ensure that it is
  available for as long as needed to satisfy these requirements.
 
  e) Convey the object code using peer-to-peer transmission, provided
  you inform other peers where the object code and Corresponding
  Source of the work are being offered to the general public at no
  charge under subsection 6d.
 
  A separable portion of the object code, whose source code is excluded
  from the Corresponding Source as a System Library, need not be
  included in conveying the object code work.
 
  A "User Product" is either (1) a "consumer product", which means any
  tangible personal property which is normally used for personal, family,
  or household purposes, or (2) anything designed or sold for incorporation
  into a dwelling. In determining whether a product is a consumer product,
  doubtful cases shall be resolved in favor of coverage. For a particular
  product received by a particular user, "normally used" refers to a
  typical or common use of that class of product, regardless of the status
  of the particular user or of the way in which the particular user
  actually uses, or expects or is expected to use, the product. A product
  is a consumer product regardless of whether the product has substantial
  commercial, industrial or non-consumer uses, unless such uses represent
  the only significant mode of use of the product.
 
  "Installation Information" for a User Product means any methods,
  procedures, authorization keys, or other information required to install
  and execute modified versions of a covered work in that User Product from
  a modified version of its Corresponding Source. The information must
  suffice to ensure that the continued functioning of the modified object
  code is in no case prevented or interfered with solely because
  modification has been made.
 
  If you convey an object code work under this section in, or with, or
  specifically for use in, a User Product, and the conveying occurs as
  part of a transaction in which the right of possession and use of the
  User Product is transferred to the recipient in perpetuity or for a
  fixed term (regardless of how the transaction is characterized), the
  Corresponding Source conveyed under this section must be accompanied
  by the Installation Information. But this requirement does not apply
  if neither you nor any third party retains the ability to install
  modified object code on the User Product (for example, the work has
  been installed in ROM).
 
  The requirement to provide Installation Information does not include a
  requirement to continue to provide support service, warranty, or updates
  for a work that has been modified or installed by the recipient, or for
  the User Product in which it has been modified or installed. Access to a
  network may be denied when the modification itself materially and
  adversely affects the operation of the network or violates the rules and
  protocols for communication across the network.
 
  Corresponding Source conveyed, and Installation Information provided,
  in accord with this section must be in a format that is publicly
  documented (and with an implementation available to the public in
  source code form), and must require no special password or key for
  unpacking, reading or copying.
 
  7. Additional Terms.
 
  "Additional permissions" are terms that supplement the terms of this
  License by making exceptions from one or more of its conditions.
  Additional permissions that are applicable to the entire Program shall
  be treated as though they were included in this License, to the extent
  that they are valid under applicable law. If additional permissions
  apply only to part of the Program, that part may be used separately
  under those permissions, but the entire Program remains governed by
  this License without regard to the additional permissions.
 
  When you convey a copy of a covered work, you may at your option
  remove any additional permissions from that copy, or from any part of
  it. (Additional permissions may be written to require their own
  removal in certain cases when you modify the work.) You may place
  additional permissions on material, added by you to a covered work,
  for which you have or can give appropriate copyright permission.
 
  Notwithstanding any other provision of this License, for material you
  add to a covered work, you may (if authorized by the copyright holders of
  that material) supplement the terms of this License with terms:
 
  a) Disclaiming warranty or limiting liability differently from the
  terms of sections 15 and 16 of this License; or
 
  b) Requiring preservation of specified reasonable legal notices or
  author attributions in that material or in the Appropriate Legal
  Notices displayed by works containing it; or
 
  c) Prohibiting misrepresentation of the origin of that material, or
  requiring that modified versions of such material be marked in
  reasonable ways as different from the original version; or
 
  d) Limiting the use for publicity purposes of names of licensors or
  authors of the material; or
 
  e) Declining to grant rights under trademark law for use of some
  trade names, trademarks, or service marks; or
 
  f) Requiring indemnification of licensors and authors of that
  material by anyone who conveys the material (or modified versions of
  it) with contractual assumptions of liability to the recipient, for
  any liability that these contractual assumptions directly impose on
  those licensors and authors.
 
  All other non-permissive additional terms are considered "further
  restrictions" within the meaning of section 10. If the Program as you
  received it, or any part of it, contains a notice stating that it is
  governed by this License along with a term that is a further
  restriction, you may remove that term. If a license document contains
  a further restriction but permits relicensing or conveying under this
  License, you may add to a covered work material governed by the terms
  of that license document, provided that the further restriction does
  not survive such relicensing or conveying.
 
  If you add terms to a covered work in accord with this section, you
  must place, in the relevant source files, a statement of the
  additional terms that apply to those files, or a notice indicating
  where to find the applicable terms.
 
  Additional terms, permissive or non-permissive, may be stated in the
  form of a separately written license, or stated as exceptions;
  the above requirements apply either way.
 
  8. Termination.
 
  You may not propagate or modify a covered work except as expressly
  provided under this License. Any attempt otherwise to propagate or
  modify it is void, and will automatically terminate your rights under
  this License (including any patent licenses granted under the third
  paragraph of section 11).
 
  However, if you cease all violation of this License, then your
  license from a particular copyright holder is reinstated (a)
  provisionally, unless and until the copyright holder explicitly and
  finally terminates your license, and (b) permanently, if the copyright
  holder fails to notify you of the violation by some reasonable means
  prior to 60 days after the cessation.
 
  Moreover, your license from a particular copyright holder is
  reinstated permanently if the copyright holder notifies you of the
  violation by some reasonable means, this is the first time you have
  received notice of violation of this License (for any work) from that
  copyright holder, and you cure the violation prior to 30 days after
  your receipt of the notice.
 
  Termination of your rights under this section does not terminate the
  licenses of parties who have received copies or rights from you under
  this License. If your rights have been terminated and not permanently
  reinstated, you do not qualify to receive new licenses for the same
  material under section 10.
 
  9. Acceptance Not Required for Having Copies.
 
  You are not required to accept this License in order to receive or
  run a copy of the Program. Ancillary propagation of a covered work
  occurring solely as a consequence of using peer-to-peer transmission
  to receive a copy likewise does not require acceptance. However,
  nothing other than this License grants you permission to propagate or
  modify any covered work. These actions infringe copyright if you do
  not accept this License. Therefore, by modifying or propagating a
  covered work, you indicate your acceptance of this License to do so.
 
  10. Automatic Licensing of Downstream Recipients.
 
  Each time you convey a covered work, the recipient automatically
  receives a license from the original licensors, to run, modify and
  propagate that work, subject to this License. You are not responsible
  for enforcing compliance by third parties with this License.
 
  An "entity transaction" is a transaction transferring control of an
  organization, or substantially all assets of one, or subdividing an
  organization, or merging organizations. If propagation of a covered
  work results from an entity transaction, each party to that
  transaction who receives a copy of the work also receives whatever
  licenses to the work the party's predecessor in interest had or could
  give under the previous paragraph, plus a right to possession of the
  Corresponding Source of the work from the predecessor in interest, if
  the predecessor has it or can get it with reasonable efforts.
 
  You may not impose any further restrictions on the exercise of the
  rights granted or affirmed under this License. For example, you may
  not impose a license fee, royalty, or other charge for exercise of
  rights granted under this License, and you may not initiate litigation
  (including a cross-claim or counterclaim in a lawsuit) alleging that
  any patent claim is infringed by making, using, selling, offering for
  sale, or importing the Program or any portion of it.
 
  11. Patents.
 
  A "contributor" is a copyright holder who authorizes use under this
  License of the Program or a work on which the Program is based. The
  work thus licensed is called the contributor's "contributor version".
 
  A contributor's "essential patent claims" are all patent claims
  owned or controlled by the contributor, whether already acquired or
  hereafter acquired, that would be infringed by some manner, permitted
  by this License, of making, using, or selling its contributor version,
  but do not include claims that would be infringed only as a
  consequence of further modification of the contributor version. For
  purposes of this definition, "control" includes the right to grant
  patent sublicenses in a manner consistent with the requirements of
  this License.
 
  Each contributor grants you a non-exclusive, worldwide, royalty-free
  patent license under the contributor's essential patent claims, to
  make, use, sell, offer for sale, import and otherwise run, modify and
  propagate the contents of its contributor version.
 
  In the following three paragraphs, a "patent license" is any express
  agreement or commitment, however denominated, not to enforce a patent
  (such as an express permission to practice a patent or covenant not to
  sue for patent infringement). To "grant" such a patent license to a
  party means to make such an agreement or commitment not to enforce a
  patent against the party.
 
  If you convey a covered work, knowingly relying on a patent license,
  and the Corresponding Source of the work is not available for anyone
  to copy, free of charge and under the terms of this License, through a
  publicly available network server or other readily accessible means,
  then you must either (1) cause the Corresponding Source to be so
  available, or (2) arrange to deprive yourself of the benefit of the
  patent license for this particular work, or (3) arrange, in a manner
  consistent with the requirements of this License, to extend the patent
  license to downstream recipients. "Knowingly relying" means you have
  actual knowledge that, but for the patent license, your conveying the
  covered work in a country, or your recipient's use of the covered work
  in a country, would infringe one or more identifiable patents in that
  country that you have reason to believe are valid.
 
  If, pursuant to or in connection with a single transaction or
  arrangement, you convey, or propagate by procuring conveyance of, a
  covered work, and grant a patent license to some of the parties
  receiving the covered work authorizing them to use, propagate, modify
  or convey a specific copy of the covered work, then the patent license
  you grant is automatically extended to all recipients of the covered
  work and works based on it.
 
  A patent license is "discriminatory" if it does not include within
  the scope of its coverage, prohibits the exercise of, or is
  conditioned on the non-exercise of one or more of the rights that are
  specifically granted under this License. You may not convey a covered
  work if you are a party to an arrangement with a third party that is
  in the business of distributing software, under which you make payment
  to the third party based on the extent of your activity of conveying
  the work, and under which the third party grants, to any of the
  parties who would receive the covered work from you, a discriminatory
  patent license (a) in connection with copies of the covered work
  conveyed by you (or copies made from those copies), or (b) primarily
  for and in connection with specific products or compilations that
  contain the covered work, unless you entered into that arrangement,
  or that patent license was granted, prior to 28 March 2007.
 
  Nothing in this License shall be construed as excluding or limiting
  any implied license or other defenses to infringement that may
  otherwise be available to you under applicable patent law.
 
  12. No Surrender of Others' Freedom.
 
  If conditions are imposed on you (whether by court order, agreement or
  otherwise) that contradict the conditions of this License, they do not
  excuse you from the conditions of this License. If you cannot convey a
  covered work so as to satisfy simultaneously your obligations under this
  License and any other pertinent obligations, then as a consequence you may
  not convey it at all. For example, if you agree to terms that obligate you
  to collect a royalty for further conveying from those to whom you convey
  the Program, the only way you could satisfy both those terms and this
  License would be to refrain entirely from conveying the Program.
 
  13. Use with the GNU Affero General Public License.
 
  Notwithstanding any other provision of this License, you have
  permission to link or combine any covered work with a work licensed
  under version 3 of the GNU Affero General Public License into a single
  combined work, and to convey the resulting work. The terms of this
  License will continue to apply to the part which is the covered work,
  but the special requirements of the GNU Affero General Public License,
  section 13, concerning interaction through a network will apply to the
  combination as such.
 
  14. Revised Versions of this License.
 
  The Free Software Foundation may publish revised and/or new versions of
  the GNU General Public License from time to time. Such new versions will
  be similar in spirit to the present version, but may differ in detail to
  address new problems or concerns.
 
  Each version is given a distinguishing version number. If the
  Program specifies that a certain numbered version of the GNU General
  Public License "or any later version" applies to it, you have the
  option of following the terms and conditions either of that numbered
  version or of any later version published by the Free Software
  Foundation. If the Program does not specify a version number of the
  GNU General Public License, you may choose any version ever published
  by the Free Software Foundation.
 
  If the Program specifies that a proxy can decide which future
  versions of the GNU General Public License can be used, that proxy's
  public statement of acceptance of a version permanently authorizes you
  to choose that version for the Program.
 
  Later license versions may give you additional or different
  permissions. However, no additional obligations are imposed on any
  author or copyright holder as a result of your choosing to follow a
  later version.
 
  15. Disclaimer of Warranty.
 
  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
  APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
  HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
  OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
  IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
  ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
 
  16. Limitation of Liability.
 
  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
  WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
  THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
  GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
  USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
  DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
  PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
  EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
  SUCH DAMAGES.
 
  17. Interpretation of Sections 15 and 16.
 
  If the disclaimer of warranty and limitation of liability provided
  above cannot be given local legal effect according to their terms,
  reviewing courts shall apply local law that most closely approximates
  an absolute waiver of all civil liability in connection with the
  Program, unless a warranty or assumption of liability accompanies a
  copy of the Program in return for a fee.
 
  END OF TERMS AND CONDITIONS
 
  How to Apply These Terms to Your New Programs
 
  If you develop a new program, and you want it to be of the greatest
  possible use to the public, the best way to achieve this is to make it
  free software which everyone can redistribute and change under these terms.
 
  To do so, attach the following notices to the program. It is safest
  to attach them to the start of each source file to most effectively
  state the exclusion of warranty; and each file should have at least
  the "copyright" line and a pointer to where the full notice is found.
 
  <one line to give the program's name and a brief idea of what it does.>
  Copyright (C) <year> <name of author>
 
  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/>.
 
  Also add information on how to contact you by electronic and paper mail.
 
  If the program does terminal interaction, make it output a short
  notice like this when it starts in an interactive mode:
 
  <program> Copyright (C) <year> <name of author>
  This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
  This is free software, and you are welcome to redistribute it
  under certain conditions; type `show c' for details.
 
  The hypothetical commands `show w' and `show c' should show the appropriate
  parts of the General Public License. Of course, your program's commands
  might be different; for a GUI interface, you would use an "about box".
 
  You should also get your employer (if you work as a programmer) or school,
  if any, to sign a "copyright disclaimer" for the program, if necessary.
  For more information on this, and how to apply and follow the GNU GPL, see
  <http://www.gnu.org/licenses/>.
 
  The GNU General Public License does not permit incorporating your program
  into proprietary programs. If your program is a subroutine library, you
  may consider it more useful to permit linking proprietary applications with
  the library. If this is what you want to do, use the GNU Lesser General
  Public License instead of this License. But first, please read
  <http://www.gnu.org/philosophy/why-not-lgpl.html>.
 
file:a/Documents/LICENSE.txt (deleted)
GNU GENERAL PUBLIC LICENSE  
Version 3, 29 June 2007  
 
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>  
Everyone is permitted to copy and distribute verbatim copies  
of this license document, but changing it is not allowed.  
 
Preamble  
 
The GNU General Public License is a free, copyleft license for  
software and other kinds of works.  
 
The licenses for most software and other practical works are designed  
to take away your freedom to share and change the works. By contrast,  
the GNU General Public License is intended to guarantee your freedom to  
share and change all versions of a program--to make sure it remains free  
software for all its users. We, the Free Software Foundation, use the  
GNU General Public License for most of our software; it applies also to  
any other work released this way by its authors. You can apply it to  
your programs, too.  
 
When we speak of free software, we are referring to freedom, not  
price. Our General Public Licenses are designed to make sure that you  
have the freedom to distribute copies of free software (and charge for  
them if you wish), that you receive source code or can get it if you  
want it, that you can change the software or use pieces of it in new  
free programs, and that you know you can do these things.  
 
To protect your rights, we need to prevent others from denying you  
these rights or asking you to surrender the rights. Therefore, you have  
certain responsibilities if you distribute copies of the software, or if  
you modify it: responsibilities to respect the freedom of others.  
 
For example, if you distribute copies of such a program, whether  
gratis or for a fee, you must pass on to the recipients the same  
freedoms that you received. You must make sure that they, too, receive  
or can get the source code. And you must show them these terms so they  
know their rights.  
 
Developers that use the GNU GPL protect your rights with two steps:  
(1) assert copyright on the software, and (2) offer you this License  
giving you legal permission to copy, distribute and/or modify it.  
 
For the developers' and authors' protection, the GPL clearly explains  
that there is no warranty for this free software. For both users' and  
authors' sake, the GPL requires that modified versions be marked as  
changed, so that their problems will not be attributed erroneously to  
authors of previous versions.  
 
Some devices are designed to deny users access to install or run  
modified versions of the software inside them, although the manufacturer  
can do so. This is fundamentally incompatible with the aim of  
protecting users' freedom to change the software. The systematic  
pattern of such abuse occurs in the area of products for individuals to  
use, which is precisely where it is most unacceptable. Therefore, we  
have designed this version of the GPL to prohibit the practice for those  
products. If such problems arise substantially in other domains, we  
stand ready to extend this provision to those domains in future versions  
of the GPL, as needed to protect the freedom of users.  
 
Finally, every program is threatened constantly by software patents.  
States should not allow patents to restrict development and use of  
software on general-purpose computers, but in those that do, we wish to  
avoid the special danger that patents applied to a free program could  
make it effectively proprietary. To prevent this, the GPL assures that  
patents cannot be used to render the program non-free.  
 
The precise terms and conditions for copying, distribution and  
modification follow.  
 
TERMS AND CONDITIONS  
 
0. Definitions.  
 
"This License" refers to version 3 of the GNU General Public License.  
 
"Copyright" also means copyright-like laws that apply to other kinds of  
works, such as semiconductor masks.  
 
"The Program" refers to any copyrightable work licensed under this  
License. Each licensee is addressed as "you". "Licensees" and  
"recipients" may be individuals or organizations.  
 
To "modify" a work means to copy from or adapt all or part of the work  
in a fashion requiring copyright permission, other than the making of an  
exact copy. The resulting work is called a "modified version" of the  
earlier work or a work "based on" the earlier work.  
 
A "covered work" means either the unmodified Program or a work based  
on the Program.  
 
To "propagate" a work means to do anything with it that, without  
permission, would make you directly or secondarily liable for  
infringement under applicable copyright law, except executing it on a  
computer or modifying a private copy. Propagation includes copying,  
distribution (with or without modification), making available to the  
public, and in some countries other activities as well.  
 
To "convey" a work means any kind of propagation that enables other  
parties to make or receive copies. Mere interaction with a user through  
a computer network, with no transfer of a copy, is not conveying.  
 
An interactive user interface displays "Appropriate Legal Notices"  
to the extent that it includes a convenient and prominently visible  
feature that (1) displays an appropriate copyright notice, and (2)  
tells the user that there is no warranty for the work (except to the  
extent that warranties are provided), that licensees may convey the  
work under this License, and how to view a copy of this License. If  
the interface presents a list of user commands or options, such as a  
menu, a prominent item in the list meets this criterion.  
 
1. Source Code.  
 
The "source code" for a work means the preferred form of the work  
for making modifications to it. "Object code" means any non-source  
form of a work.  
 
A "Standard Interface" means an interface that either is an official  
standard defined by a recognized standards body, or, in the case of  
interfaces specified for a particular programming language, one that  
is widely used among developers working in that language.  
 
The "System Libraries" of an executable work include anything, other  
than the work as a whole, that (a) is included in the normal form of  
packaging a Major Component, but which is not part of that Major  
Component, and (b) serves only to enable use of the work with that  
Major Component, or to implement a Standard Interface for which an  
implementation is available to the public in source code form. A  
"Major Component", in this context, means a major essential component  
(kernel, window system, and so on) of the specific operating system  
(if any) on which the executable work runs, or a compiler used to  
produce the work, or an object code interpreter used to run it.  
 
The "Corresponding Source" for a work in object code form means all  
the source code needed to generate, install, and (for an executable  
work) run the object code and to modify the work, including scripts to  
control those activities. However, it does not include the work's  
System Libraries, or general-purpose tools or generally available free  
programs which are used unmodified in performing those activities but  
which are not part of the work. For example, Corresponding Source  
includes interface definition files associated with source files for  
the work, and the source code for shared libraries and dynamically  
linked subprograms that the work is specifically designed to require,  
such as by intimate data communication or control flow between those  
subprograms and other parts of the work.  
 
The Corresponding Source need not include anything that users  
can regenerate automatically from other parts of the Corresponding  
Source.  
 
The Corresponding Source for a work in source code form is that  
same work.  
 
2. Basic Permissions.  
 
All rights granted under this License are granted for the term of  
copyright on the Program, and are irrevocable provided the stated  
conditions are met. This License explicitly affirms your unlimited  
permission to run the unmodified Program. The output from running a  
covered work is covered by this License only if the output, given its  
content, constitutes a covered work. This License acknowledges your  
rights of fair use or other equivalent, as provided by copyright law.  
 
You may make, run and propagate covered works that you do not  
convey, without conditions so long as your license otherwise remains  
in force. You may convey covered works to others for the sole purpose  
of having them make modifications exclusively for you, or provide you  
with facilities for running those works, provided that you comply with  
the terms of this License in conveying all material for which you do  
not control copyright. Those thus making or running the covered works  
for you must do so exclusively on your behalf, under your direction  
and control, on terms that prohibit them from making any copies of  
your copyrighted material outside their relationship with you.  
 
Conveying under any other circumstances is permitted solely under  
the conditions stated below. Sublicensing is not allowed; section 10  
makes it unnecessary.  
 
3. Protecting Users' Legal Rights From Anti-Circumvention Law.  
 
No covered work shall be deemed part of an effective technological  
measure under any applicable law fulfilling obligations under article  
11 of the WIPO copyright treaty adopted on 20 December 1996, or  
similar laws prohibiting or restricting circumvention of such  
measures.  
 
When you convey a covered work, you waive any legal power to forbid  
circumvention of technological measures to the extent such circumvention  
is effected by exercising rights under this License with respect to  
the covered work, and you disclaim any intention to limit operation or  
modification of the work as a means of enforcing, against the work's  
users, your or third parties' legal rights to forbid circumvention of  
technological measures.  
 
4. Conveying Verbatim Copies.  
 
You may convey verbatim copies of the Program's source code as you  
receive it, in any medium, provided that you conspicuously and  
appropriately publish on each copy an appropriate copyright notice;  
keep intact all notices stating that this License and any  
non-permissive terms added in accord with section 7 apply to the code;  
keep intact all notices of the absence of any warranty; and give all  
recipients a copy of this License along with the Program.  
 
You may charge any price or no price for each copy that you convey,  
and you may offer support or warranty protection for a fee.  
 
5. Conveying Modified Source Versions.  
 
You may convey a work based on the Program, or the modifications to  
produce it from the Program, in the form of source code under the  
terms of section 4, provided that you also meet all of these conditions:  
 
a) The work must carry prominent notices stating that you modified  
it, and giving a relevant date.  
 
b) The work must carry prominent notices stating that it is  
released under this License and any conditions added under section  
7. This requirement modifies the requirement in section 4 to  
"keep intact all notices".  
 
c) You must license the entire work, as a whole, under this  
License to anyone who comes into possession of a copy. This  
License will therefore apply, along with any applicable section 7  
additional terms, to the whole of the work, and all its parts,  
regardless of how they are packaged. This License gives no  
permission to license the work in any other way, but it does not  
invalidate such permission if you have separately received it.  
 
d) If the work has interactive user interfaces, each must display  
Appropriate Legal Notices; however, if the Program has interactive  
interfaces that do not display Appropriate Legal Notices, your  
work need not make them do so.  
 
A compilation of a covered work with other separate and independent  
works, which are not by their nature extensions of the covered work,  
and which are not combined with it such as to form a larger program,  
in or on a volume of a storage or distribution medium, is called an  
"aggregate" if the compilation and its resulting copyright are not  
used to limit the access or legal rights of the compilation's users  
beyond what the individual works permit. Inclusion of a covered work  
in an aggregate does not cause this License to apply to the other  
parts of the aggregate.  
 
6. Conveying Non-Source Forms.  
 
You may convey a covered work in object code form under the terms  
of sections 4 and 5, provided that you also convey the  
machine-readable Corresponding Source under the terms of this License,  
in one of these ways:  
 
a) Convey the object code in, or embodied in, a physical product  
(including a physical distribution medium), accompanied by the  
Corresponding Source fixed on a durable physical medium  
customarily used for software interchange.  
 
b) Convey the object code in, or embodied in, a physical product  
(including a physical distribution medium), accompanied by a  
written offer, valid for at least three years and valid for as  
long as you offer spare parts or customer support for that product  
model, to give anyone who possesses the object code either (1) a  
copy of the Corresponding Source for all the software in the  
product that is covered by this License, on a durable physical  
medium customarily used for software interchange, for a price no  
more than your reasonable cost of physically performing this  
conveying of source, or (2) access to copy the  
Corresponding Source from a network server at no charge.  
 
c) Convey individual copies of the object code with a copy of the  
written offer to provide the Corresponding Source. This  
alternative is allowed only occasionally and noncommercially, and  
only if you received the object code with such an offer, in accord  
with subsection 6b.  
 
d) Convey the object code by offering access from a designated  
place (gratis or for a charge), and offer equivalent access to the  
Corresponding Source in the same way through the same place at no  
further charge. You need not require recipients to copy the  
Corresponding Source along with the object code. If the place to  
copy the object code is a network server, the Corresponding Source  
may be on a different server (operated by you or a third party)  
that supports equivalent copying facilities, provided you maintain  
clear directions next to the object code saying where to find the  
Corresponding Source. Regardless of what server hosts the  
Corresponding Source, you remain obligated to ensure that it is  
available for as long as needed to satisfy these requirements.  
 
e) Convey the object code using peer-to-peer transmission, provided  
you inform other peers where the object code and Corresponding  
Source of the work are being offered to the general public at no  
charge under subsection 6d.  
 
A separable portion of the object code, whose source code is excluded  
from the Corresponding Source as a System Library, need not be  
included in conveying the object code work.  
 
A "User Product" is either (1) a "consumer product", which means any  
tangible personal property which is normally used for personal, family,  
or household purposes, or (2) anything designed or sold for incorporation  
into a dwelling. In determining whether a product is a consumer product,  
doubtful cases shall be resolved in favor of coverage. For a particular  
product received by a particular user, "normally used" refers to a  
typical or common use of that class of product, regardless of the status  
of the particular user or of the way in which the particular user  
actually uses, or expects or is expected to use, the product. A product  
is a consumer product regardless of whether the product has substantial  
commercial, industrial or non-consumer uses, unless such uses represent  
the only significant mode of use of the product.  
 
"Installation Information" for a User Product means any methods,  
procedures, authorization keys, or other information required to install  
and execute modified versions of a covered work in that User Product from  
a modified version of its Corresponding Source. The information must  
suffice to ensure that the continued functioning of the modified object  
code is in no case prevented or interfered with solely because  
modification has been made.  
 
If you convey an object code work under this section in, or with, or  
specifically for use in, a User Product, and the conveying occurs as  
part of a transaction in which the right of possession and use of the  
User Product is transferred to the recipient in perpetuity or for a  
fixed term (regardless of how the transaction is characterized), the  
Corresponding Source conveyed under this section must be accompanied  
by the Installation Information. But this requirement does not apply  
if neither you nor any third party retains the ability to install  
modified object code on the User Product (for example, the work has  
been installed in ROM).  
 
The requirement to provide Installation Information does not include a  
requirement to continue to provide support service, warranty, or updates  
for a work that has been modified or installed by the recipient, or for  
the User Product in which it has been modified or installed. Access to a  
network may be denied when the modification itself materially and  
adversely affects the operation of the network or violates the rules and  
protocols for communication across the network.  
 
Corresponding Source conveyed, and Installation Information provided,  
in accord with this section must be in a format that is publicly  
documented (and with an implementation available to the public in  
source code form), and must require no special password or key for  
unpacking, reading or copying.  
 
7. Additional Terms.  
 
"Additional permissions" are terms that supplement the terms of this  
License by making exceptions from one or more of its conditions.  
Additional permissions that are applicable to the entire Program shall  
be treated as though they were included in this License, to the extent  
that they are valid under applicable law. If additional permissions  
apply only to part of the Program, that part may be used separately  
under those permissions, but the entire Program remains governed by  
this License without regard to the additional permissions.  
 
When you convey a copy of a covered work, you may at your option  
remove any additional permissions from that copy, or from any part of  
it. (Additional permissions may be written to require their own  
removal in certain cases when you modify the work.) You may place  
additional permissions on material, added by you to a covered work,  
for which you have or can give appropriate copyright permission.  
 
Notwithstanding any other provision of this License, for material you  
add to a covered work, you may (if authorized by the copyright holders of  
that material) supplement the terms of this License with terms:  
 
a) Disclaiming warranty or limiting liability differently from the  
terms of sections 15 and 16 of this License; or  
 
b) Requiring preservation of specified reasonable legal notices or  
author attributions in that material or in the Appropriate Legal  
Notices displayed by works containing it; or  
 
c) Prohibiting misrepresentation of the origin of that material, or  
requiring that modified versions of such material be marked in  
reasonable ways as different from the original version; or  
 
d) Limiting the use for publicity purposes of names of licensors or  
authors of the material; or  
 
e) Declining to grant rights under trademark law for use of some  
trade names, trademarks, or service marks; or  
 
f) Requiring indemnification of licensors and authors of that  
material by anyone who conveys the material (or modified versions of  
it) with contractual assumptions of liability to the recipient, for  
any liability that these contractual assumptions directly impose on  
those licensors and authors.  
 
All other non-permissive additional terms are considered "further  
restrictions" within the meaning of section 10. If the Program as you  
received it, or any part of it, contains a notice stating that it is  
governed by this License along with a term that is a further  
restriction, you may remove that term. If a license document contains  
a further restriction but permits relicensing or conveying under this  
License, you may add to a covered work material governed by the terms  
of that license document, provided that the further restriction does  
not survive such relicensing or conveying.  
 
If you add terms to a covered work in accord with this section, you  
must place, in the relevant source files, a statement of the  
additional terms that apply to those files, or a notice indicating  
where to find the applicable terms.  
 
Additional terms, permissive or non-permissive, may be stated in the  
form of a separately written license, or stated as exceptions;  
the above requirements apply either way.  
 
8. Termination.  
 
You may not propagate or modify a covered work except as expressly  
provided under this License. Any attempt otherwise to propagate or  
modify it is void, and will automatically terminate your rights under  
this License (including any patent licenses granted under the third  
paragraph of section 11).  
 
However, if you cease all violation of this License, then your  
license from a particular copyright holder is reinstated (a)  
provisionally, unless and until the copyright holder explicitly and  
finally terminates your license, and (b) permanently, if the copyright  
holder fails to notify you of the violation by some reasonable means  
prior to 60 days after the cessation.  
 
Moreover, your license from a particular copyright holder is  
reinstated permanently if the copyright holder notifies you of the  
violation by some reasonable means, this is the first time you have  
received notice of violation of this License (for any work) from that  
copyright holder, and you cure the violation prior to 30 days after  
your receipt of the notice.  
 
Termination of your rights under this section does not terminate the  
licenses of parties who have received copies or rights from you under  
this License. If your rights have been terminated and not permanently  
reinstated, you do not qualify to receive new licenses for the same  
material under section 10.  
 
9. Acceptance Not Required for Having Copies.  
 
You are not required to accept this License in order to receive or  
run a copy of the Program. Ancillary propagation of a covered work  
occurring solely as a consequence of using peer-to-peer transmission  
to receive a copy likewise does not require acceptance. However,  
nothing other than this License grants you permission to propagate or  
modify any covered work. These actions infringe copyright if you do  
not accept this License. Therefore, by modifying or propagating a  
covered work, you indicate your acceptance of this License to do so.  
 
10. Automatic Licensing of Downstream Recipients.  
 
Each time you convey a covered work, the recipient automatically  
receives a license from the original licensors, to run, modify and  
propagate that work, subject to this License. You are not responsible  
for enforcing compliance by third parties with this License.  
 
An "entity transaction" is a transaction transferring control of an  
organization, or substantially all assets of one, or subdividing an  
organization, or merging organizations. If propagation of a covered  
work results from an entity transaction, each party to that  
transaction who receives a copy of the work also receives whatever  
licenses to the work the party's predecessor in interest had or could  
give under the previous paragraph, plus a right to possession of the  
Corresponding Source of the work from the predecessor in interest, if  
the predecessor has it or can get it with reasonable efforts.  
 
You may not impose any further restrictions on the exercise of the  
rights granted or affirmed under this License. For example, you may  
not impose a license fee, royalty, or other charge for exercise of  
rights granted under this License, and you may not initiate litigation  
(including a cross-claim or counterclaim in a lawsuit) alleging that  
any patent claim is infringed by making, using, selling, offering for  
sale, or importing the Program or any portion of it.  
 
11. Patents.  
 
A "contributor" is a copyright holder who authorizes use under this  
License of the Program or a work on which the Program is based. The  
work thus licensed is called the contributor's "contributor version".  
 
A contributor's "essential patent claims" are all patent claims  
owned or controlled by the contributor, whether already acquired or  
hereafter acquired, that would be infringed by some manner, permitted  
by this License, of making, using, or selling its contributor version,  
but do not include claims that would be infringed only as a  
consequence of further modification of the contributor version. For  
purposes of this definition, "control" includes the right to grant  
patent sublicenses in a manner consistent with the requirements of  
this License.  
 
Each contributor grants you a non-exclusive, worldwide, royalty-free  
patent license under the contributor's essential patent claims, to  
make, use, sell, offer for sale, import and otherwise run, modify and  
propagate the contents of its contributor version.  
 
In the following three paragraphs, a "patent license" is any express  
agreement or commitment, however denominated, not to enforce a patent  
(such as an express permission to practice a patent or covenant not to  
sue for patent infringement). To "grant" such a patent license to a  
party means to make such an agreement or commitment not to enforce a  
patent against the party.  
 
If you convey a covered work, knowingly relying on a patent license,  
and the Corresponding Source of the work is not available for anyone  
to copy, free of charge and under the terms of this License, through a  
publicly available network server or other readily accessible means,  
then you must either (1) cause the Corresponding Source to be so  
available, or (2) arrange to deprive yourself of the benefit of the  
patent license for this particular work, or (3) arrange, in a manner  
consistent with the requirements of this License, to extend the patent  
license to downstream recipients. "Knowingly relying" means you have  
actual knowledge that, but for the patent license, your conveying the  
covered work in a country, or your recipient's use of the covered work  
in a country, would infringe one or more identifiable patents in that  
country that you have reason to believe are valid.  
 
If, pursuant to or in connection with a single transaction or  
arrangement, you convey, or propagate by procuring conveyance of, a  
covered work, and grant a patent license to some of the parties  
receiving the covered work authorizing them to use, propagate, modify  
or convey a specific copy of the covered work, then the patent license  
you grant is automatically extended to all recipients of the covered  
work and works based on it.  
 
A patent license is "discriminatory" if it does not include within  
the scope of its coverage, prohibits the exercise of, or is  
conditioned on the non-exercise of one or more of the rights that are  
specifically granted under this License. You may not convey a covered  
work if you are a party to an arrangement with a third party that is  
in the business of distributing software, under which you make payment  
to the third party based on the extent of your activity of conveying  
the work, and under which the third party grants, to any of the  
parties who would receive the covered work from you, a discriminatory  
patent license (a) in connection with copies of the covered work  
conveyed by you (or copies made from those copies), or (b) primarily  
for and in connection with specific products or compilations that  
contain the covered work, unless you entered into that arrangement,  
or that patent license was granted, prior to 28 March 2007.  
 
Nothing in this License shall be construed as excluding or limiting  
any implied license or other defenses to infringement that may  
otherwise be available to you under applicable patent law.  
 
12. No Surrender of Others' Freedom.  
 
If conditions are imposed on you (whether by court order, agreement or  
otherwise) that contradict the conditions of this License, they do not  
excuse you from the conditions of this License. If you cannot convey a  
covered work so as to satisfy simultaneously your obligations under this  
License and any other pertinent obligations, then as a consequence you may  
not convey it at all. For example, if you agree to terms that obligate you  
to collect a royalty for further conveying from those to whom you convey  
the Program, the only way you could satisfy both those terms and this  
License would be to refrain entirely from conveying the Program.  
 
13. Use with the GNU Affero General Public License.  
 
Notwithstanding any other provision of this License, you have  
permission to link or combine any covered work with a work licensed  
under version 3 of the GNU Affero General Public License into a single  
combined work, and to convey the resulting work. The terms of this  
License will continue to apply to the part which is the covered work,  
but the special requirements of the GNU Affero General Public License,  
section 13, concerning interaction through a network will apply to the  
combination as such.  
 
14. Revised Versions of this License.  
 
The Free Software Foundation may publish revised and/or new versions of  
the GNU General Public License from time to time. Such new versions will  
be similar in spirit to the present version, but may differ in detail to  
address new problems or concerns.  
 
Each version is given a distinguishing version number. If the  
Program specifies that a certain numbered version of the GNU General  
Public License "or any later version" applies to it, you have the  
option of following the terms and conditions either of that numbered  
version or of any later version published by the Free Software  
Foundation. If the Program does not specify a version number of the  
GNU General Public License, you may choose any version ever published  
by the Free Software Foundation.  
 
If the Program specifies that a proxy can decide which future  
versions of the GNU General Public License can be used, that proxy's  
public statement of acceptance of a version permanently authorizes you  
to choose that version for the Program.  
 
Later license versions may give you additional or different  
permissions. However, no additional obligations are imposed on any  
author or copyright holder as a result of your choosing to follow a  
later version.  
 
15. Disclaimer of Warranty.  
 
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY  
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT  
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY  
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,  
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR  
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM  
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF  
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.  
 
16. Limitation of Liability.  
 
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING  
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS  
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY  
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE  
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF  
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD  
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),  
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF  
SUCH DAMAGES.  
 
17. Interpretation of Sections 15 and 16.  
 
If the disclaimer of warranty and limitation of liability provided  
above cannot be given local legal effect according to their terms,  
reviewing courts shall apply local law that most closely approximates  
an absolute waiver of all civil liability in connection with the  
Program, unless a warranty or assumption of liability accompanies a  
copy of the Program in return for a fee.  
 
END OF TERMS AND CONDITIONS  
 
How to Apply These Terms to Your New Programs  
 
If you develop a new program, and you want it to be of the greatest  
possible use to the public, the best way to achieve this is to make it  
free software which everyone can redistribute and change under these terms.  
 
To do so, attach the following notices to the program. It is safest  
to attach them to the start of each source file to most effectively  
state the exclusion of warranty; and each file should have at least  
the "copyright" line and a pointer to where the full notice is found.  
 
<one line to give the program's name and a brief idea of what it does.>  
Copyright (C) <year> <name of author>  
 
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/>.  
 
Also add information on how to contact you by electronic and paper mail.  
 
If the program does terminal interaction, make it output a short  
notice like this when it starts in an interactive mode:  
 
<program> Copyright (C) <year> <name of author>  
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.  
This is free software, and you are welcome to redistribute it  
under certain conditions; type `show c' for details.  
 
The hypothetical commands `show w' and `show c' should show the appropriate  
parts of the General Public License. Of course, your program's commands  
might be different; for a GUI interface, you would use an "about box".  
 
You should also get your employer (if you work as a programmer) or school,  
if any, to sign a "copyright disclaimer" for the program, if necessary.  
For more information on this, and how to apply and follow the GNU GPL, see  
<http://www.gnu.org/licenses/>.  
 
The GNU General Public License does not permit incorporating your program  
into proprietary programs. If your program is a subroutine library, you  
may consider it more useful to permit linking proprietary applications with  
the library. If this is what you want to do, use the GNU Lesser General  
Public License instead of this License. But first, please read  
<http://www.gnu.org/philosophy/why-not-lgpl.html>.  
 
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset='UTF-8'> <meta charset='UTF-8'>
<title>Kerbal Engineer Redux - README</title> <title>Kerbal Engineer Redux - README</title>
<link href='http://fonts.googleapis.com/css?family=PT+Sans:400,700' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=PT+Sans:400,700' rel='stylesheet' type='text/css'>
<script> <script>
function resizeIframe(obj) { function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px'; obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
} }
</script> </script>
<style> <style>
* { * {
margin: 0; padding: 0; margin: 0; padding: 0;
box-sizing: border-box; moz-box-sizing: border-box; webkit-box-sizing: border-box; box-sizing: border-box; moz-box-sizing: border-box; webkit-box-sizing: border-box;
} }
   
html, body { html, body {
height: 100%; height: 100%;
font-family: 'PT Sans', Verdana, Geneva, sans-serif; font-family: 'PT Sans', Verdana, Geneva, sans-serif;
} }
   
a { a {
text-decoration: none; text-decoration: none;
font-weight: 700; font-weight: 700;
color: inherit; color: inherit;
} }
   
a:hover { a:hover {
text-decoration: underline; text-decoration: underline;
} }
   
h3 { h3 {
display: block; display: block;
line-height: 1.5em; line-height: 1.5em;
font-size: 1.1em; font-size: 1.1em;
font-weight: 700; font-weight: 700;
} }
   
p { p {
display: block; display: block;
margin: 0 0.5em; margin: 0 0.5em;
text-align: justify; text-align: justify;
} }
   
ul { ul {
display: block; display: block;
margin-left: 1.5em; margin-left: 1.5em;
list-style-type: square; list-style-type: square;
} }
   
li { li {
margin-top: 0.5em; margin-top: 0.5em;
text-align: justify; text-align: justify;
} }
   
iframe { iframe {
width: 100%; width: 100%;
border: none; border: none;
} }
   
header { header {
display: block; display: block;
padding: 25px; padding: 25px;
text-align: center; text-align: center;
font-size: 3rem; font-size: 3rem;
font-weight: 700; font-weight: 700;
letter-spacing: 0.2em; letter-spacing: 0.2em;
color: white; color: white;
background-color: black; background-color: black;
} }
   
section { section {
display: block; display: block;
margin: 10px; margin: 10px;
padding: 0.5em 1em; padding: 0.5em 1em;
line-height: 1.5em; line-height: 1.5em;
background-color: #DDD; background-color: #DDD;
} }
   
footer { footer {
display: block; display: block;
text-align: center; text-align: center;
line-height: 50px; line-height: 50px;
font-size: 0.8rem; font-size: 0.8rem;
letter-spacing: 0.2em; letter-spacing: 0.2em;
color: white; color: white;
background-color: black; background-color: black;
} }
   
.nested_list > li { .nested_list > li {
margin-top: 1em; margin-top: 1em;
} }
   
.nested_list > li:first-child { .nested_list > li:first-child {
margin-top: 0.5em; margin-top: 0.5em;
} }
   
#root { #root {
clear: both; clear: both;
min-height: 100%; min-height: 100%;
height: auto !important; height: auto !important;
height: 100%; height: 100%;
margin-bottom: -50px; margin-bottom: -50px;
} }
   
#root > #root_footer { #root > #root_footer {
height: 50px; height: 50px;
} }
   
#footer { #footer {
clear: both; clear: both;
position: relative; position: relative;
height: 50px; height: 50px;
} }
</style> </style>
</head> </head>
<body> <body>
<div id='root'> <div id='root'>
<header>Kerbal Engineer Redux v1.0</header> <header>Kerbal Engineer Redux v1.0</header>
   
<section> <section>
<h3>Developers</h3> <h3>Developers</h3>
<p> <p>
CYBUTEK: Primary Development<br> CYBUTEK: Primary Development<br>
Padishar: Simulation Logic Padishar: Simulation Logic
</p> </p>
</section> </section>
   
<section> <section>
<h3>Honourable Mentions</h3> <h3>Honourable Mentions</h3>
<p> <p>
Mic_E: Impact Readouts Mic_E: Impact Readouts
</p> </p>
</section> </section>
   
<section> <section>
<h3>Goto the Forum Thread</h3> <h3>Goto the Forum Thread</h3>
<p> <p>
<a href="http://forum.kerbalspaceprogram.com/threads/18230" target='_blank'>http://forum.kerbalspaceprogram.com/threads/18230</a> <a href="http://forum.kerbalspaceprogram.com/threads/18230" target='_blank'>http://forum.kerbalspaceprogram.com/threads/18230</a>
</p> </p>
</section> </section>
   
<section> <section>
<h3>KSP-AVC Ready</h3> <h3>KSP-AVC Ready</h3>
<p> <p>
KSP Add-on Version Checker is a standardised system for versioning mods. You can get more information on this KSP Add-on Version Checker is a standardised system for versioning mods. You can get more information on this
<a href='http://forum.kerbalspaceprogram.com/threads/79745' target='_blank'>forum thread</a>. <a href='http://forum.kerbalspaceprogram.com/threads/79745' target='_blank'>forum thread</a>.
</p> </p>
</section> </section>
   
<section> <section>
<h3>Contains MiniAVC</h3> <h3>Contains MiniAVC</h3>
<p> <p>
This mod includes version checking using <a href="http://forum.kerbalspaceprogram.com/threads/79745">MiniAVC</a>. If you opt-in, it will use the internet to check whether there is a new version available. Data is only read from the internet and no personal information is sent. For a more comprehensive version checking experience, please download the <a href="http://forum.kerbalspaceprogram.com/threads/79745">KSP-AVC Plugin</a>. This mod includes version checking using <a href="http://forum.kerbalspaceprogram.com/threads/79745">MiniAVC</a>. If you opt-in, it will use the internet to check whether there is a new version available. Data is only read from the internet and no personal information is sent. For a more comprehensive version checking experience, please download the <a href="http://forum.kerbalspaceprogram.com/threads/79745">KSP-AVC Plugin</a>.
</p> </p>
</section> </section>
   
<section> <section>
<h3>Description</h3> <h3>Description</h3>
<p> <p>
This plugin will allow you to view important statistics about your ship on the fly, whilst constructing and in flight. This plugin will allow you to view important statistics about your ship on the fly, whilst constructing and in flight.
</p> </p>
</section> </section>
   
<section> <section>
<h3>Installation</h3> <h3>Installation</h3>
<ul> <ul>
<li>Copy the 'KerbalEngineer' folder into the 'GameData' folder located within your Kerbal Space Program installation directory.</li> <li>Copy the 'KerbalEngineer' folder into the 'GameData' folder located within your Kerbal Space Program installation directory.</li>
<li>The 'Parts' folder including the 'ER7500' and 'EngineerChip' is optional and are only required if running in module mode.</li> <li>The 'Parts' folder including the 'ER7500' and 'EngineerChip' is optional and are only required if running in module mode.</li>
</ul> </ul>
</section> </section>
   
<section> <section>
<h3>Change Log</h3> <h3>Change Log</h3>
<iframe src='CHANGES.txt' onload="this.style.height = this.contentWindow.document.body.scrollHeight + 'px'"></iframe> <iframe src='CHANGES.txt' onload="this.style.height = this.contentWindow.document.body.scrollHeight + 'px'"></iframe>
</section> </section>
   
<section> <section>
<h3>Software License</h3> <h3>Software License</h3>
<p> <p>
Licensed under the <a href='LICENSE.txt'>GNU General Public License v3</a>. Licensed under the <a href='LICENCE.txt'>GNU General Public License v3</a>.
</p> </p>
</section> </section>
   
<div id='root_footer'></div> <div id='root_footer'></div>
</div> </div>
   
<footer id='footer'> <footer id='footer'>
README design by <a href='http://ksp.cybutek.net' target='_blank'><strong>CYBUTEK</strong></a> (GPLv3) README design by <a href='http://ksp.cybutek.net' target='_blank'><strong>CYBUTEK</strong></a> (GPLv3)
</footer> </footer>
</body> </body>
</html> </html>
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives  
   
using System;  
using System.Collections.Generic;  
using System.Linq;  
   
#endregion  
   
namespace KerbalEngineer namespace KerbalEngineer
{ {
  using System;
  using System.Collections.Generic;
  using System.Linq;
   
/* /*
* *
* With thanks to Nathaniel R. Lewis (aka. Teknoman117) (linux.robotdude@gmail.com) for working out * With thanks to Nathaniel R. Lewis (aka. Teknoman117) (linux.robotdude@gmail.com) for working out
* the best way of getting the celestial body information dynamically using PSystemManager. * the best way of getting the celestial body information dynamically using PSystemManager.
* *
*/ */
   
public static class CelestialBodies public static class CelestialBodies
{ {
#region Constructors  
   
static CelestialBodies() static CelestialBodies()
{ {
try try
{ {
SystemBody = new BodyInfo(PSystemManager.Instance.localBodies.Find(b => b.referenceBody == null || b.referenceBody == b)); SystemBody = new BodyInfo(PSystemManager.Instance.localBodies.Find(b => b.referenceBody == null || b.referenceBody == b));
if (!SetSelectedBody("Kerbin")) String homeCBName = Planetarium.fetch.Home.bodyName;
  if (!SetSelectedBody(homeCBName))
{ {
SelectedBody = SystemBody; SelectedBody = SystemBody;
SelectedBody.SetSelected(true); SelectedBody.SetSelected(true);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion  
   
#region Properties  
   
public static BodyInfo SelectedBody { get; private set; } public static BodyInfo SelectedBody { get; private set; }
public static BodyInfo SystemBody { get; private set; } public static BodyInfo SystemBody { get; private set; }
   
#endregion  
   
#region Public Methods  
   
/// <summary> /// <summary>
/// Gets a body given a supplied body name. /// Gets a body given a supplied body name.
/// </summary> /// </summary>
public static BodyInfo GetBodyInfo(string bodyName) public static BodyInfo GetBodyInfo(string bodyName)
{ {
try try
{ {
return SystemBody.GetBodyInfo(bodyName); return SystemBody.GetBodyInfo(bodyName);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
return null; return null;
} }
   
/// <summary> /// <summary>
/// Sets the selected body to one matching the supplied body name. Returns true if successful. /// Sets the selected body to one matching the supplied body name. Returns true if successful.
/// </summary> /// </summary>
public static bool SetSelectedBody(string bodyName) public static bool SetSelectedBody(string bodyName)
{ {
try try
{ {
var body = GetBodyInfo(bodyName); BodyInfo body = GetBodyInfo(bodyName);
if (body != null) if (body != null)
{ {
if (SelectedBody != null) if (SelectedBody != null)
{ {
SelectedBody.SetSelected(false); SelectedBody.SetSelected(false);
} }
SelectedBody = body; SelectedBody = body;
SelectedBody.SetSelected(true); SelectedBody.SetSelected(true);
return true; return true;
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
return false; return false;
} }
   
#endregion  
   
#region Nested type: BodyInfo  
   
public class BodyInfo public class BodyInfo
{ {
#region Constructors  
   
public BodyInfo(CelestialBody body, BodyInfo parent = null) public BodyInfo(CelestialBody body, BodyInfo parent = null)
{ {
try try
{ {
// Set the body information. // Set the body information.
this.CelestialBody = body; CelestialBody = body;
this.Name = body.bodyName; Name = body.bodyName;
this.Gravity = 9.81 * body.GeeASL; Gravity = 9.81 * body.GeeASL;
this.Atmosphere = body.atmosphere ? 101.325 * body.atmosphereMultiplier : 0; Parent = parent;
this.Parent = parent;  
   
// Set orbiting bodies information. // Set orbiting bodies information.
this.Children = new List<BodyInfo>(); Children = new List<BodyInfo>();
foreach (var orbitingBody in body.orbitingBodies) foreach (CelestialBody orbitingBody in body.orbitingBodies)
{ {
this.Children.Add(new BodyInfo(orbitingBody, this)); Children.Add(new BodyInfo(orbitingBody, this));
} }
   
this.SelectedDepth = 0; SelectedDepth = 0;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion public CelestialBody CelestialBody { get; private set; }
  public List<BodyInfo> Children { get; private set; }
#region Properties public double Gravity { get; private set; }
   
public string Name { get; private set; } public string Name { get; private set; }
public double Gravity { get; private set; }  
public double Atmosphere { get; private set; }  
public BodyInfo Parent { get; private set; } public BodyInfo Parent { get; private set; }
public List<BodyInfo> Children { get; private set; }  
public CelestialBody CelestialBody { get; private set; }  
public bool Selected { get; private set; } public bool Selected { get; private set; }
public int SelectedDepth { get; private set; } public int SelectedDepth { get; private set; }
   
#endregion  
   
#region Public Methods  
   
public BodyInfo GetBodyInfo(string bodyName) public BodyInfo GetBodyInfo(string bodyName)
{ {
try try
{ {
// This is the searched body. // This is the searched body.
if (String.Equals(this.Name, bodyName, StringComparison.CurrentCultureIgnoreCase)) if (String.Equals(Name, bodyName, StringComparison.CurrentCultureIgnoreCase))
{ {
return this; return this;
} }
   
// Check to see if any of this bodies children are the searched body. // Check to see if any of this bodies children are the searched body.
foreach (var child in this.Children) foreach (BodyInfo child in Children)
{ {
var body = child.GetBodyInfo(bodyName); BodyInfo body = child.GetBodyInfo(bodyName);
if (body != null) if (body != null)
{ {
return body; return body;
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
   
// A body with the specified name was not found. // A body with the specified name was not found.
return null; return null;
} }
   
  public double GetDensity(double altitude)
  {
  return CelestialBody.GetDensity(GetPressure(altitude), GetTemperature(altitude));
  }
   
  public double GetPressure(double altitude)
  {
  return CelestialBody.GetPressure(altitude);
  }
   
  public double GetTemperature(double altitude)
  {
  return CelestialBody.GetTemperature(altitude);
  }
   
  public double GetAtmospheres(double altitude)
  {
  return GetPressure(altitude) * PhysicsGlobals.KpaToAtmospheres;
  }
   
public void SetSelected(bool state, int depth = 0) public void SetSelected(bool state, int depth = 0)
{ {
this.Selected = state; Selected = state;
this.SelectedDepth = depth; SelectedDepth = depth;
if (this.Parent != null) if (Parent != null)
{ {
this.Parent.SetSelected(state, depth + 1); Parent.SetSelected(state, depth + 1);
} }
} }
   
#endregion  
   
#region Debugging  
   
public override string ToString() public override string ToString()
{ {
var log = "\n" + this.Name + string log = "\n" + Name +
"\n\tGravity: " + this.Gravity + "\n\tGravity: " + Gravity +
"\n\tAtmosphere: " + this.Atmosphere + "\n\tSelected: " + Selected;
"\n\tSelected: " + this.Selected;  
  return Children.Aggregate(log, (current, child) => current + "\n" + child);
return this.Children.Aggregate(log, (current, child) => current + "\n" + child); }
} }
   
#endregion  
}  
   
#endregion  
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
   
using KerbalEngineer.Control.Panels; using KerbalEngineer.Control.Panels;
   
using UnityEngine; using UnityEngine;
   
#endregion #endregion
   
namespace KerbalEngineer.Control namespace KerbalEngineer.Control
{ {
[KSPAddon(KSPAddon.Startup.Instantly, false)] [KSPAddon(KSPAddon.Startup.Instantly, false)]
public class ControlCentre : MonoBehaviour public class ControlCentre : MonoBehaviour
{ {
#region Fields #region Fields
   
private static readonly List<IControlPanel> panels = new List<IControlPanel>(); private static readonly List<IControlPanel> panels = new List<IControlPanel>();
   
private static GUIStyle button; private static GUIStyle button;
private static ControlCentre instance; private static ControlCentre instance;
private static GUIStyle label; private static GUIStyle label;
private static GUIStyle title; private static GUIStyle title;
   
private Vector2 contentsScrollPosition; private Vector2 contentsScrollPosition;
private GUIStyle panelSelectorStyle; private GUIStyle panelSelectorStyle;
private Rect position = new Rect(Screen.width, Screen.height, 900.0f, 500.0f); private Rect position = new Rect(Screen.width, Screen.height, 900.0f, 500.0f);
private IControlPanel selectedPanel; private IControlPanel selectedPanel;
private bool shouldCentre = true; private bool shouldCentre = true;
   
#endregion #endregion
   
#region Properties #region Properties
   
public static GUIStyle Button public static GUIStyle Button
{ {
get get
{ {
return button ?? (button = new GUIStyle(HighLogic.Skin.button) return button ?? (button = new GUIStyle(HighLogic.Skin.button)
{ {
normal = normal =
{ {
textColor = Color.white textColor = Color.white
}, },
fixedHeight = 30.0f fixedHeight = 30.0f
}); });
} }
} }
   
public static bool Enabled public static bool Enabled
{ {
get { return instance.enabled; } get { return instance.enabled; }
set { instance.enabled = value; } set { instance.enabled = value; }
} }
   
public static GUIStyle Label public static GUIStyle Label
{ {
get get
{ {
return label ?? (label = new GUIStyle(HighLogic.Skin.label) return label ?? (label = new GUIStyle(HighLogic.Skin.label)
{ {
normal = normal =
{ {
textColor = Color.white textColor = Color.white
}, },
fontStyle = FontStyle.Bold, fontStyle = FontStyle.Bold,
fixedHeight = 30.0f, fixedHeight = 30.0f,
alignment = TextAnchor.MiddleLeft, alignment = TextAnchor.MiddleLeft,
stretchWidth = true, stretchWidth = true,
}); });
} }
} }
   
public static List<IControlPanel> Panels public static List<IControlPanel> Panels
{ {
get { return panels; } get { return panels; }
} }
   
public static GUIStyle Title public static GUIStyle Title
{ {
get get
{ {
return title ?? (title = new GUIStyle(HighLogic.Skin.label) return title ?? (title = new GUIStyle(HighLogic.Skin.label)
{ {
normal = normal =
{ {
textColor = Color.white textColor = Color.white
}, },
fontSize = 26, fontSize = 26,
fontStyle = FontStyle.Bold, fontStyle = FontStyle.Bold,
alignment = TextAnchor.UpperCenter, alignment = TextAnchor.UpperCenter,
stretchWidth = true, stretchWidth = true,
}); });
} }
} }
   
#endregion #endregion
   
#region Methods: protected #region Methods: protected
   
protected void Awake() protected void Awake()
{ {
try try
{ {
if (instance == null) if (instance == null)
{ {
DontDestroyOnLoad(this); DontDestroyOnLoad(this);
instance = this; instance = this;
this.enabled = false; this.enabled = false;
return; return;
} }
Destroy(this); Destroy(this);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
protected void OnGUI() protected void OnGUI()
{ {
try try
{ {
GUI.skin = null; GUI.skin = null;
this.position = GUILayout.Window(this.GetInstanceID(), this.position, this.Window, "KERBAL ENGINEER REDUX " + EngineerGlobals.AssemblyVersion + " - CONTROL CENTRE", HighLogic.Skin.window); this.position = GUILayout.Window(this.GetInstanceID(), this.position, this.Window, "KERBAL ENGINEER REDUX " + EngineerGlobals.ASSEMBLY_VERSION + " - CONTROL CENTRE", HighLogic.Skin.window);
this.CentreWindow(); this.CentreWindow();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
protected void Start() protected void Start()
{ {
try try
{ {
this.InitialiseStyles(); this.InitialiseStyles();
LoadPanels(); LoadPanels();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion #endregion
   
#region Methods: private #region Methods: private
   
private static void LoadPanels() private static void LoadPanels()
{ {
panels.Add(new BuildEngineerPanel()); panels.Add(new BuildEngineerPanel());
panels.Add(new BuildOverlayPanel()); panels.Add(new BuildOverlayPanel());
} }
   
private void CentreWindow() private void CentreWindow()
{ {
if (this.shouldCentre && this.position.width > 0.0f && this.position.height > 0.0f) if (this.shouldCentre && this.position.width > 0.0f && this.position.height > 0.0f)
{ {
this.position.center = new Vector2(Screen.width * 0.5f, Screen.height * 0.5f); this.position.center = new Vector2(Screen.width * 0.5f, Screen.height * 0.5f);
this.shouldCentre = false; this.shouldCentre = false;
} }
} }
   
private void DrawContents() private void DrawContents()
{ {
GUI.skin = HighLogic.Skin; GUI.skin = HighLogic.Skin;
this.contentsScrollPosition = GUILayout.BeginScrollView(this.contentsScrollPosition, false, true); this.contentsScrollPosition = GUILayout.BeginScrollView(this.contentsScrollPosition, false, true);
GUI.skin = null; GUI.skin = null;
   
if (this.selectedPanel != null) if (this.selectedPanel != null)
{ {
this.selectedPanel.Draw(); this.selectedPanel.Draw();
} }
   
GUILayout.FlexibleSpace(); GUILayout.FlexibleSpace();
GUILayout.EndScrollView(); GUILayout.EndScrollView();
} }
   
private void DrawSelectors() private void DrawSelectors()
{ {
GUILayout.BeginVertical(HighLogic.Skin.box, GUILayout.Width(225.0f)); GUILayout.BeginVertical(HighLogic.Skin.box, GUILayout.Width(225.0f));
foreach (var panel in panels) foreach (var panel in panels)
{ {
if (GUILayout.Toggle(this.selectedPanel == panel, panel.Name, this.panelSelectorStyle)) if (GUILayout.Toggle(this.selectedPanel == panel, panel.Name, this.panelSelectorStyle))
{ {
this.selectedPanel = panel; this.selectedPanel = panel;
} }
} }
GUILayout.FlexibleSpace(); GUILayout.FlexibleSpace();
if (GUILayout.Button("CLOSE", Button)) if (GUILayout.Button("CLOSE", Button))
{ {
this.enabled = false; this.enabled = false;
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
private void InitialiseStyles() private void InitialiseStyles()
{ {
this.panelSelectorStyle = new GUIStyle(Button) this.panelSelectorStyle = new GUIStyle(Button)
{ {
fontSize = 16, fontSize = 16,
fixedHeight = 40.0f fixedHeight = 40.0f
}; };
} }
   
private void Window(int windowId) private void Window(int windowId)
{ {
try try
{ {
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
this.DrawSelectors(); this.DrawSelectors();
this.DrawContents(); this.DrawContents();
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives  
   
using System;  
using System.Linq;  
   
using KerbalEngineer.Extensions;  
using KerbalEngineer.Flight;  
using KerbalEngineer.Helpers;  
using KerbalEngineer.Settings;  
using KerbalEngineer.UIControls;  
using KerbalEngineer.VesselSimulator;  
   
using UnityEngine;  
   
#endregion  
   
namespace KerbalEngineer.Editor namespace KerbalEngineer.Editor
{ {
  #region Using Directives
  using System;
  using Extensions;
  using Flight;
  using Helpers;
  using Settings;
  using UIControls;
  using UnityEngine;
  using VesselSimulator;
   
  #endregion
   
[KSPAddon(KSPAddon.Startup.EditorAny, false)] [KSPAddon(KSPAddon.Startup.EditorAny, false)]
public class BuildAdvanced : MonoBehaviour public class BuildAdvanced : MonoBehaviour
{ {
#region Fields #region Fields
  public static float Altitude = 0.0f;
   
private GUIStyle areaSettingStyle; private GUIStyle areaSettingStyle;
private GUIStyle areaStyle; private GUIStyle areaStyle;
private float atmosphericPercentage = 1.0f; private float atmosphericMach;
private float atmosphericVelocity;  
private GUIStyle bodiesButtonActiveStyle; private GUIStyle bodiesButtonActiveStyle;
private GUIStyle bodiesButtonStyle; private GUIStyle bodiesButtonStyle;
private DropDown bodiesList; private DropDown bodiesList;
private Rect bodiesListPosition; private Rect bodiesListPosition;
private GUIStyle buttonStyle; private GUIStyle buttonStyle;
private int compactCheck; private int compactCheck;
private bool compactCollapseRight; private bool compactCollapseRight;
private bool compactMode; private bool compactMode;
private float compactRight; private float compactRight;
private bool hasChanged; private bool hasChanged;
private GUIStyle infoStyle; private GUIStyle infoStyle;
private bool isEditorLocked; private bool isEditorLocked;
  private float maxMach;
private int numberOfStages; private int numberOfStages;
private Rect position = new Rect(265.0f, 45.0f, 0, 0); private Rect position = new Rect(265.0f, 45.0f, 0, 0);
private GUIStyle settingAtmoStyle; private GUIStyle settingAtmoStyle;
private GUIStyle settingStyle; private GUIStyle settingStyle;
private bool showAllStages; private bool showAllStages;
private bool showAtmosphericDetails; private bool showAtmosphericDetails;
private bool showSettings; private bool showSettings;
private Stage[] stages; private Stage[] stages;
private GUIStyle titleStyle; private GUIStyle titleStyle;
private bool visible = true; private bool visible = true;
private GUIStyle windowStyle; private GUIStyle windowStyle;
   
#endregion #endregion
   
#region Properties #region Properties
   
/// <summary> /// <summary>
/// Gets the current instance if started or returns null. /// Gets the current instance if started or returns null.
/// </summary> /// </summary>
public static BuildAdvanced Instance { get; private set; } public static BuildAdvanced Instance { get; private set; }
   
/// <summary> /// <summary>
/// Gets and sets whether to show in compact mode. /// Gets and sets whether to show in compact mode.
/// </summary> /// </summary>
public bool CompactMode public bool CompactMode
{ {
get { return this.compactMode; } get
set { this.compactMode = value; } {
  return compactMode;
  }
  set
  {
  compactMode = value;
  }
} }
   
/// <summary> /// <summary>
/// Gets and sets whether to show all stages. /// Gets and sets whether to show all stages.
/// </summary> /// </summary>
public bool ShowAllStages public bool ShowAllStages
{ {
get { return this.showAllStages; } get
set { this.showAllStages = value; } {
  return showAllStages;
  }
  set
  {
  showAllStages = value;
  }
} }
   
/// <summary> /// <summary>
/// Gets and sets whether to use atmospheric details. /// Gets and sets whether to use atmospheric details.
/// </summary> /// </summary>
public bool ShowAtmosphericDetails public bool ShowAtmosphericDetails
{ {
get { return this.showAtmosphericDetails; } get
set { this.showAtmosphericDetails = value; } {
  return showAtmosphericDetails;
  }
  set
  {
  showAtmosphericDetails = value;
  }
} }
   
/// <summary> /// <summary>
/// Gets and sets whether to show the settings display. /// Gets and sets whether to show the settings display.
/// </summary> /// </summary>
public bool ShowSettings public bool ShowSettings
{ {
get { return this.showSettings; } get
set { this.showSettings = value; } {
  return showSettings;
  }
  set
  {
  showSettings = value;
  }
} }
   
/// <summary> /// <summary>
/// Gets and sets whether the display is enabled. /// Gets and sets whether the display is enabled.
/// </summary> /// </summary>
public bool Visible public bool Visible
{ {
get { return this.visible; } get
set { this.visible = value; } {
} return visible;
  }
  set
  {
  visible = value;
  }
  }
#endregion #endregion
   
#region Methods: protected #region Methods
  private static Rect compactModeRect = new Rect(0.0f, 5.0f, 0.0f, 20.0f);
  private static Stage stage;
  private static int stagesCount;
  private static int stagesLength;
  private static string title;
   
protected void Awake() protected void Awake()
{ {
try try
{ {
Instance = this; Instance = this;
this.bodiesList = this.gameObject.AddComponent<DropDown>(); bodiesList = gameObject.AddComponent<DropDown>();
this.bodiesList.DrawCallback = this.DrawBodiesList; bodiesList.DrawCallback = DrawBodiesList;
this.Load(); Load();
   
  SimManager.UpdateModSettings();
  SimManager.OnReady -= GetStageInfo;
  SimManager.OnReady += GetStageInfo;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex, "BuildAdvanced.Awake()");
} }
} }
   
/// <summary> /// <summary>
/// Saves the settings when this object is destroyed. /// Saves the settings when this object is destroyed.
/// </summary> /// </summary>
protected void OnDestroy() protected void OnDestroy()
{ {
try try
{ {
var handler = new SettingHandler(); SettingHandler handler = new SettingHandler();
handler.Set("visible", this.visible); handler.Set("visible", visible);
handler.Set("windowPositionX", this.position.x); handler.Set("windowPositionX", position.x);
handler.Set("windowPositionY", this.position.y); handler.Set("windowPositionY", position.y);
handler.Set("compactMode", this.compactMode); handler.Set("compactMode", compactMode);
handler.Set("compactCollapseRight", this.compactCollapseRight); handler.Set("compactCollapseRight", compactCollapseRight);
handler.Set("showAllStages", this.showAllStages); handler.Set("showAllStages", showAllStages);
handler.Set("showAtmosphericDetails", this.showAtmosphericDetails); handler.Set("showAtmosphericDetails", showAtmosphericDetails);
handler.Set("showSettings", this.showSettings); handler.Set("showSettings", showSettings);
handler.Set("selectedBodyName", CelestialBodies.SelectedBody.Name); handler.Set("selectedBodyName", CelestialBodies.SelectedBody.Name);
handler.Save("BuildAdvanced.xml"); handler.Save("BuildAdvanced.xml");
GuiDisplaySize.OnSizeChanged -= this.OnSizeChanged; GuiDisplaySize.OnSizeChanged -= OnSizeChanged;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex, "BuildAdvanced.OnDestroy()");
} }
} }
   
protected void OnGUI() protected void OnGUI()
{ {
try try
{ {
if (!this.visible || EditorLogic.fetch == null || EditorLogic.fetch.ship.parts.Count == 0 || EditorLogic.fetch.editorScreen != EditorLogic.EditorScreen.Parts) if (!visible || EditorLogic.fetch == null || EditorLogic.fetch.ship.parts.Count == 0 || EditorLogic.fetch.editorScreen != EditorScreen.Parts)
{ {
return; return;
} }
   
if (SimManager.ResultsReady()) if (stages == null)
{  
this.stages = SimManager.Stages;  
}  
   
SimManager.RequestSimulation();  
   
if (this.stages == null)  
{ {
return; return;
} }
   
// Change the window title based on whether in compact mode or not. // Change the window title based on whether in compact mode or not.
var title = !this.compactMode ? "KERBAL ENGINEER REDUX " + EngineerGlobals.AssemblyVersion : "K.E.R. " + EngineerGlobals.AssemblyVersion + (this.showAtmosphericDetails ? " (ATMOS.)" : String.Empty); title = !compactMode ? "KERBAL ENGINEER REDUX " + EngineerGlobals.ASSEMBLY_VERSION : "K.E.R. " + EngineerGlobals.ASSEMBLY_VERSION;
   
// Reset the window size when the staging or something else has changed. // Reset the window size when the staging or something else has changed.
var stageCount = this.stages.Count(stage => this.showAllStages || stage.deltaV > 0); stagesLength = stages.Length;
if (this.hasChanged || stageCount != this.numberOfStages) if (showAllStages)
{ {
this.hasChanged = false; stagesCount = stagesLength;
this.numberOfStages = stageCount; }
  if (showAllStages == false)
this.position.width = 0; {
this.position.height = 0; stagesCount = 0;
  for (int i = 0; i < stagesLength; ++i)
  {
  if (stages[i].deltaV > 0.0f)
  {
  stagesCount = stagesCount + 1;
  }
  }
  }
   
  if (hasChanged || stagesCount != numberOfStages)
  {
  hasChanged = false;
  numberOfStages = stagesCount;
   
  position.width = 0;
  position.height = 0;
} }
   
GUI.skin = null; GUI.skin = null;
this.position = GUILayout.Window(this.GetInstanceID(), this.position, this.Window, title, this.windowStyle).ClampToScreen(); position = GUILayout.Window(GetInstanceID(), position, Window, title, windowStyle).ClampToScreen();
   
if (this.compactCheck > 0 && this.compactCollapseRight) if (compactCheck > 0 && compactCollapseRight)
{ {
this.position.x = this.compactRight - this.position.width; position.x = compactRight - position.width;
this.compactCheck--; compactCheck--;
} }
else if (this.compactCheck > 0) else if (compactCheck > 0)
{ {
this.compactCheck = 0; compactCheck = 0;
} }
   
// Check editor lock to manage click-through. // Check editor lock to manage click-through.
this.CheckEditorLock(); CheckEditorLock();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex, "BuildAdvanced.OnGUI()");
} }
} }
   
protected void Start() protected void Start()
{ {
try try
{ {
this.InitialiseStyles(); InitialiseStyles();
GuiDisplaySize.OnSizeChanged += this.OnSizeChanged; GuiDisplaySize.OnSizeChanged += OnSizeChanged;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex, "BuildAdvanced.Start()");
} }
} }
   
protected void Update() protected void Update()
{ {
try try
{ {
if (Input.GetKeyDown(KeyBinder.EditorShowHide)) if (Input.GetKeyDown(KeyBinder.EditorShowHide))
{ {
this.visible = !this.visible; visible = !visible;
} if (!visible)
  {
if (!this.visible || EditorLogic.fetch == null || EditorLogic.fetch.ship.parts.Count == 0) EditorLock(false);
{ }
this.bodiesList.enabled = false; }
   
  if (!visible || EditorLogic.fetch == null || EditorLogic.fetch.ship.parts.Count == 0)
  {
  bodiesList.enabled = false;
return; return;
} }
   
// Configure the simulation parameters based on the selected reference body. // Configure the simulation parameters based on the selected reference body.
SimManager.Gravity = CelestialBodies.SelectedBody.Gravity; SimManager.Gravity = CelestialBodies.SelectedBody.Gravity;
   
if (this.showAtmosphericDetails) if (showAtmosphericDetails)
{ {
SimManager.Atmosphere = CelestialBodies.SelectedBody.Atmosphere * 0.01d * this.atmosphericPercentage; SimManager.Atmosphere = CelestialBodies.SelectedBody.GetAtmospheres(Altitude);
} }
else else
{ {
SimManager.Atmosphere = 0; SimManager.Atmosphere = 0;
} }
   
SimManager.Velocity = this.atmosphericVelocity; SimManager.Mach = atmosphericMach;
   
  SimManager.RequestSimulation();
SimManager.TryStartSimulation(); SimManager.TryStartSimulation();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex, "BuildAdvanced->Update"); Logger.Exception(ex, "BuildAdvanced.Update()");
} }
} }
   
#endregion  
   
#region Methods: private  
   
/// <summary> /// <summary>
/// Checks whether the editor should be locked to stop click-through. /// Checks whether the editor should be locked to stop click-through.
/// </summary> /// </summary>
private void CheckEditorLock() private void CheckEditorLock()
{ {
if ((this.position.MouseIsOver() || this.bodiesList.Position.MouseIsOver()) && !this.isEditorLocked) if ((position.MouseIsOver() || bodiesList.Position.MouseIsOver()) && !isEditorLocked)
{ {
EditorLogic.fetch.Lock(true, true, true, "KER_BuildAdvanced"); EditorLock(true);
BuildOverlayPartInfo.Hidden = true; }
this.isEditorLocked = true; else if (!position.MouseIsOver() && !bodiesList.Position.MouseIsOver() && isEditorLocked)
} {
else if (!this.position.MouseIsOver() && !this.bodiesList.Position.MouseIsOver() && this.isEditorLocked) EditorLock(false);
{  
EditorLogic.fetch.Unlock("KER_BuildAdvanced");  
BuildOverlayPartInfo.Hidden = false;  
this.isEditorLocked = false;  
} }
} }
   
/// <summary> /// <summary>
/// Draws the atmospheric settings. /// Draws the atmospheric settings.
/// </summary> /// </summary>
private void DrawAtmosphericDetails() private void DrawAtmosphericDetails()
{ {
GUILayout.BeginHorizontal(); try
GUILayout.BeginVertical(); {
GUILayout.Label("Pressure: " + (this.atmosphericPercentage * 100.0f).ToString("F1") + "%", this.settingAtmoStyle, GUILayout.Width(125.0f * GuiDisplaySize.Offset)); GUILayout.BeginHorizontal();
GUI.skin = HighLogic.Skin; GUILayout.BeginVertical();
this.atmosphericPercentage = GUILayout.HorizontalSlider(this.atmosphericPercentage, 0, 1.0f); GUILayout.Label("Altitude: " + (Altitude * 0.001f).ToString("F1") + "km", settingAtmoStyle, GUILayout.Width(125.0f * GuiDisplaySize.Offset));
GUI.skin = null; GUI.skin = HighLogic.Skin;
GUILayout.EndVertical(); Altitude = GUILayout.HorizontalSlider(Altitude, 0.0f, (float)(CelestialBodies.SelectedBody.CelestialBody.atmosphereDepth));
  GUI.skin = null;
GUILayout.Space(5.0f); GUILayout.EndVertical();
   
GUILayout.BeginVertical(); GUILayout.Space(5.0f);
GUILayout.Label("Velocity: " + this.atmosphericVelocity.ToString("F1") + "m/s", this.settingAtmoStyle, GUILayout.Width(125.0f * GuiDisplaySize.Offset));  
GUI.skin = HighLogic.Skin; GUILayout.BeginVertical();
this.atmosphericVelocity = GUILayout.HorizontalSlider(this.atmosphericVelocity, 0, 2500f); GUILayout.Label("Mach: " + atmosphericMach.ToString("F2"), settingAtmoStyle, GUILayout.Width(125.0f * GuiDisplaySize.Offset));
GUI.skin = null; GUI.skin = HighLogic.Skin;
GUILayout.EndVertical(); atmosphericMach = GUILayout.HorizontalSlider(Mathf.Clamp(atmosphericMach, 0.0f, maxMach), 0.0f, maxMach);
GUILayout.EndHorizontal(); GUI.skin = null;
  GUILayout.EndVertical();
  GUILayout.EndHorizontal();
  }
  catch (Exception ex)
  {
  Logger.Exception(ex, "BuildAdvanced.DrawAtmosphericDetails()");
  }
} }
   
private void DrawBodiesList() private void DrawBodiesList()
{ {
if (CelestialBodies.SystemBody == CelestialBodies.SelectedBody) if (CelestialBodies.SystemBody == CelestialBodies.SelectedBody)
{ {
this.DrawBody(CelestialBodies.SystemBody); DrawBody(CelestialBodies.SystemBody);
} }
else else
{ {
foreach (var body in CelestialBodies.SystemBody.Children) foreach (CelestialBodies.BodyInfo body in CelestialBodies.SystemBody.Children)
{ {
this.DrawBody(body); DrawBody(body);
} }
} }
} }
   
private void DrawBody(CelestialBodies.BodyInfo bodyInfo, int depth = 0) private void DrawBody(CelestialBodies.BodyInfo bodyInfo, int depth = 0)
{ {
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
GUILayout.Space(20.0f * depth); GUILayout.Space(20.0f * depth);
if (GUILayout.Button(bodyInfo.Children.Count > 0 ? bodyInfo.Name + " [" + bodyInfo.Children.Count + "]" : bodyInfo.Name, bodyInfo.Selected && bodyInfo.SelectedDepth == 0 ? this.bodiesButtonActiveStyle : this.bodiesButtonStyle)) if (GUILayout.Button(bodyInfo.Children.Count > 0 ? bodyInfo.Name + " [" + bodyInfo.Children.Count + "]" : bodyInfo.Name, bodyInfo.Selected && bodyInfo.SelectedDepth == 0 ? bodiesButtonActiveStyle : bodiesButtonStyle))
{ {
CelestialBodies.SetSelectedBody(bodyInfo.Name); CelestialBodies.SetSelectedBody(bodyInfo.Name);
this.bodiesList.Resize = true; Altitude = 0.0f;
  bodiesList.Resize = true;
} }
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
if (bodyInfo.Selected) if (bodyInfo.Selected)
{ {
foreach (var body in bodyInfo.Children) for (int i = 0; i < bodyInfo.Children.Count; ++i)
{ {
this.DrawBody(body, depth + 1); DrawBody(bodyInfo.Children[i], depth + 1);
} }
} }
} }
   
/// <summary> /// <summary>
/// Draws the burn time column. /// Draws the burn time column.
/// </summary> /// </summary>
private void DrawBurnTime() private void DrawBurnTime()
{ {
GUILayout.BeginVertical(GUILayout.Width(75.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(75.0f * GuiDisplaySize.Offset));
GUILayout.Label("BURN", this.titleStyle); GUILayout.Label("BURN", titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label(TimeFormatter.ConvertToString(stage.time), this.infoStyle); {
  GUILayout.Label(TimeFormatter.ConvertToString(stage.time), infoStyle);
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
/// <summary> /// <summary>
/// Draws the cost column. /// Draws the cost column.
/// </summary> /// </summary>
private void DrawCost() private void DrawCost()
{ {
GUILayout.BeginVertical(GUILayout.Width(110.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(110.0f * GuiDisplaySize.Offset));
GUILayout.Label("COST", this.titleStyle); GUILayout.Label("COST", titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label(Units.Concat(stage.cost, stage.totalCost), this.infoStyle); {
  GUILayout.Label(Units.Cost(stage.cost, stage.totalCost), infoStyle);
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
/// <summary> /// <summary>
/// Draws the deltaV column. /// Draws the deltaV column.
/// </summary> /// </summary>
private void DrawDeltaV() private void DrawDeltaV()
{ {
GUILayout.BeginVertical(GUILayout.Width(100.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(100.0f * GuiDisplaySize.Offset));
GUILayout.Label("DELTA-V", this.titleStyle); GUILayout.Label("DELTA-V", titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label(stage.deltaV.ToString("N0") + " / " + stage.inverseTotalDeltaV.ToString("N0") + "m/s", this.infoStyle); {
  GUILayout.Label(stage.deltaV.ToString("N0") + " / " + stage.inverseTotalDeltaV.ToString("N0") + "m/s", infoStyle);
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
/// <summary> /// <summary>
/// Draws the specific impluse column. /// Draws the specific impluse column.
/// </summary> /// </summary>
private void DrawIsp() private void DrawIsp()
{ {
GUILayout.BeginVertical(GUILayout.Width(75.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(75.0f * GuiDisplaySize.Offset));
GUILayout.Label("ISP", this.titleStyle); GUILayout.Label("ISP", titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label(stage.isp.ToString("F1") + "s", this.infoStyle); {
  GUILayout.Label(stage.isp.ToString("F1") + "s", infoStyle);
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
/// <summary> /// <summary>
/// Draws the mass column. /// Draws the mass column.
/// </summary> /// </summary>
private void DrawMass() private void DrawMass()
{ {
GUILayout.BeginVertical(GUILayout.Width(110.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(110.0f * GuiDisplaySize.Offset));
GUILayout.Label("MASS", this.titleStyle); GUILayout.Label("MASS", titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label(Units.ToMass(stage.mass, stage.totalMass), this.infoStyle); {
  GUILayout.Label(Units.ToMass(stage.mass, stage.totalMass), infoStyle);
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
/// <summary> /// <summary>
/// Draws the part count column. /// Draws the part count column.
/// </summary> /// </summary>
private void DrawPartCount() private void DrawPartCount()
{ {
GUILayout.BeginVertical(GUILayout.Width(50.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(50.0f * GuiDisplaySize.Offset));
GUILayout.Label("PARTS", this.titleStyle); GUILayout.Label("PARTS", titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label(stage.partCount.ToString("N0"), this.infoStyle); {
  GUILayout.Label(stage.partCount + " / " + stage.totalPartCount, infoStyle);
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
/// <summary> /// <summary>
/// Draws the settings panel. /// Draws the settings panel.
/// </summary> /// </summary>
private void DrawSettings() private void DrawSettings()
{ {
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
GUILayout.Label("Compact mode collapses to the:", this.settingStyle); GUILayout.Label("Compact mode collapses to the:", settingStyle);
this.compactCollapseRight = !GUILayout.Toggle(!this.compactCollapseRight, "LEFT", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)); compactCollapseRight = !GUILayout.Toggle(!compactCollapseRight, "LEFT", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
this.compactCollapseRight = GUILayout.Toggle(this.compactCollapseRight, "RIGHT", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)); compactCollapseRight = GUILayout.Toggle(compactCollapseRight, "RIGHT", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
GUILayout.Label("Build Engineer Overlay:", this.settingStyle); GUILayout.Label("Simulate using vectored thrust values:");
BuildOverlay.Visible = GUILayout.Toggle(BuildOverlay.Visible, "VISIBLE", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)); SimManager.vectoredThrust = GUILayout.Toggle(SimManager.vectoredThrust, "ENABLED", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
BuildOverlayPartInfo.NamesOnly = GUILayout.Toggle(BuildOverlayPartInfo.NamesOnly, "NAMES ONLY", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));  
BuildOverlayPartInfo.ClickToOpen = GUILayout.Toggle(BuildOverlayPartInfo.ClickToOpen, "CLICK TO OPEN", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));  
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
GUILayout.Label("Flight Engineer activation mode:", this.settingStyle); GUILayout.Label("Verbose Simulation Log:");
FlightEngineerPartless.IsPartless = GUILayout.Toggle(FlightEngineerPartless.IsPartless, "PARTLESS", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)); SimManager.logOutput = GUILayout.Toggle(SimManager.logOutput, "ENABLED", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
FlightEngineerPartless.IsPartless = !GUILayout.Toggle(!FlightEngineerPartless.IsPartless, "MODULE", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));  
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
GUILayout.Label("GUI Size: " + GuiDisplaySize.Increment, this.settingStyle); GUILayout.Label("Build Engineer Overlay:", settingStyle);
if (GUILayout.Button("<", this.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.ClickToOpen = GUILayout.Toggle(BuildOverlayPartInfo.ClickToOpen, "CLICK TO OPEN", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
  GUILayout.EndHorizontal();
   
  GUILayout.BeginHorizontal();
  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, "PARTLESS", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
  GUILayout.EndHorizontal();
   
  GUILayout.BeginHorizontal();
  GUILayout.Label("Flight Engineer Career Limitations:", settingStyle);
  FlightEngineerCore.IsKerbalLimited = GUILayout.Toggle(FlightEngineerCore.IsKerbalLimited, "KERBAL", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
  FlightEngineerCore.IsTrackingStationLimited = GUILayout.Toggle(FlightEngineerCore.IsTrackingStationLimited, "TRACKING", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));
  GUILayout.EndHorizontal();
   
  GUILayout.BeginHorizontal();
  GUILayout.Label("GUI Size: " + GuiDisplaySize.Increment, settingStyle);
  if (GUILayout.Button("<", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)))
{ {
GuiDisplaySize.Increment--; GuiDisplaySize.Increment--;
} }
if (GUILayout.Button(">", this.buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset))) if (GUILayout.Button(">", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)))
{ {
GuiDisplaySize.Increment++; GuiDisplaySize.Increment++;
} }
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.Label("Minimum delay between simulations: " + SimManager.minSimTime + "ms", this.settingStyle); GUILayout.Label("Minimum delay between simulations: " + SimManager.minSimTime.TotalMilliseconds + "ms", settingStyle);
GUI.skin = HighLogic.Skin; GUI.skin = HighLogic.Skin;
SimManager.minSimTime = (long)GUILayout.HorizontalSlider(SimManager.minSimTime, 0, 2000.0f); SimManager.minSimTime = TimeSpan.FromMilliseconds(GUILayout.HorizontalSlider((float)SimManager.minSimTime.TotalMilliseconds, 0, 2000.0f));
GUI.skin = null; GUI.skin = null;
} }
   
/// <summary> /// <summary>
/// Draws the stage number column. /// Draws the stage number column.
/// </summary> /// </summary>
private void DrawStageNumbers() private void DrawStageNumbers()
{ {
GUILayout.BeginVertical(GUILayout.Width(30.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(30.0f * GuiDisplaySize.Offset));
GUILayout.Label(string.Empty, this.titleStyle); GUILayout.Label(string.Empty, titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label("S" + stage.number, this.titleStyle); {
  GUILayout.Label("S" + stage.number, titleStyle);
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
/// <summary> /// <summary>
/// Draws the thrust column. /// Draws the thrust column.
/// </summary> /// </summary>
private void DrawThrust() private void DrawThrust()
{ {
GUILayout.BeginVertical(GUILayout.Width(75.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(75.0f * GuiDisplaySize.Offset));
GUILayout.Label("THRUST", this.titleStyle); GUILayout.Label("THRUST", titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label(stage.thrust.ToForce(), this.infoStyle); {
  GUILayout.Label(stage.thrust.ToForce(), infoStyle);
  }
  }
  GUILayout.EndVertical();
  }
   
  /// <summary>
  /// Draws the torque column.
  /// </summary>
  private void DrawTorque()
  {
  GUILayout.BeginVertical(GUILayout.Width(75.0f * GuiDisplaySize.Offset));
  GUILayout.Label("TORQUE", titleStyle);
  for (int i = 0; i < stagesLength; ++i)
  {
  stage = stages[i];
  if (showAllStages || stage.deltaV > 0.0)
  {
  GUILayout.Label(stage.maxThrustTorque.ToTorque(), infoStyle);
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
/// <summary> /// <summary>
/// Drwas the thrust to weight ratio column. /// Drwas the thrust to weight ratio column.
/// </summary> /// </summary>
private void DrawTwr() private void DrawTwr()
{ {
GUILayout.BeginVertical(GUILayout.Width(100.0f * GuiDisplaySize.Offset)); GUILayout.BeginVertical(GUILayout.Width(100.0f * GuiDisplaySize.Offset));
GUILayout.Label("TWR (MAX)", this.titleStyle); GUILayout.Label("TWR (MAX)", titleStyle);
foreach (var stage in this.stages) for (int i = 0; i < stagesLength; ++i)
{ {
if (this.showAllStages || stage.deltaV > 0) stage = stages[i];
{ if (showAllStages || stage.deltaV > 0.0)
GUILayout.Label(stage.thrustToWeight.ToString("F2") + " (" + stage.maxThrustToWeight.ToString("F2") + ")", this.infoStyle); {
} GUILayout.Label(stage.thrustToWeight.ToString("F2") + " (" + stage.maxThrustToWeight.ToString("F2") + ")", infoStyle);
} }
GUILayout.EndVertical(); }
  GUILayout.EndVertical();
  }
   
  private void EditorLock(bool state)
  {
  if (state)
  {
  InputLockManager.SetControlLock(ControlTypes.All, "KER_BuildAdvanced");
  BuildOverlayPartInfo.Hidden = true;
  isEditorLocked = true;
  }
  else
  {
  InputLockManager.SetControlLock(ControlTypes.None, "KER_BuildAdvanced");
  BuildOverlayPartInfo.Hidden = false;
  isEditorLocked = false;
  }
  }
   
  private void GetStageInfo()
  {
  stages = SimManager.Stages;
  if (stages != null && stages.Length > 0)
  {
  maxMach = stages[stages.Length - 1].maxMach;
  }
} }
   
/// <summary> /// <summary>
/// Initialises all the styles that are required. /// Initialises all the styles that are required.
/// </summary> /// </summary>
private void InitialiseStyles() private void InitialiseStyles()
{ {
this.windowStyle = new GUIStyle(HighLogic.Skin.window) windowStyle = new GUIStyle(HighLogic.Skin.window)
{ {
alignment = TextAnchor.UpperLeft alignment = TextAnchor.UpperLeft
}; };
   
this.areaStyle = new GUIStyle(HighLogic.Skin.box) areaStyle = new GUIStyle(HighLogic.Skin.box)
{ {
padding = new RectOffset(0, 0, 9, 0) padding = new RectOffset(0, 0, 9, 0)
}; };
   
this.areaSettingStyle = new GUIStyle(HighLogic.Skin.box) areaSettingStyle = new GUIStyle(HighLogic.Skin.box)
{ {
padding = new RectOffset(10, 10, 10, 10) padding = new RectOffset(10, 10, 10, 10)
}; };
   
this.buttonStyle = new GUIStyle(HighLogic.Skin.button) buttonStyle = new GUIStyle(HighLogic.Skin.button)
{ {
normal = normal =
{ {
textColor = Color.white textColor = Color.white
}, },
fontSize = (int)(11 * GuiDisplaySize.Offset), fontSize = (int)(11 * GuiDisplaySize.Offset),
fontStyle = FontStyle.Bold, fontStyle = FontStyle.Bold,
alignment = TextAnchor.MiddleCenter alignment = TextAnchor.MiddleCenter
}; };
   
this.titleStyle = new GUIStyle(HighLogic.Skin.label) titleStyle = new GUIStyle(HighLogic.Skin.label)
{ {
normal = normal =
{ {
textColor = Color.white textColor = Color.white
}, },
fontSize = (int)(11 * GuiDisplaySize.Offset), fontSize = (int)(11 * GuiDisplaySize.Offset),
fontStyle = FontStyle.Bold, fontStyle = FontStyle.Bold,
alignment = TextAnchor.MiddleCenter, alignment = TextAnchor.MiddleCenter,
stretchWidth = true, stretchWidth = true,
}; };
   
this.infoStyle = new GUIStyle(HighLogic.Skin.label) infoStyle = new GUIStyle(HighLogic.Skin.label)
{ {
fontSize = (int)(11 * GuiDisplaySize.Offset), fontSize = (int)(11 * GuiDisplaySize.Offset),
fontStyle = FontStyle.Bold, fontStyle = FontStyle.Bold,
alignment = TextAnchor.MiddleCenter, alignment = TextAnchor.MiddleCenter,
stretchWidth = true stretchWidth = true
}; };
   
this.settingStyle = new GUIStyle(this.titleStyle) settingStyle = new GUIStyle(titleStyle)
{ {
alignment = TextAnchor.MiddleLeft, alignment = TextAnchor.MiddleLeft,
stretchWidth = true, stretchWidth = true,
stretchHeight = true stretchHeight = true
}; };
   
this.settingAtmoStyle = new GUIStyle(this.titleStyle) settingAtmoStyle = new GUIStyle(titleStyle)
{ {
margin = new RectOffset(), margin = new RectOffset(),
padding = new RectOffset(), padding = new RectOffset(),
alignment = TextAnchor.UpperLeft alignment = TextAnchor.UpperLeft
}; };
   
this.bodiesButtonStyle = new GUIStyle(HighLogic.Skin.button) bodiesButtonStyle = new GUIStyle(HighLogic.Skin.button)
{ {
margin = new RectOffset(0, 0, 2, 0), margin = new RectOffset(0, 0, 2, 0),
padding = new RectOffset(5, 5, 5, 5), padding = new RectOffset(5, 5, 5, 5),
normal = normal =
{ {
textColor = Color.white textColor = Color.white
}, },
active = active =
{ {
textColor = Color.white textColor = Color.white
}, },
fontSize = (int)(11 * GuiDisplaySize.Offset), fontSize = (int)(11 * GuiDisplaySize.Offset),
fontStyle = FontStyle.Bold, fontStyle = FontStyle.Bold,
alignment = TextAnchor.MiddleCenter, alignment = TextAnchor.MiddleCenter,
fixedHeight = 20.0f fixedHeight = 20.0f
}; };
   
this.bodiesButtonActiveStyle = new GUIStyle(this.bodiesButtonStyle) bodiesButtonActiveStyle = new GUIStyle(bodiesButtonStyle)
{ {
normal = this.bodiesButtonStyle.onNormal, normal = bodiesButtonStyle.onNormal,
hover = this.bodiesButtonStyle.onHover hover = bodiesButtonStyle.onHover
}; };
} }
   
/// <summary> /// <summary>
/// Loads the settings when this object is created. /// Loads the settings when this object is created.
/// </summary> /// </summary>
private void Load() private void Load()
{ {
try try
{ {
var handler = SettingHandler.Load("BuildAdvanced.xml"); SettingHandler handler = SettingHandler.Load("BuildAdvanced.xml");
handler.Get("visible", ref this.visible); handler.Get("visible", ref visible);
this.position.x = handler.Get("windowPositionX", this.position.x); position.x = handler.Get("windowPositionX", position.x);
this.position.y = handler.Get("windowPositionY", this.position.y); position.y = handler.Get("windowPositionY", position.y);
handler.Get("compactMode", ref this.compactMode); handler.Get("compactMode", ref compactMode);
handler.Get("compactCollapseRight", ref this.compactCollapseRight); handler.Get("compactCollapseRight", ref compactCollapseRight);
handler.Get("showAllStages", ref this.showAllStages); handler.Get("showAllStages", ref showAllStages);
handler.Get("showAtmosphericDetails", ref this.showAtmosphericDetails); handler.Get("showAtmosphericDetails", ref showAtmosphericDetails);
handler.Get("showSettings", ref this.showSettings); handler.Get("showSettings", ref showSettings);
CelestialBodies.SetSelectedBody(handler.Get("selectedBodyName", CelestialBodies.SelectedBody.Name)); CelestialBodies.SetSelectedBody(handler.Get("selectedBodyName", CelestialBodies.SelectedBody.Name));
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex, "BuildAdvanced->Load"); Logger.Exception(ex, "BuildAdvanced.Load()");
} }
} }
   
private void OnSizeChanged() private void OnSizeChanged()
{ {
this.InitialiseStyles(); InitialiseStyles();
this.hasChanged = true; hasChanged = true;
} }
   
/// <summary> /// <summary>
/// Draws the OnGUI window. /// Draws the OnGUI window.
/// </summary> /// </summary>
private void Window(int windowId) private void Window(int windowId)
{ {
try try
{ {
  compactModeRect = new Rect(position.width - 70.0f * GuiDisplaySize.Offset, 5.0f, 65.0f * GuiDisplaySize.Offset, 20.0f);
   
// Draw the compact mode toggle. // Draw the compact mode toggle.
if (GUI.Toggle(new Rect(this.position.width - 70.0f * GuiDisplaySize.Offset, 5.0f, 65.0f * GuiDisplaySize.Offset, 20.0f), this.compactMode, "COMPACT", this.buttonStyle) != this.compactMode) if (GUI.Toggle(compactModeRect, compactMode, "COMPACT", buttonStyle) != compactMode)
{ {
this.hasChanged = true; hasChanged = true;
this.compactCheck = 2; compactCheck = 2;
this.compactRight = this.position.xMax; compactRight = position.xMax;
this.compactMode = !this.compactMode; compactMode = !compactMode;
} }
   
// When not in compact mode draw the 'All Stages' and 'Atmospheric' toggles. // When not in compact mode draw the 'All Stages' and 'Atmospheric' toggles.
if (!this.compactMode) if (!compactMode)
{ {
if (GUI.Toggle(new Rect(this.position.width - 143.0f * GuiDisplaySize.Offset, 5.0f, 70.0f * GuiDisplaySize.Offset, 20.0f), this.showSettings, "SETTINGS", this.buttonStyle) != this.showSettings) if (GUI.Toggle(new Rect(position.width - 143.0f * GuiDisplaySize.Offset, 5.0f, 70.0f * GuiDisplaySize.Offset, 20.0f), showSettings, "SETTINGS", buttonStyle) != showSettings)
{ {
this.hasChanged = true; hasChanged = true;
this.showSettings = !this.showSettings; showSettings = !showSettings;
} }
   
if (GUI.Toggle(new Rect(this.position.width - 226.0f * GuiDisplaySize.Offset, 5.0f, 80.0f * GuiDisplaySize.Offset, 20.0f), this.showAllStages, "ALL STAGES", this.buttonStyle) != this.showAllStages) if (GUI.Toggle(new Rect(position.width - 226.0f * GuiDisplaySize.Offset, 5.0f, 80.0f * GuiDisplaySize.Offset, 20.0f), showAllStages, "ALL STAGES", buttonStyle) != showAllStages)
{ {
this.hasChanged = true; hasChanged = true;
this.showAllStages = !this.showAllStages; showAllStages = !showAllStages;
} }
   
if (GUI.Toggle(new Rect(this.position.width - 324.0f * GuiDisplaySize.Offset, 5.0f, 95.0f * GuiDisplaySize.Offset, 20.0f), this.showAtmosphericDetails, "ATMOSPHERIC", this.buttonStyle) != this.showAtmosphericDetails) if (GUI.Toggle(new Rect(position.width - 324.0f * GuiDisplaySize.Offset, 5.0f, 95.0f * GuiDisplaySize.Offset, 20.0f), showAtmosphericDetails, "ATMOSPHERIC", buttonStyle) != showAtmosphericDetails)
{ {
this.hasChanged = true; hasChanged = true;
this.showAtmosphericDetails = !this.showAtmosphericDetails; showAtmosphericDetails = !showAtmosphericDetails;
} }
   
this.bodiesListPosition = new Rect(this.position.width - 452.0f * GuiDisplaySize.Offset, 5.0f, 125.0f * GuiDisplaySize.Offset, 20.0f); bodiesListPosition = new Rect(position.width - 452.0f * GuiDisplaySize.Offset, 5.0f, 125.0f * GuiDisplaySize.Offset, 20.0f);
this.bodiesList.enabled = GUI.Toggle(this.bodiesListPosition, this.bodiesList.enabled, "BODY: " + CelestialBodies.SelectedBody.Name.ToUpper(), this.buttonStyle); bodiesList.enabled = GUI.Toggle(bodiesListPosition, bodiesList.enabled, "BODY: " + CelestialBodies.SelectedBody.Name.ToUpper(), buttonStyle);
this.bodiesList.SetPosition(this.bodiesListPosition.Translate(this.position)); bodiesList.SetPosition(bodiesListPosition.Translate(position));
  }
  else
  {
  if (GUI.Toggle(new Rect(position.width - 133.0f * GuiDisplaySize.Offset, 5.0f, 60.0f * GuiDisplaySize.Offset, 20.0f), showAtmosphericDetails, "ATMO", buttonStyle) != showAtmosphericDetails)
  {
  hasChanged = true;
  showAtmosphericDetails = !showAtmosphericDetails;
  }
} }
   
// Draw the main informational display box. // Draw the main informational display box.
if (!this.compactMode) if (!compactMode)
{ {
GUILayout.BeginHorizontal(this.areaStyle); GUILayout.BeginHorizontal(areaStyle);
this.DrawStageNumbers(); DrawStageNumbers();
this.DrawPartCount(); DrawPartCount();
this.DrawCost(); DrawCost();
this.DrawMass(); DrawMass();
this.DrawIsp(); DrawIsp();
this.DrawThrust(); DrawThrust();
this.DrawTwr(); DrawTorque();
this.DrawDeltaV(); DrawTwr();
this.DrawBurnTime(); DrawDeltaV();
  DrawBurnTime();
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
if (this.showAtmosphericDetails) if (showAtmosphericDetails && !compactMode)
{ {
GUILayout.BeginVertical(this.areaSettingStyle); GUILayout.BeginVertical(areaSettingStyle);
this.DrawAtmosphericDetails(); DrawAtmosphericDetails();
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
   
if (this.showSettings) if (showSettings)
{ {
GUILayout.BeginVertical(this.areaSettingStyle); GUILayout.BeginVertical(areaSettingStyle);
this.DrawSettings(); DrawSettings();
GUILayout.EndVertical(); GUILayout.EndVertical();
} }
} }
else // Draw only a few details when in compact mode. else // Draw only a few details when in compact mode.
{ {
GUILayout.BeginHorizontal(this.areaStyle); GUILayout.BeginHorizontal(areaStyle);
this.DrawStageNumbers(); DrawStageNumbers();
this.DrawTwr(); DrawTwr();
this.DrawDeltaV(); DrawDeltaV();
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
   
GUI.DragWindow(); GUI.DragWindow();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex, "BuildAdvanced.Window()");
} }
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using System;  
   
using KerbalEngineer.Helpers;  
using KerbalEngineer.Settings;  
   
using UnityEngine;  
   
#endregion #endregion
   
namespace KerbalEngineer.Editor namespace KerbalEngineer.Editor
{ {
  #region Using Directives
   
  using System;
  using Helpers;
  using Settings;
  using UnityEngine;
   
  #endregion
   
[KSPAddon(KSPAddon.Startup.EditorAny, false)] [KSPAddon(KSPAddon.Startup.EditorAny, false)]
public class BuildOverlay : MonoBehaviour public class BuildOverlay : MonoBehaviour
{ {
#region Fields #region Fields
   
private static BuildOverlayPartInfo buildOverlayPartInfo; private static BuildOverlayPartInfo buildOverlayPartInfo;
private static BuildOverlayResources buildOverlayResources; private static BuildOverlayResources buildOverlayResources;
private static BuildOverlayVessel buildOverlayVessel; private static BuildOverlayVessel buildOverlayVessel;
private static BuildOverlay instance; private static BuildOverlay instance;
   
private static float minimumWidth = 200.0f; private static float minimumWidth = 200.0f;
private static GUIStyle nameStyle; private static GUIStyle nameStyle;
private static float tabSpeed = 5.0f; private static float tabSpeed = 5.0f;
private static GUIStyle tabStyle; private static GUIStyle tabStyle;
private static GUIStyle titleStyle; private static GUIStyle titleStyle;
private static GUIStyle valueStyle; private static GUIStyle valueStyle;
private static GUIStyle windowStyle; private static GUIStyle windowStyle;
   
#endregion #endregion
   
#region Properties #region Properties
   
public static BuildOverlayPartInfo BuildOverlayPartInfo public static BuildOverlayPartInfo BuildOverlayPartInfo
{ {
get { return buildOverlayPartInfo; } get { return buildOverlayPartInfo; }
} }
   
public static BuildOverlayResources BuildOverlayResources public static BuildOverlayResources BuildOverlayResources
{ {
get { return buildOverlayResources; } get { return buildOverlayResources; }
} }
   
public static BuildOverlayVessel BuildOverlayVessel public static BuildOverlayVessel BuildOverlayVessel
{ {
get { return buildOverlayVessel; } get { return buildOverlayVessel; }
} }
   
public static float MinimumWidth public static float MinimumWidth
{ {
get { return minimumWidth; } get { return minimumWidth; }
set { minimumWidth = value; } set { minimumWidth = value; }
} }
   
public static GUIStyle NameStyle public static GUIStyle NameStyle
{ {
get get
{ {
return nameStyle ?? (nameStyle = new GUIStyle return nameStyle ?? (nameStyle = new GUIStyle
{ {
normal = normal =
{ {
textColor = Color.white textColor = Color.white
}, },
fontSize = 11, fontSize = 11,
fontStyle = FontStyle.Bold, fontStyle = FontStyle.Bold,
alignment = TextAnchor.UpperLeft, alignment = TextAnchor.UpperLeft,
stretchWidth = true stretchWidth = true
}); });
} }
} }
   
public static float TabSpeed public static float TabSpeed
{ {
get { return tabSpeed; } get { return tabSpeed; }
set { tabSpeed = value; } set { tabSpeed = value; }
} }
   
public static GUIStyle TabStyle public static GUIStyle TabStyle
{ {
get get
{ {
return tabStyle ?? (tabStyle = new GUIStyle return tabStyle ?? (tabStyle = new GUIStyle
{ {
normal = normal =
{ {
background = TextureHelper.CreateTextureFromColour(new Color(0.0f, 0.0f, 0.0f, 0.5f)), background = TextureHelper.CreateTextureFromColour(new Color(0.0f, 0.0f, 0.0f, 0.5f)),
textColor = Color.yellow textColor = Color.yellow
}, },
hover = hover =
{ {
background = TextureHelper.CreateTextureFromColour(new Color(0.0f, 0.0f, 0.0f, 0.75f)), background = TextureHelper.CreateTextureFromColour(new Color(0.0f, 0.0f, 0.0f, 0.75f)),
textColor = Color.yellow textColor = Color.yellow
}, },
onNormal = onNormal =
{ {
background = TextureHelper.CreateTextureFromColour(new Color(0.0f, 0.0f, 0.0f, 0.5f)), background = TextureHelper.CreateTextureFromColour(new Color(0.0f, 0.0f, 0.0f, 0.5f)),
textColor = Color.yellow textColor = Color.yellow
}, },
onHover = onHover =
{ {
background = TextureHelper.CreateTextureFromColour(new Color(0.0f, 0.0f, 0.0f, 0.75f)), background = TextureHelper.CreateTextureFromColour(new Color(0.0f, 0.0f, 0.0f, 0.75f)),
textColor = Color.yellow textColor = Color.yellow
}, },
padding = new RectOffset(20, 20, 0, 0), padding = new RectOffset(20, 20, 0, 0),
fontSize = 11, fontSize = 11,
fontStyle = FontStyle.Bold, fontStyle = FontStyle.Bold,
alignment = TextAnchor.MiddleCenter, alignment = TextAnchor.MiddleCenter,
fixedHeight = 15.0f, fixedHeight = 15.0f,
stretchWidth = true stretchWidth = true
}); });
} }
} }
   
public static GUIStyle TitleStyle public static GUIStyle TitleStyle
{ {
get get
{ {
return titleStyle ?? (titleStyle = new GUIStyle return titleStyle ?? (titleStyle = new GUIStyle
{ {
normal = normal =
{ {
textColor = Color.yellow textColor = Color.yellow
}, },
fontSize = 11, fontSize = 11,
fontStyle = FontStyle.Bold, fontStyle = FontStyle.Bold,
stretchWidth = true stretchWidth = true
}); });
} }
} }
   
public static GUIStyle ValueStyle public static GUIStyle ValueStyle
{ {
get get
{ {
return valueStyle ?? (valueStyle = new GUIStyle return valueStyle ?? (valueStyle = new GUIStyle
{ {
normal = normal =
{ {
textColor = Color.white textColor = Color.white
}, },
fontSize = 11, fontSize = 11,
fontStyle = FontStyle.Normal, fontStyle = FontStyle.Normal,
alignment = TextAnchor.UpperRight, alignment = TextAnchor.UpperRight,
stretchWidth = true stretchWidth = true
}); });
} }
} }
   
public static bool Visible public static bool Visible
{ {
get { return BuildOverlayPartInfo.Visible && BuildOverlayVessel.Visible && BuildOverlayResources.Visible; } get { return BuildOverlayPartInfo.Visible && BuildOverlayVessel.Visible && BuildOverlayResources.Visible; }
set { BuildOverlayPartInfo.Visible = BuildOverlayVessel.Visible = BuildOverlayResources.Visible = value; } set { BuildOverlayPartInfo.Visible = BuildOverlayVessel.Visible = BuildOverlayResources.Visible = value; }
} }
   
public static GUIStyle WindowStyle public static GUIStyle WindowStyle
{ {
get get
{ {
return windowStyle ?? (windowStyle = new GUIStyle return windowStyle ?? (windowStyle = new GUIStyle
{ {
normal = normal =
{ {
background = TextureHelper.CreateTextureFromColour(new Color(0.0f, 0.0f, 0.0f, 0.5f)) background = TextureHelper.CreateTextureFromColour(new Color(0.0f, 0.0f, 0.0f, 0.5f))
}, },
padding = new RectOffset(5, 5, 3, 3), padding = new RectOffset(5, 5, 3, 3),
}); });
} }
} }
   
#endregion #endregion
   
#region Methods: public #region Methods
   
public static void Load() public static void Load()
{ {
var handler = SettingHandler.Load("BuildOverlay.xml"); var handler = SettingHandler.Load("BuildOverlay.xml");
handler.GetSet("visible", Visible); Visible = handler.GetSet("visible", Visible);
BuildOverlayPartInfo.NamesOnly = handler.GetSet("namesOnly", BuildOverlayPartInfo.NamesOnly); BuildOverlayPartInfo.NamesOnly = handler.GetSet("namesOnly", BuildOverlayPartInfo.NamesOnly);
BuildOverlayPartInfo.ClickToOpen = handler.GetSet("clickToOpen", BuildOverlayPartInfo.ClickToOpen); BuildOverlayPartInfo.ClickToOpen = handler.GetSet("clickToOpen", BuildOverlayPartInfo.ClickToOpen);
buildOverlayVessel.Open = handler.GetSet("vesselOpen", buildOverlayVessel.Open); buildOverlayVessel.Open = handler.GetSet("vesselOpen", buildOverlayVessel.Open);
buildOverlayResources.Open = handler.GetSet("resourcesOpen", buildOverlayResources.Open); buildOverlayResources.Open = handler.GetSet("resourcesOpen", buildOverlayResources.Open);
  buildOverlayVessel.WindowX = handler.GetSet("vesselWindowX", buildOverlayVessel.WindowX);
handler.Save("BuildOverlay.xml"); handler.Save("BuildOverlay.xml");
} }
   
public static void Save() public static void Save()
{ {
var handler = SettingHandler.Load("BuildOverlay.xml"); var handler = SettingHandler.Load("BuildOverlay.xml");
handler.Set("visible", Visible); handler.Set("visible", Visible);
handler.Set("namesOnly", BuildOverlayPartInfo.NamesOnly); handler.Set("namesOnly", BuildOverlayPartInfo.NamesOnly);
handler.Set("clickToOpen", BuildOverlayPartInfo.ClickToOpen); handler.Set("clickToOpen", BuildOverlayPartInfo.ClickToOpen);
handler.Set("vesselOpen", buildOverlayVessel.Open); handler.Set("vesselOpen", buildOverlayVessel.Open);
handler.Set("resourcesOpen", buildOverlayResources.Open); handler.Set("resourcesOpen", buildOverlayResources.Open);
  handler.Set("vesselWindowX", buildOverlayVessel.WindowX);
handler.Save("BuildOverlay.xml"); handler.Save("BuildOverlay.xml");
} }
   
#endregion  
   
#region Methods: protected  
   
protected void Awake() protected void Awake()
{ {
try try
{ {
if (instance != null) if (instance != null)
{ {
Destroy(this); Destroy(this);
return; return;
} }
instance = this; instance = this;
buildOverlayPartInfo = this.gameObject.AddComponent<BuildOverlayPartInfo>(); buildOverlayPartInfo = this.gameObject.AddComponent<BuildOverlayPartInfo>();
buildOverlayVessel = this.gameObject.AddComponent<BuildOverlayVessel>(); buildOverlayVessel = this.gameObject.AddComponent<BuildOverlayVessel>();
buildOverlayResources = this.gameObject.AddComponent<BuildOverlayResources>(); buildOverlayResources = this.gameObject.AddComponent<BuildOverlayResources>();
Load(); Load();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
protected void OnDestroy() protected void OnDestroy()
{ {
try try
{ {
Save(); Save();
if (buildOverlayPartInfo != null) if (buildOverlayPartInfo != null)
{ {
Destroy(buildOverlayPartInfo); Destroy(buildOverlayPartInfo);
} }
if (buildOverlayVessel != null) if (buildOverlayVessel != null)
{ {
Destroy(buildOverlayVessel); Destroy(buildOverlayVessel);
} }
if (buildOverlayResources != null) if (buildOverlayResources != null)
{ {
Destroy(buildOverlayResources); Destroy(buildOverlayResources);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives  
   
using System;  
using System.Collections.Generic;  
using System.Linq;  
   
using KerbalEngineer.Extensions;  
using KerbalEngineer.Helpers;  
   
using UnityEngine;  
   
#endregion  
   
namespace KerbalEngineer.Editor namespace KerbalEngineer.Editor
{ {
  using System;
  using System.Collections.Generic;
  using Extensions;
  using Helpers;
  using UnityEngine;
   
public class BuildOverlayPartInfo : MonoBehaviour public class BuildOverlayPartInfo : MonoBehaviour
{ {
#region Fields  
   
private static bool clickToOpen = true; private static bool clickToOpen = true;
  private static ModuleGenerator.GeneratorResource generatorResource;
  private static ModuleAlternator moduleAlternator;
  private static ModuleDataTransmitter moduleDataTransmitter;
  private static ModuleDeployableSolarPanel moduleDeployableSolarPanel;
  private static ModuleGenerator moduleGenerator;
  private static ModuleGimbal moduleGimbal;
  private static ModuleParachute moduleParachute;
  private static ModuleRCS moduleRcs;
  private static ModuleReactionWheel moduleReactionWheel;
  private static ModuleResource moduleResource;
  private static ModuleScienceExperiment moduleScienceExperiment;
private static bool namesOnly; private static bool namesOnly;
  private static Part part;
  private static PartInfoItem partInfoItem;
  private static PartResource partResource;
  private static Propellant propellant;
  private static PartExtensions.ProtoModuleDecoupler protoModuleDecoupler;
  private static PartExtensions.ProtoModuleEngine protoModuleEngine;
private static bool visible = true; private static bool visible = true;
   
private readonly List<PartInfoItem> infoItems = new List<PartInfoItem>(); private readonly List<PartInfoItem> infoItems = new List<PartInfoItem>();
   
private Rect position; private Rect position;
private Part selectedPart; private Part selectedPart;
private bool showInfo; private bool showInfo;
private bool skipFrame; private bool skipFrame;
   
#endregion  
   
#region Properties  
   
public static bool ClickToOpen public static bool ClickToOpen
{ {
get { return clickToOpen; } get
set { clickToOpen = value; } {
  return clickToOpen;
  }
  set
  {
  clickToOpen = value;
  }
} }
   
public static bool Hidden { get; set; } public static bool Hidden { get; set; }
   
public static bool NamesOnly public static bool NamesOnly
{ {
get { return namesOnly; } get
set { namesOnly = value; } {
  return namesOnly;
  }
  set
  {
  namesOnly = value;
  }
} }
   
public static bool Visible public static bool Visible
{ {
get { return visible; } get
set { visible = value; } {
} return visible;
  }
#endregion set
  {
#region Methods: protected visible = value;
  }
  }
   
protected void OnGUI() protected void OnGUI()
{ {
try try
{ {
if (!Visible || Hidden || this.selectedPart == null) if (!Visible || Hidden || selectedPart == null)
{ {
return; return;
} }
   
this.position = GUILayout.Window(this.GetInstanceID(), this.position, this.Window, String.Empty, BuildOverlay.WindowStyle); position = GUILayout.Window(GetInstanceID(), position, Window, String.Empty, BuildOverlay.WindowStyle);
} }
catch (Exception ex) catch (Exception ex)
   
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
protected void Update() protected void Update()
{ {
try try
{ {
if (!Visible || Hidden || EditorLogic.startPod == null || EditorLogic.fetch.editorScreen != EditorLogic.EditorScreen.Parts) if (!Visible || Hidden || EditorLogic.RootPart == null || EditorLogic.fetch.editorScreen != EditorScreen.Parts)
{ {
return; return;
} }
   
this.position.x = Mathf.Clamp(Input.mousePosition.x + 16.0f, 0.0f, Screen.width - this.position.width); position.x = Mathf.Clamp(Input.mousePosition.x + 16.0f, 0.0f, Screen.width - position.width);
this.position.y = Mathf.Clamp(Screen.height - Input.mousePosition.y, 0.0f, Screen.height - this.position.height); position.y = Mathf.Clamp(Screen.height - Input.mousePosition.y, 0.0f, Screen.height - position.height);
if (this.position.x < Input.mousePosition.x + 20.0f) if (position.x < Input.mousePosition.x + 20.0f)
{ {
this.position.y = Mathf.Clamp(this.position.y + 20.0f, 0.0f, Screen.height - this.position.height); position.y = Mathf.Clamp(position.y + 20.0f, 0.0f, Screen.height - position.height);
} }
if (this.position.x < Input.mousePosition.x + 16.0f && this.position.y < Screen.height - Input.mousePosition.y) if (position.x < Input.mousePosition.x + 16.0f && position.y < Screen.height - Input.mousePosition.y)
{ {
this.position.x = Input.mousePosition.x - 3 - this.position.width; position.x = Input.mousePosition.x - 3 - position.width;
} }
   
this.infoItems.Clear(); part = EditorLogic.fetch.ship.parts.Find(p => p.stackIcon.highlightIcon) ?? EditorLogic.SelectedPart;
var part = EditorLogic.fetch.ship.parts.Find(p => p.stackIcon.highlightIcon) ?? EditorLogic.SelectedPart;  
if (part != null) if (part != null)
{ {
if (!part.Equals(this.selectedPart)) if (!part.Equals(selectedPart))
{ {
this.selectedPart = part; selectedPart = part;
this.ResetInfo(); ResetInfo();
} }
if (NamesOnly || this.skipFrame) if (NamesOnly || skipFrame)
{ {
this.skipFrame = false; skipFrame = false;
return; return;
} }
   
this.SetCostInfo(); if (!showInfo && Input.GetMouseButtonDown(2))
this.SetMassItems(); {
this.SetResourceItems(); showInfo = true;
this.SetEngineInfo(); }
this.SetAlternatorInfo(); else if (ClickToOpen && showInfo && Input.GetMouseButtonDown(2))
this.SetGimbalInfo(); {
this.SetRcsInfo(); ResetInfo();
this.SetParachuteInfo(); }
this.SetSasInfo();  
this.SetReactionWheelInfo(); if (showInfo)
this.SetSolarPanelInfo(); {
this.SetGeneratorInfo(); PartInfoItem.Release(infoItems);
this.SetDecouplerInfo(); infoItems.Clear();
this.SetTransmitterInfo(); SetCostInfo();
this.SetScienceExperimentInfo(); SetMassItems();
this.SetScienceContainerInfo(); SetResourceItems();
this.SetSingleActivationInfo(); SetEngineInfo();
  SetAlternatorInfo();
if (!this.showInfo && Input.GetMouseButtonDown(2)) SetGimbalInfo();
{ SetRcsInfo();
this.showInfo = true; SetParachuteInfo();
} SetSasInfo();
else if (ClickToOpen && this.showInfo && Input.GetMouseButtonDown(2)) SetReactionWheelInfo();
{ SetSolarPanelInfo();
this.ResetInfo(); SetGeneratorInfo();
  SetDecouplerInfo();
  SetTransmitterInfo();
  SetScienceExperimentInfo();
  SetScienceContainerInfo();
  SetSingleActivationInfo();
} }
} }
else else
{ {
this.selectedPart = null; selectedPart = null;
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion  
   
#region Methods: private  
   
private void ResetInfo() private void ResetInfo()
{ {
this.showInfo = !clickToOpen; showInfo = !clickToOpen;
this.skipFrame = true; skipFrame = true;
this.position.width = namesOnly || clickToOpen ? 0.0f : 200.0f; position.width = namesOnly || clickToOpen ? 0.0f : 200.0f;
this.position.height = 0.0f; position.height = 0.0f;
} }
   
private void SetAlternatorInfo() private void SetAlternatorInfo()
{ {
if (!this.selectedPart.HasModule<ModuleAlternator>()) moduleAlternator = selectedPart.GetModule<ModuleAlternator>();
{ if (moduleAlternator != null)
return; {
} infoItems.Add(PartInfoItem.Create("Alternator"));
  for (int i = 0; i < moduleAlternator.outputResources.Count; ++i)
var alternator = this.selectedPart.GetModule<ModuleAlternator>(); {
this.infoItems.Add(new PartInfoItem("Alternator")); moduleResource = moduleAlternator.outputResources[i];
foreach (var resource in alternator.outputResources) infoItems.Add(PartInfoItem.Create("\t" + moduleResource.name, moduleResource.rate.ToRate()));
{ }
this.infoItems.Add(new PartInfoItem("\t" + resource.name, resource.rate.ToRate()));  
} }
} }
   
private void SetCostInfo() private void SetCostInfo()
{ {
this.infoItems.Add(new PartInfoItem("Cost", Units.Concat(this.selectedPart.GetCostDry(), this.selectedPart.GetCostWet()))); infoItems.Add(PartInfoItem.Create("Cost", Units.ConcatF(selectedPart.GetCostDry(), selectedPart.GetCostWet())));
} }
   
private void SetDecouplerInfo() private void SetDecouplerInfo()
{ {
if (!this.selectedPart.IsDecoupler()) protoModuleDecoupler = selectedPart.GetProtoModuleDecoupler();
{ if (protoModuleDecoupler != null)
return; {
} infoItems.Add(PartInfoItem.Create("Ejection Force", protoModuleDecoupler.EjectionForce.ToForce()));
  if (protoModuleDecoupler.IsOmniDecoupler)
var decoupler = this.selectedPart.GetProtoModuleDecoupler(); {
this.infoItems.Add(new PartInfoItem("Ejection Force", decoupler.EjectionForce.ToForce())); infoItems.Add(PartInfoItem.Create("Omni-directional"));
if (decoupler.IsOmniDecoupler) }
{  
this.infoItems.Add(new PartInfoItem("Omni-directional"));  
} }
} }
   
private void SetEngineInfo() private void SetEngineInfo()
{ {
if (!this.selectedPart.IsEngine()) protoModuleEngine = selectedPart.GetProtoModuleEngine();
{ if (protoModuleEngine != null)
return; {
} infoItems.Add(PartInfoItem.Create("Thrust", Units.ToForce(protoModuleEngine.MinimumThrust, protoModuleEngine.MaximumThrust)));
  infoItems.Add(PartInfoItem.Create("Isp", Units.ConcatF(protoModuleEngine.GetSpecificImpulse(1.0f), protoModuleEngine.GetSpecificImpulse(0.0f)) + "s"));
var engine = this.selectedPart.GetProtoModuleEngine(); if (protoModuleEngine.Propellants.Count > 0)
this.infoItems.Add(new PartInfoItem("Thrust", Units.ToForce(engine.MinimumThrust, engine.MaximumThrust))); {
this.infoItems.Add(new PartInfoItem("Isp", Units.Concat(engine.GetSpecificImpulse(1.0f), engine.GetSpecificImpulse(0.0f)) + "s")); infoItems.Add(PartInfoItem.Create("Propellants"));
if (engine.Propellants.Count > 0)  
{ float totalRatio = 0.0f;
this.infoItems.Add(new PartInfoItem("Propellants")); for (int i = 0; i < protoModuleEngine.Propellants.Count; ++i)
var totalRatio = engine.Propellants.Sum(p => p.ratio); {
foreach (var propellant in engine.Propellants) totalRatio = totalRatio + protoModuleEngine.Propellants[i].ratio;
{ }
this.infoItems.Add(new PartInfoItem("\t" + propellant.name, (propellant.ratio / totalRatio).ToPercent()));  
  for (int i = 0; i < protoModuleEngine.Propellants.Count; ++i)
  {
  propellant = protoModuleEngine.Propellants[i];
  infoItems.Add(PartInfoItem.Create("\t" + propellant.name, (propellant.ratio / totalRatio).ToPercent()));
  }
} }
} }
} }
   
private void SetGeneratorInfo() private void SetGeneratorInfo()
{ {
if (!this.selectedPart.HasModule<ModuleGenerator>()) moduleGenerator = selectedPart.GetModule<ModuleGenerator>();
{ if (moduleGenerator != null)
return; {
} if (moduleGenerator.inputList.Count > 0)
  {
var generator = this.selectedPart.GetModule<ModuleGenerator>(); infoItems.Add(PartInfoItem.Create("Generator Input"));
if (generator.inputList.Count > 0) for (int i = 0; i < moduleGenerator.inputList.Count; ++i)
{ {
this.infoItems.Add(new PartInfoItem("Generator Input")); generatorResource = moduleGenerator.inputList[i];
foreach (var resource in generator.inputList) infoItems.Add(PartInfoItem.Create("\t" + generatorResource.name, generatorResource.rate.ToRate()));
{ }
this.infoItems.Add(new PartInfoItem("\t" + resource.name, resource.rate.ToRate())); }
} if (moduleGenerator.outputList.Count > 0)
} {
if (generator.outputList.Count > 0) infoItems.Add(PartInfoItem.Create("Generator Output"));
{ for (int i = 0; i < moduleGenerator.outputList.Count; ++i)
this.infoItems.Add(new PartInfoItem("Generator Output")); {
foreach (var resource in generator.outputList) generatorResource = moduleGenerator.outputList[i];
{ infoItems.Add(PartInfoItem.Create("\t" + generatorResource.name, generatorResource.rate.ToRate()));
this.infoItems.Add(new PartInfoItem("\t" + resource.name, resource.rate.ToRate())); }
} }
} if (moduleGenerator.isAlwaysActive)
if (generator.isAlwaysActive) {
{ infoItems.Add(PartInfoItem.Create("Generator is Always Active"));
this.infoItems.Add(new PartInfoItem("Generator is Always Active")); }
} }
} }
   
private void SetGimbalInfo() private void SetGimbalInfo()
{ {
if (!this.selectedPart.HasModule<ModuleGimbal>()) moduleGimbal = selectedPart.GetModule<ModuleGimbal>();
{ if (moduleGimbal != null)
return; {
} infoItems.Add(PartInfoItem.Create("Thrust Vectoring", moduleGimbal.gimbalRange.ToString("F2")));
  }
var gimbal = this.selectedPart.GetModule<ModuleGimbal>();  
this.infoItems.Add(new PartInfoItem("Thrust Vectoring", gimbal.gimbalRange.ToString("F2")));  
} }
   
private void SetMassItems() private void SetMassItems()
{ {
if (this.selectedPart.physicalSignificance == Part.PhysicalSignificance.FULL) if (selectedPart.physicalSignificance == Part.PhysicalSignificance.FULL)
{ {
this.infoItems.Add(new PartInfoItem("Mass", Units.ToMass(this.selectedPart.GetDryMass(), this.selectedPart.GetWetMass()))); infoItems.Add(PartInfoItem.Create("Mass", Units.ToMass(selectedPart.GetDryMass(), selectedPart.GetWetMass())));
} }
} }
   
private void SetParachuteInfo() private void SetParachuteInfo()
{ {
if (!this.selectedPart.HasModule<ModuleParachute>()) moduleParachute = selectedPart.GetModule<ModuleParachute>();
{ if (moduleParachute != null)
return; {
} infoItems.Add(PartInfoItem.Create("Deployed Drag", Units.ConcatF(moduleParachute.semiDeployedDrag, moduleParachute.fullyDeployedDrag)));
  infoItems.Add(PartInfoItem.Create("Deployment Altitude", moduleParachute.deployAltitude.ToDistance()));
var parachute = this.selectedPart.GetModule<ModuleParachute>(); infoItems.Add(PartInfoItem.Create("Deployment Pressure", moduleParachute.minAirPressureToOpen.ToString("F2")));
this.infoItems.Add(new PartInfoItem("Deployed Drag", Units.Concat(parachute.semiDeployedDrag, parachute.fullyDeployedDrag))); }
this.infoItems.Add(new PartInfoItem("Deployment Altitude", parachute.deployAltitude.ToDistance()));  
this.infoItems.Add(new PartInfoItem("Deployment Pressure", parachute.minAirPressureToOpen.ToString("F2")));  
} }
   
private void SetRcsInfo() private void SetRcsInfo()
{ {
if (!this.selectedPart.HasModule<ModuleRCS>()) moduleRcs = selectedPart.GetModule<ModuleRCS>();
{ if (moduleRcs != null)
return; {
} infoItems.Add(PartInfoItem.Create("Thruster Power", moduleRcs.thrusterPower.ToForce()));
  infoItems.Add(PartInfoItem.Create("Specific Impulse", Units.ConcatF(moduleRcs.atmosphereCurve.Evaluate(1.0f), moduleRcs.atmosphereCurve.Evaluate(0.0f)) + "s"));
var rcs = this.selectedPart.GetModule<ModuleRCS>(); }
this.infoItems.Add(new PartInfoItem("Thruster Power", rcs.thrusterPower.ToForce()));  
this.infoItems.Add(new PartInfoItem("Specific Impulse", Units.Concat(rcs.atmosphereCurve.Evaluate(1.0f), rcs.atmosphereCurve.Evaluate(0.0f)) + "s"));  
} }
   
private void SetReactionWheelInfo() private void SetReactionWheelInfo()
{ {
if (!this.selectedPart.HasModule<ModuleReactionWheel>()) moduleReactionWheel = selectedPart.GetModule<ModuleReactionWheel>();
{ if (moduleReactionWheel != null)
return; {
} infoItems.Add(PartInfoItem.Create("Reaction Wheel Torque"));
  infoItems.Add(PartInfoItem.Create("\tPitch", moduleReactionWheel.PitchTorque.ToTorque()));
var reactionWheel = this.selectedPart.GetModule<ModuleReactionWheel>(); infoItems.Add(PartInfoItem.Create("\tRoll", moduleReactionWheel.RollTorque.ToTorque()));
this.infoItems.Add(new PartInfoItem("Reaction Wheel Torque")); infoItems.Add(PartInfoItem.Create("\tYaw", moduleReactionWheel.YawTorque.ToTorque()));
this.infoItems.Add(new PartInfoItem("\tPitch", reactionWheel.PitchTorque.ToForce())); for (int i = 0; i < moduleReactionWheel.inputResources.Count; ++i)
this.infoItems.Add(new PartInfoItem("\tRoll", reactionWheel.RollTorque.ToForce())); {
this.infoItems.Add(new PartInfoItem("\tYaw", reactionWheel.YawTorque.ToForce())); moduleResource = moduleReactionWheel.inputResources[i];
foreach (var resource in reactionWheel.inputResources) infoItems.Add(PartInfoItem.Create("\t" + moduleResource.name, moduleResource.rate.ToRate()));
{ }
this.infoItems.Add(new PartInfoItem("\t" + resource.name, resource.rate.ToRate()));  
} }
} }
   
private void SetResourceItems() private void SetResourceItems()
{ {
if (this.selectedPart.Resources.list.Any(r => !r.hideFlow)) bool visibleResources = false;
{ for (int i = 0; i < selectedPart.Resources.list.Count; ++i)
this.infoItems.Add(new PartInfoItem("Resources")); {
foreach (var resource in this.selectedPart.Resources.list.Where(r => !r.hideFlow)) if (selectedPart.Resources.list[i].hideFlow == false)
{ {
this.infoItems.Add(resource.GetDensity() > 0 visibleResources = true;
? new PartInfoItem("\t" + resource.info.name, "(" + resource.GetMass().ToMass() + ") " + resource.amount.ToString("F1")) break;
: new PartInfoItem("\t" + resource.info.name, resource.amount.ToString("F1"))); }
  }
  if (visibleResources)
  {
  infoItems.Add(PartInfoItem.Create("Resources"));
  for (int i = 0; i < selectedPart.Resources.list.Count; ++i)
  {
  partResource = selectedPart.Resources.list[i];
   
  if (partResource.hideFlow == false)
  {
  infoItems.Add(partResource.GetDensity() > 0
  ? PartInfoItem.Create("\t" + partResource.info.name, "(" + partResource.GetMass().ToMass() + ") " + partResource.amount.ToString("F1"))
  : PartInfoItem.Create("\t" + partResource.info.name, partResource.amount.ToString("F1")));
  }
} }
} }
} }
   
private void SetSasInfo() private void SetSasInfo()
{ {
if (this.selectedPart.HasModule<ModuleSAS>()) if (selectedPart.HasModule<ModuleSAS>())
{ {
this.infoItems.Add(new PartInfoItem("SAS Equiped")); infoItems.Add(PartInfoItem.Create("SAS Equiped"));
} }
} }
   
private void SetScienceContainerInfo() private void SetScienceContainerInfo()
{ {
if (this.selectedPart.HasModule<ModuleScienceContainer>()) if (selectedPart.HasModule<ModuleScienceContainer>())
{ {
this.infoItems.Add(new PartInfoItem("Science Container")); infoItems.Add(PartInfoItem.Create("Science Container"));
} }
} }
   
private void SetScienceExperimentInfo() private void SetScienceExperimentInfo()
{ {
if (!this.selectedPart.HasModule<ModuleScienceExperiment>()) moduleScienceExperiment = selectedPart.GetModule<ModuleScienceExperiment>();
{ if (moduleScienceExperiment != null)
return; {
} infoItems.Add(PartInfoItem.Create("Science Experiment", moduleScienceExperiment.experimentActionName));
  infoItems.Add(PartInfoItem.Create("\tTransmit Efficiency", moduleScienceExperiment.xmitDataScalar.ToPercent()));
var experiment = this.selectedPart.GetModule<ModuleScienceExperiment>(); if (moduleScienceExperiment.rerunnable == false)
this.infoItems.Add(new PartInfoItem("Science Experiment", experiment.experimentActionName)); {
this.infoItems.Add(new PartInfoItem("\tTransmit Efficiency", experiment.xmitDataScalar.ToPercent())); infoItems.Add(PartInfoItem.Create("\tSingle Usage"));
if (!experiment.rerunnable) }
{  
this.infoItems.Add(new PartInfoItem("\tSingle Usage"));  
} }
} }
   
private void SetSingleActivationInfo() private void SetSingleActivationInfo()
{ {
if (this.selectedPart.HasModule<ModuleAnimateGeneric>(m => m.isOneShot)) if (selectedPart.HasModule<ModuleAnimateGeneric>(m => m.isOneShot))
{ {
this.infoItems.Add(new PartInfoItem("Single Activation")); infoItems.Add(PartInfoItem.Create("Single Activation"));
} }
} }
   
private void SetSolarPanelInfo() private void SetSolarPanelInfo()
{ {
if (!this.selectedPart.HasModule<ModuleDeployableSolarPanel>()) moduleDeployableSolarPanel = selectedPart.GetModule<ModuleDeployableSolarPanel>();
{ if (moduleDeployableSolarPanel != null)
return; {
} infoItems.Add(PartInfoItem.Create("Charge Rate", moduleDeployableSolarPanel.chargeRate.ToRate()));
  if (moduleDeployableSolarPanel.isBreakable)
var solarPanel = this.selectedPart.GetModule<ModuleDeployableSolarPanel>(); {
this.infoItems.Add(new PartInfoItem("Charge Rate", solarPanel.chargeRate.ToRate())); infoItems.Add(PartInfoItem.Create("Breakable"));
if (solarPanel.isBreakable) }
{ if (moduleDeployableSolarPanel.sunTracking)
this.infoItems.Add(new PartInfoItem("Breakable")); {
} infoItems.Add(PartInfoItem.Create("Sun Tracking"));
if (solarPanel.sunTracking) }
{  
this.infoItems.Add(new PartInfoItem("Sun Tracking"));  
} }
} }
   
private void SetTransmitterInfo() private void SetTransmitterInfo()
{ {
if (!this.selectedPart.HasModule<ModuleDataTransmitter>()) moduleDataTransmitter = selectedPart.GetModule<ModuleDataTransmitter>();
{ if (moduleDataTransmitter != null)
return; {
} infoItems.Add(PartInfoItem.Create("Packet Size", moduleDataTransmitter.packetSize.ToString("F2") + " Mits"));
  infoItems.Add(PartInfoItem.Create("Bandwidth", (moduleDataTransmitter.packetInterval * moduleDataTransmitter.packetSize).ToString("F2") + "Mits/sec"));
var transmitter = this.selectedPart.GetModule<ModuleDataTransmitter>(); infoItems.Add(PartInfoItem.Create(moduleDataTransmitter.requiredResource, moduleDataTransmitter.packetResourceCost.ToString("F2") + "/Packet"));
this.infoItems.Add(new PartInfoItem("Packet Size", transmitter.packetSize.ToString("F2") + " Mits")); }
this.infoItems.Add(new PartInfoItem("Bandwidth", (transmitter.packetInterval * transmitter.packetSize).ToString("F2") + "Mits/sec"));  
this.infoItems.Add(new PartInfoItem(transmitter.requiredResource, transmitter.packetResourceCost.ToString("F2") + "/Packet"));  
} }
   
private void Window(int windowId) private void Window(int windowId)
{ {
try try
{ {
GUILayout.Label(this.selectedPart.partInfo.title, BuildOverlay.TitleStyle); GUILayout.Label(selectedPart.partInfo.title, BuildOverlay.TitleStyle);
if (this.showInfo) if (showInfo)
{ {
foreach (var item in this.infoItems) for (int i = 0; i < infoItems.Count; ++i)
{ {
  partInfoItem = infoItems[i];
GUILayout.Space(2.0f); GUILayout.Space(2.0f);
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
if (item.Value != null) if (partInfoItem.Value != null)
{ {
GUILayout.Label(item.Name + ":", BuildOverlay.NameStyle); GUILayout.Label(partInfoItem.Name + ":", BuildOverlay.NameStyle);
GUILayout.Space(25.0f); GUILayout.Space(25.0f);
GUILayout.Label(item.Value, BuildOverlay.ValueStyle); GUILayout.Label(partInfoItem.Value, BuildOverlay.ValueStyle);
} }
else else
{ {
GUILayout.Label(item.Name, BuildOverlay.NameStyle); GUILayout.Label(partInfoItem.Name, BuildOverlay.NameStyle);
} }
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
} }
else if (this.infoItems.Count > 0) else if (clickToOpen && namesOnly == false)
{ {
GUILayout.Space(2.0f); GUILayout.Space(2.0f);
GUILayout.Label("Click middle mouse to show more info...", BuildOverlay.NameStyle); GUILayout.Label("Click middle mouse to show more info...", BuildOverlay.NameStyle);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion  
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using System;  
using System.Collections.Generic;  
using System.Linq;  
   
using KerbalEngineer.Extensions;  
   
using UnityEngine;  
   
#endregion #endregion
   
namespace KerbalEngineer.Editor namespace KerbalEngineer.Editor
{ {
  using System;
  using System.Collections.Generic;
  using Extensions;
  using UnityEngine;
   
public class BuildOverlayResources : MonoBehaviour public class BuildOverlayResources : MonoBehaviour
{ {
#region Fields #region Fields
   
private static bool visible = true; private static bool visible = true;
   
private readonly Dictionary<int, ResourceInfoItem> resources = new Dictionary<int, ResourceInfoItem>(); private readonly Dictionary<int, ResourceInfoItem> resources = new Dictionary<int, ResourceInfoItem>();
   
private bool open = true; private bool open = true;
private float openPercent; private float openPercent;
private GUIContent tabContent; private GUIContent tabContent;
private Rect tabPosition; private Rect tabPosition;
private Vector2 tabSize; private Vector2 tabSize;
private Rect windowPosition = new Rect(0.0f, 0.0f, BuildOverlay.MinimumWidth, 0.0f); private Rect windowPosition = new Rect(0.0f, 0.0f, BuildOverlay.MinimumWidth, 0.0f);
   
#endregion #endregion
   
#region Properties #region Properties
   
public static bool Visible public static bool Visible
{ {
get { return visible; } get
set { visible = value; } {
  return visible;
  }
  set
  {
  visible = value;
  }
} }
   
public bool Open public bool Open
{ {
get { return this.open; } get
set { this.open = value; } {
} return open;
  }
  set
  {
  open = value;
  }
  }
#endregion #endregion
   
#region Methods: protected #region Methods: protected
   
protected void OnGUI() protected void OnGUI()
{ {
try try
{ {
if (!BuildOverlay.Visible || this.resources.Count == 0 || EditorLogic.fetch.editorScreen != EditorLogic.EditorScreen.Parts) if (!Visible || resources.Count == 0 || EditorLogic.fetch.editorScreen != EditorScreen.Parts)
{ {
return; return;
} }
   
this.open = GUI.Toggle(this.tabPosition, this.open, this.tabContent, BuildOverlay.TabStyle); open = GUI.Toggle(tabPosition, open, tabContent, BuildOverlay.TabStyle);
if (this.openPercent > 0.0) if (openPercent > 0.0)
{ {
this.windowPosition = GUILayout.Window(this.GetInstanceID(), this.windowPosition, this.Window, String.Empty, BuildOverlay.WindowStyle); windowPosition = GUILayout.Window(GetInstanceID(), windowPosition, Window, String.Empty, BuildOverlay.WindowStyle);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
protected void Start() protected void Start()
{ {
try try
{ {
this.tabContent = new GUIContent("RESOURCES"); tabContent = new GUIContent("RESOURCES");
this.tabSize = BuildOverlay.TabStyle.CalcSize(this.tabContent); tabSize = BuildOverlay.TabStyle.CalcSize(tabContent);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
protected void Update() protected void Update()
{ {
try try
{ {
if (!BuildOverlay.Visible) if (!Visible)
{ {
return; return;
} }
   
this.SetResources(); SetResources();
this.SetSlidePosition(); SetSlidePosition();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion #endregion
   
#region Methods: private #region Methods: private
  private static Part part;
  private static PartResource partResource;
   
private void SetResources() private void SetResources()
{ {
var previousCount = this.resources.Count; int previousCount = resources.Count;
this.resources.Clear(); resources.Clear();
foreach (var resource in EditorLogic.fetch.ship.parts.SelectMany(p => p.Resources.list).Where(r => r.amount > 0.0))  
{ for (int i = 0; i < EditorLogic.fetch.ship.parts.Count; ++i)
if (this.resources.ContainsKey(resource.info.id)) {
{ part = EditorLogic.fetch.ship.parts[i];
this.resources[resource.info.id].Amount += resource.amount; for (int j = 0; j < part.Resources.list.Count; ++j)
} {
else partResource = part.Resources.list[j];
{  
this.resources.Add(resource.info.id, new ResourceInfoItem(resource)); if (resources.ContainsKey(partResource.info.id))
} {
} resources[partResource.info.id].Amount += partResource.amount;
  }
if (this.resources.Count < previousCount) else
{ {
this.windowPosition.height = 0; resources.Add(partResource.info.id, new ResourceInfoItem(partResource));
  }
  }
  }
   
  if (resources.Count < previousCount)
  {
  windowPosition.height = 0;
} }
} }
   
private void SetSlidePosition() private void SetSlidePosition()
{ {
if (this.open && this.openPercent < 1.0f) if (open && openPercent < 1.0f)
{ {
this.openPercent = Mathf.Clamp(this.openPercent + Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f); openPercent = Mathf.Clamp(openPercent + Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f);
} }
else if (!this.open && this.openPercent > 0.0f) else if (!open && openPercent > 0.0f)
{ {
this.openPercent = Mathf.Clamp(this.openPercent - Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f); openPercent = Mathf.Clamp(openPercent - Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f);
} }
   
this.windowPosition.x = BuildOverlay.BuildOverlayVessel.WindowPosition.xMax + 5.0f; windowPosition.x = BuildOverlay.BuildOverlayVessel.WindowPosition.xMax + 5.0f;
this.windowPosition.y = Mathf.Lerp(Screen.height, Screen.height - this.windowPosition.height, this.openPercent); windowPosition.y = Mathf.Lerp(Screen.height, Screen.height - windowPosition.height, openPercent);
this.tabPosition.width = this.tabSize.x; tabPosition.width = tabSize.x;
this.tabPosition.height = this.tabSize.y; tabPosition.height = tabSize.y;
this.tabPosition.x = this.windowPosition.x; tabPosition.x = windowPosition.x;
this.tabPosition.y = this.windowPosition.y - this.tabPosition.height; tabPosition.y = windowPosition.y - tabPosition.height;
} }
   
private void Window(int windowId) private void Window(int windowId)
{ {
try try
{ {
var firstItem = true; bool firstItem = true;
foreach (var resource in this.resources) foreach (KeyValuePair<int, ResourceInfoItem> resource in resources)
{ {
if (!firstItem) if (!firstItem)
{ {
GUILayout.Space(2.0f); GUILayout.Space(2.0f);
} }
firstItem = false; firstItem = false;
   
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
   
GUILayout.Label(resource.Value.Name + ":", BuildOverlay.NameStyle); GUILayout.Label(resource.Value.Name + ":", BuildOverlay.NameStyle);
GUILayout.Space(50.0f); GUILayout.Space(50.0f);
if (resource.Value.Mass > 0.0) if (resource.Value.Mass > 0.0)
{ {
GUILayout.Label("(" + resource.Value.Mass.ToMass() + ") " + resource.Value.Amount.ToString("N1"), BuildOverlay.ValueStyle); GUILayout.Label("(" + resource.Value.Mass.ToMass() + ") " + resource.Value.Amount.ToString("N1"), BuildOverlay.ValueStyle);
} }
else else
{ {
GUILayout.Label(resource.Value.Amount.ToString("N1"), BuildOverlay.ValueStyle); GUILayout.Label(resource.Value.Amount.ToString("N1"), BuildOverlay.ValueStyle);
} }
   
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using System;  
using System.Collections.Generic;  
   
using KerbalEngineer.Extensions;  
using KerbalEngineer.VesselSimulator;  
   
using UnityEngine;  
   
#endregion #endregion
   
namespace KerbalEngineer.Editor namespace KerbalEngineer.Editor
{ {
  #region Using Directives
  using System;
  using System.Collections.Generic;
  using Helpers;
  using UnityEngine;
  using VesselSimulator;
   
  #endregion
   
public class BuildOverlayVessel : MonoBehaviour public class BuildOverlayVessel : MonoBehaviour
{ {
  #region Constants
  private const float Width = 175.0f;
  #endregion
   
#region Fields #region Fields
   
private static bool visible = true; private static bool visible = true;
   
private readonly List<PartInfoItem> infoItems = new List<PartInfoItem>(); private readonly List<PartInfoItem> infoItems = new List<PartInfoItem>();
   
private Stage lastStage; private Stage lastStage;
private bool open = true; private bool open = true;
private float openPercent; private float openPercent;
private GUIContent tabContent; private GUIContent tabContent;
private Rect tabPosition; private Rect tabPosition;
private Vector2 tabSize; private Vector2 tabSize;
private Rect windowPosition = new Rect(300.0f, 0.0f, BuildOverlay.MinimumWidth, 0.0f); private Rect windowPosition = new Rect(330.0f, 0.0f, Width, 0.0f);
   
#endregion #endregion
   
#region Properties #region Properties
   
public static bool Visible public static bool Visible
{ {
get { return visible; } get
set { visible = value; } {
  return visible;
  }
  set
  {
  visible = value;
  }
} }
   
public bool Open public bool Open
{ {
get { return this.open; } get
set { this.open = value; } {
  return open;
  }
  set
  {
  open = value;
  }
} }
   
public Rect WindowPosition public Rect WindowPosition
{ {
get { return this.windowPosition; } get
} {
  return windowPosition;
#endregion }
  }
#region Methods: protected  
  public float WindowX
  {
  get
  {
  return windowPosition.x;
  }
  set
  {
  windowPosition.x = value;
  }
  }
  #endregion
   
  #region Methods
  protected void Awake()
  {
  try
  {
  SimManager.OnReady -= GetStageInfo;
  SimManager.OnReady += GetStageInfo;
  }
  catch (Exception ex)
  {
  Logger.Exception(ex);
  }
  }
   
protected void OnGUI() protected void OnGUI()
{ {
try try
{ {
if (!Visible || EditorLogic.startPod == null || this.lastStage == null || EditorLogic.fetch.editorScreen != EditorLogic.EditorScreen.Parts) if (!Visible || EditorLogic.RootPart == null || EditorLogic.fetch.editorScreen != EditorScreen.Parts)
{ {
return; return;
} }
   
this.open = GUI.Toggle(this.tabPosition, this.open, this.tabContent, BuildOverlay.TabStyle); open = GUI.Toggle(tabPosition, open, tabContent, BuildOverlay.TabStyle);
if (this.openPercent > 0.0) if (openPercent > 0.0)
{ {
this.windowPosition = GUILayout.Window(this.GetInstanceID(), this.windowPosition, this.VesselWindow, String.Empty, BuildOverlay.WindowStyle); windowPosition = GUILayout.Window(GetInstanceID(), windowPosition, VesselWindow, String.Empty, BuildOverlay.WindowStyle);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
protected void Start() protected void Start()
{ {
try try
{ {
this.tabContent = new GUIContent("VESSEL"); tabContent = new GUIContent("VESSEL");
this.tabSize = BuildOverlay.TabStyle.CalcSize(this.tabContent); tabSize = BuildOverlay.TabStyle.CalcSize(tabContent);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
protected void Update() protected void Update()
{ {
if (!Visible || EditorLogic.startPod == null) try
{ {
return; if (!Visible || EditorLogic.RootPart == null)
} {
  return;
if (this.openPercent > 0.0) }
{  
this.SetVesselInfo(); if (openPercent > 0.0)
} {
  SetVesselInfo();
this.SetSlidePosition(); }
}  
  SetSlidePosition();
#endregion }
  catch (Exception ex)
#region Methods: private {
  Logger.Exception(ex);
  }
  }
   
  private void GetStageInfo()
  {
  lastStage = SimManager.LastStage;
  }
   
private void SetSlidePosition() private void SetSlidePosition()
{ {
if (this.open && this.openPercent < 1.0f) if (open && openPercent < 1.0f)
{ {
this.openPercent = Mathf.Clamp(this.openPercent + Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f); openPercent = Mathf.Clamp(openPercent + Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f);
} }
else if (!this.open && this.openPercent > 0.0f) else if (!open && openPercent > 0.0f)
{ {
this.openPercent = Mathf.Clamp(this.openPercent - Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f); openPercent = Mathf.Clamp(openPercent - Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f);
} }
   
this.windowPosition.y = Mathf.Lerp(Screen.height, Screen.height - this.windowPosition.height, this.openPercent); windowPosition.y = Mathf.Lerp(Screen.height, Screen.height - windowPosition.height, openPercent);
this.tabPosition.width = this.tabSize.x; if (windowPosition.width < Width)
this.tabPosition.height = this.tabSize.y; {
this.tabPosition.x = this.windowPosition.x; windowPosition.width = Width;
this.tabPosition.y = this.windowPosition.y - this.tabPosition.height; }
  tabPosition.width = tabSize.x;
  tabPosition.height = tabSize.y;
  tabPosition.x = windowPosition.x;
  tabPosition.y = windowPosition.y - tabPosition.height;
} }
   
private void SetVesselInfo() private void SetVesselInfo()
{ {
SimManager.Gravity = CelestialBodies.SelectedBody.Gravity; SimManager.Gravity = CelestialBodies.SelectedBody.Gravity;
   
if (BuildAdvanced.Instance.ShowAtmosphericDetails) if (BuildAdvanced.Instance.ShowAtmosphericDetails)
{ {
SimManager.Atmosphere = CelestialBodies.SelectedBody.Atmosphere * 0.01; SimManager.Atmosphere = CelestialBodies.SelectedBody.GetAtmospheres(BuildAdvanced.Altitude);
} }
else else
{ {
SimManager.Atmosphere = 0.0; SimManager.Atmosphere = 0.0;
} }
   
SimManager.RequestSimulation(); SimManager.RequestSimulation();
SimManager.TryStartSimulation(); SimManager.TryStartSimulation();
   
if (SimManager.ResultsReady()) if (lastStage != null)
{ {
this.lastStage = SimManager.LastStage; PartInfoItem.Release(infoItems);
} infoItems.Clear();
  infoItems.Add(PartInfoItem.Create("Delta-V", lastStage.deltaV.ToString("N0") + " / " + lastStage.totalDeltaV.ToString("N0") + "m/s"));
if (this.lastStage != null) infoItems.Add(PartInfoItem.Create("Mass", Units.ToMass(lastStage.mass, lastStage.totalMass)));
{ infoItems.Add(PartInfoItem.Create("TWR", lastStage.thrustToWeight.ToString("F2") + " (" + lastStage.maxThrustToWeight.ToString("F2") + ")"));
this.infoItems.Clear(); infoItems.Add(PartInfoItem.Create("Parts", lastStage.partCount + " / " + lastStage.totalPartCount));
this.infoItems.Add(new PartInfoItem("Delta-V", this.lastStage.totalDeltaV.ToString("N0") + "m/s"));  
this.infoItems.Add(new PartInfoItem("Mass", this.lastStage.totalMass.ToMass()));  
this.infoItems.Add(new PartInfoItem("TWR", this.lastStage.thrustToWeight.ToString("F2")));  
this.infoItems.Add(new PartInfoItem("Parts", this.lastStage.partCount.ToString("N0")));  
} }
} }
   
private void VesselWindow(int windowId) private void VesselWindow(int windowId)
{ {
try try
{ {
var firstItem = true; bool firstItem = true;
foreach (var item in this.infoItems) foreach (PartInfoItem item in infoItems)
{ {
if (!firstItem) if (!firstItem)
{ {
GUILayout.Space(2.0f); GUILayout.Space(2.0f);
} }
firstItem = false; firstItem = false;
   
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
if (item.Value != null) if (item.Value != null)
{ {
GUILayout.Label(item.Name + ":", BuildOverlay.NameStyle); GUILayout.Label(item.Name + ":", BuildOverlay.NameStyle);
GUILayout.Space(50.0f); GUILayout.FlexibleSpace();
GUILayout.Label(item.Value, BuildOverlay.ValueStyle); GUILayout.Label(item.Value, BuildOverlay.ValueStyle);
} }
else else
{ {
GUILayout.Label(item.Name, BuildOverlay.NameStyle); GUILayout.Label(item.Name, BuildOverlay.NameStyle);
} }
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using System; using System;
   
using UnityEngine; using UnityEngine;
   
#endregion #endregion
   
namespace KerbalEngineer.Editor namespace KerbalEngineer.Editor
{ {
[KSPAddon(KSPAddon.Startup.EditorAny, false)] [KSPAddon(KSPAddon.Startup.EditorAny, false)]
public class BuildToolbar : MonoBehaviour public class BuildToolbar : MonoBehaviour
{ {
#region Fields #region Fields
   
private ApplicationLauncherButton button; private ApplicationLauncherButton button;
   
#endregion #endregion
   
#region Methods: private #region Methods: private
   
private void Awake() private void Awake()
{ {
GameEvents.onGUIApplicationLauncherReady.Add(this.OnGuiAppLauncherReady); GameEvents.onGUIApplicationLauncherReady.Add(this.OnGuiAppLauncherReady);
Logger.Log("BuildToolbar->Awake"); Logger.Log("BuildToolbar->Awake");
  }
   
  private void Start()
  {
  if (button == null)
  {
  OnGuiAppLauncherReady();
  }
} }
   
private void OnDestroy() private void OnDestroy()
{ {
GameEvents.onGUIApplicationLauncherReady.Remove(this.OnGuiAppLauncherReady); GameEvents.onGUIApplicationLauncherReady.Remove(this.OnGuiAppLauncherReady);
if (this.button != null) if (this.button != null)
{ {
ApplicationLauncher.Instance.RemoveModApplication(this.button); ApplicationLauncher.Instance.RemoveModApplication(this.button);
} }
Logger.Log("BuildToolbar->OnDestroy"); Logger.Log("BuildToolbar->OnDestroy");
} }
   
private void OnGuiAppLauncherReady() private void OnGuiAppLauncherReady()
{ {
try try
{ {
this.button = ApplicationLauncher.Instance.AddModApplication( this.button = ApplicationLauncher.Instance.AddModApplication(
() => BuildAdvanced.Instance.Visible = true, () => BuildAdvanced.Instance.Visible = true,
() => BuildAdvanced.Instance.Visible = false, () => BuildAdvanced.Instance.Visible = false,
null, null,
null, null,
null, null,
null, null,
ApplicationLauncher.AppScenes.ALWAYS, ApplicationLauncher.AppScenes.ALWAYS,
GameDatabase.Instance.GetTexture("KerbalEngineer/Textures/ToolbarIcon", false) GameDatabase.Instance.GetTexture("KerbalEngineer/Textures/ToolbarIcon", false)
); );
Logger.Log("BuildToolbar->OnGuiAppLauncherReady"); Logger.Log("BuildToolbar->OnGuiAppLauncherReady");
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex, "BuildToolbar->OnGuiAppLauncherReady"); Logger.Exception(ex, "BuildToolbar->OnGuiAppLauncherReady");
} }
} }
   
private void Update() private void Update()
{ {
try try
{ {
if (this.button == null) if (this.button == null)
{ {
return; return;
} }
   
if (EditorLogic.fetch != null && EditorLogic.fetch.ship.parts.Count > 0) if (EditorLogic.fetch != null && EditorLogic.fetch.ship.parts.Count > 0)
{ {
if (BuildAdvanced.Instance.Visible && this.button.State != RUIToggleButton.ButtonState.TRUE) if (BuildAdvanced.Instance.Visible && this.button.State != RUIToggleButton.ButtonState.TRUE)
{ {
this.button.SetTrue(); this.button.SetTrue();
} }
else if (!BuildAdvanced.Instance.Visible && this.button.State != RUIToggleButton.ButtonState.FALSE) else if (!BuildAdvanced.Instance.Visible && this.button.State != RUIToggleButton.ButtonState.FALSE)
{ {
this.button.SetFalse(); this.button.SetFalse();
} }
} }
else if (this.button.State != RUIToggleButton.ButtonState.DISABLED) else if (this.button.State != RUIToggleButton.ButtonState.DISABLED)
{ {
this.button.Disable(); this.button.Disable();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex, "BuildToolbar->Update"); Logger.Exception(ex, "BuildToolbar->Update");
} }
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
namespace KerbalEngineer.Editor namespace KerbalEngineer.Editor
{ {
  using System.Collections.Generic;
  using VesselSimulator;
   
public class PartInfoItem public class PartInfoItem
{ {
#region Constructors private static readonly Pool<PartInfoItem> pool = new Pool<PartInfoItem>(Create, Reset);
   
public PartInfoItem(string name)  
{  
this.Name = name;  
}  
   
public PartInfoItem(string name, string value)  
{  
this.Name = name;  
this.Value = value;  
}  
   
#endregion  
   
#region Properties  
   
public string Name { get; set; } public string Name { get; set; }
   
public string Value { get; set; } public string Value { get; set; }
   
#endregion private static PartInfoItem Create()
  {
  return new PartInfoItem();
  }
   
  public void Release()
  {
  pool.Release(this);
  }
   
  public static void Release(List<PartInfoItem> objList)
  {
  for (int i = 0; i < objList.Count; ++i)
  {
  objList[i].Release();
  }
  }
   
  private static void Reset(PartInfoItem obj)
  {
  obj.Name = string.Empty;
  obj.Value = string.Empty;
  }
   
  public static PartInfoItem Create(string name)
  {
  return New(name);
  }
   
  public static PartInfoItem Create(string name, string value)
  {
  return New(name, value);
  }
   
  public static PartInfoItem New(string name)
  {
  PartInfoItem obj = pool.Borrow();
   
  obj.Name = name;
  obj.Value = string.Empty;
   
  return obj;
  }
   
  public static PartInfoItem New(string name, string value)
  {
  PartInfoItem obj = pool.Borrow();
   
  obj.Name = name;
  obj.Value = value;
   
  return obj;
  }
} }
} }
// //
// Kerbal Engineer Redux // Copyright (C) 2015 CYBUTEK
//  
// Copyright (C) 2014 CYBUTEK  
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives  
   
using System.IO;  
using System.Reflection;  
   
#endregion  
   
namespace KerbalEngineer namespace KerbalEngineer
{ {
public class EngineerGlobals using System.IO;
  using System.Reflection;
   
  public static class EngineerGlobals
{ {
#region Constants  
   
/// <summary> /// <summary>
/// Current version of the Kerbal Engineer assembly. /// Current version of the Kerbal Engineer assembly.
/// </summary> /// </summary>
public const string AssemblyVersion = "1.0.9.3"; public const string ASSEMBLY_VERSION = "1.0.17.0";
   
#endregion  
   
#region Fields  
   
private static string assemblyFile; private static string assemblyFile;
private static string assemblyName; private static string assemblyName;
private static string assemblyPath; private static string assemblyPath;
   
#endregion  
   
#region Properties  
   
/// <summary> /// <summary>
/// Gets the Kerbal Engineer assembly's path including the file name. /// Gets the Kerbal Engineer assembly's path including the file name.
/// </summary> /// </summary>
public static string AssemblyFile public static string AssemblyFile
{ {
get { return assemblyFile ?? (assemblyFile = Assembly.GetExecutingAssembly().Location); } get
  {
  return assemblyFile ?? (assemblyFile = Assembly.GetExecutingAssembly().Location);
  }
} }
   
/// <summary> /// <summary>
/// Gets the Kerbal Engineer assembly's file name. /// Gets the Kerbal Engineer assembly's file name.
/// </summary> /// </summary>
public static string AssemblyName public static string AssemblyName
{ {
get { return assemblyName ?? (assemblyName = new FileInfo(AssemblyFile).Name); } get
  {
  return assemblyName ?? (assemblyName = new FileInfo(AssemblyFile).Name);
  }
} }
   
/// <summary> /// <summary>
/// Gets the Kerbal Engineer assembly's path excluding the file name. /// Gets the Kerbal Engineer assembly's path excluding the file name.
/// </summary> /// </summary>
public static string AssemblyPath public static string AssemblyPath
{ {
get { return assemblyPath ?? (assemblyPath = AssemblyFile.Replace(new FileInfo(AssemblyFile).Name, "")); } get
  {
  return assemblyPath ?? (assemblyPath = AssemblyFile.Replace(new FileInfo(AssemblyFile).Name, ""));
  }
} }
   
#endregion  
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2015 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives  
   
using KerbalEngineer.Helpers;  
   
#endregion  
   
namespace KerbalEngineer.Extensions namespace KerbalEngineer.Extensions
{ {
  using Helpers;
   
public static class DoubleExtensions public static class DoubleExtensions
{ {
#region Methods: public public static double Clamp(this double value, double lower, double higher)
  {
  return value < lower ? lower : value > higher ? higher : value;
  }
   
public static string ToAcceleration(this double value) public static string ToAcceleration(this double value)
{ {
return Units.ToAcceleration(value); return Units.ToAcceleration(value);
} }
   
public static string ToAngle(this double value) public static string ToAngle(this double value)
{ {
return Units.ToAngle(value); return Units.ToAngle(value);
} }
   
public static string ToDistance(this double value) public static string ToDistance(this double value)
{ {
return Units.ToDistance(value); return Units.ToDistance(value);
} }
   
  public static string ToFlux(this double value)
  {
  return Units.ToFlux(value);
  }
   
public static string ToForce(this double value) public static string ToForce(this double value)
{ {
return Units.ToForce(value); return Units.ToForce(value);
  }
   
  public static string ToMach(this double value)
  {
  return Units.ToMach(value);
} }
   
public static string ToMass(this double value) public static string ToMass(this double value)
{ {
return Units.ToMass(value); return Units.ToMass(value);
} }
   
public static string ToPercent(this double value) public static string ToPercent(this double value)
{ {
return Units.ToPercent(value); return Units.ToPercent(value);
} }
   
public static string ToRate(this double value) public static string ToRate(this double value)
{ {
return Units.ToRate(value); return Units.ToRate(value);
} }
   
public static string ToSpeed(this double value) public static string ToSpeed(this double value)
{ {
return Units.ToSpeed(value); return Units.ToSpeed(value);
} }
   
#endregion public static string ToTemperature(this double value)
  {
  return Units.ToTemperature(value);
  }
   
  public static string ToTorque(this double value)
  {
  return Units.ToTorque(value);
  }
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2015 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives  
   
using KerbalEngineer.Helpers;  
   
#endregion  
   
namespace KerbalEngineer.Extensions namespace KerbalEngineer.Extensions
{ {
  using Helpers;
   
public static class FloatExtensions public static class FloatExtensions
{ {
#region Methods: public  
   
public static string ToAcceleration(this float value) public static string ToAcceleration(this float value)
{ {
return Units.ToAcceleration(value); return Units.ToAcceleration(value);
} }
   
public static string ToAngle(this float value) public static string ToAngle(this float value)
{ {
return Units.ToAngle(value); return Units.ToAngle(value);
} }
   
public static string ToDistance(this float value) public static string ToDistance(this float value)
{ {
return Units.ToDistance(value); return Units.ToDistance(value);
} }
   
  public static string ToFlux(this float value)
  {
  return Units.ToFlux(value);
  }
   
public static string ToForce(this float value) public static string ToForce(this float value)
{ {
return Units.ToForce(value); return Units.ToForce(value);
  }
   
  public static string ToMach(this float value)
  {
  return Units.ToMach(value);
} }
   
public static string ToMass(this float value) public static string ToMass(this float value)
{ {
return Units.ToMass(value); return Units.ToMass(value);
} }
   
public static string ToPercent(this float value) public static string ToPercent(this float value)
{ {
return Units.ToPercent(value); return Units.ToPercent(value);
} }
   
public static string ToRate(this float value) public static string ToRate(this float value)
{ {
return Units.ToRate(value); return Units.ToRate(value);
} }
   
public static string ToSpeed(this float value) public static string ToSpeed(this float value)
{ {
return Units.ToSpeed(value); return Units.ToSpeed(value);
} }
   
#endregion public static string ToTemperature(this float value)
  {
  return Units.ToTemperature(value);
  }
   
  public static string ToTorque(this float value)
  {
  return Units.ToTorque(value);
  }
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using System; using System;
   
using KerbalEngineer.Helpers; using KerbalEngineer.Helpers;
   
using UnityEngine; using UnityEngine;
   
#endregion #endregion
   
namespace KerbalEngineer.Extensions namespace KerbalEngineer.Extensions
{ {
public static class OrbitExtensions public static class OrbitExtensions
{ {
#region Constants #region Constants
   
public const double Tau = Math.PI * 2.0; public const double Tau = Math.PI * 2.0;
   
#endregion #endregion
   
#region Methods: public #region Methods: public
   
public static double GetAngleToAscendingNode(this Orbit orbit) public static double GetAngleToAscendingNode(this Orbit orbit)
{ {
return GetAngleToTrueAnomaly(orbit, GetTrueAnomalyOfAscendingNode(orbit)); return GetAngleToTrueAnomaly(orbit, GetTrueAnomalyOfAscendingNode(orbit));
} }
   
public static double GetAngleToDescendingNode(this Orbit orbit) public static double GetAngleToDescendingNode(this Orbit orbit)
{ {
return GetAngleToTrueAnomaly(orbit, GetTrueAnomalyOfDescendingNode(orbit)); return GetAngleToTrueAnomaly(orbit, GetTrueAnomalyOfDescendingNode(orbit));
} }
   
public static double GetAngleToPrograde(this Orbit orbit) public static double GetAngleToPrograde(this Orbit orbit)
{ {
if (orbit.referenceBody == CelestialBodies.SystemBody.CelestialBody) return GetAngleToPrograde(orbit, Planetarium.GetUniversalTime());
{  
return 0.0;  
}  
   
var angle = AngleHelper.GetAngleBetweenVectors(orbit.getRelativePositionAtUT(Planetarium.GetUniversalTime()),  
Vector3d.Exclude(orbit.GetOrbitNormal(), orbit.referenceBody.orbit.getRelativePositionAtUT(Planetarium.GetUniversalTime())));  
   
angle = AngleHelper.Clamp360(angle + 90.0);  
   
return orbit.inclination <= 90.0 ? angle : 360.0 - angle;  
} }
   
public static double GetAngleToRetrograde(this Orbit orbit) public static double GetAngleToPrograde(this Orbit orbit, double universalTime)
{ {
if (orbit.referenceBody == CelestialBodies.SystemBody.CelestialBody) if (orbit.referenceBody == CelestialBodies.SystemBody.CelestialBody)
{ {
return 0.0; return 0.0;
} }
   
var angle = AngleHelper.GetAngleBetweenVectors(orbit.getRelativePositionAtUT(Planetarium.GetUniversalTime()), var angle = AngleHelper.GetAngleBetweenVectors(orbit.getRelativePositionAtUT(universalTime),
Vector3d.Exclude(orbit.GetOrbitNormal(), orbit.referenceBody.orbit.getRelativePositionAtUT(Planetarium.GetUniversalTime()))); Vector3d.Exclude(orbit.GetOrbitNormal(), orbit.referenceBody.orbit.getRelativePositionAtUT(universalTime)));
   
angle = AngleHelper.Clamp360(angle - 90.0); angle = AngleHelper.Clamp360(angle - 90.0);
   
return orbit.inclination <= 90.0 ? angle : 360.0 - angle; return orbit.inclination > 90.0 ? angle : 360.0 - angle;
  }
   
  public static double GetAngleToRetrograde(this Orbit orbit)
  {
  return GetAngleToRetrograde(orbit, Planetarium.GetUniversalTime());
  }
   
  public static double GetAngleToRetrograde(this Orbit orbit, double universalTime)
  {
  if (orbit.referenceBody == CelestialBodies.SystemBody.CelestialBody)
  {
  return 0.0;
  }
   
  var angle = AngleHelper.GetAngleBetweenVectors(orbit.getRelativePositionAtUT(universalTime),
  Vector3d.Exclude(orbit.GetOrbitNormal(), orbit.referenceBody.orbit.getRelativePositionAtUT(universalTime)));
   
  angle = AngleHelper.Clamp360(angle + 90.0);
   
  return orbit.inclination > 90.0 ? angle : 360.0 - angle;
} }
   
public static double GetAngleToTrueAnomaly(this Orbit orbit, double trueAnomaly) public static double GetAngleToTrueAnomaly(this Orbit orbit, double trueAnomaly)
{ {
return AngleHelper.Clamp360(trueAnomaly - orbit.trueAnomaly); return AngleHelper.Clamp360(trueAnomaly - orbit.trueAnomaly);
} }
   
public static double GetAngleToVector(this Orbit orbit, Vector3d vector) public static double GetAngleToVector(this Orbit orbit, Vector3d vector)
{ {
return GetAngleToTrueAnomaly(orbit, GetTrueAnomalyFromVector(orbit, Vector3d.Exclude(orbit.GetOrbitNormal(), vector))); return GetAngleToTrueAnomaly(orbit, GetTrueAnomalyFromVector(orbit, Vector3d.Exclude(orbit.GetOrbitNormal(), vector)));
} }
   
public static double GetPhaseAngle(this Orbit orbit, Orbit target) public static double GetPhaseAngle(this Orbit orbit, Orbit target)
{ {
return orbit.inclination <= 90.0 var angle = AngleHelper.GetAngleBetweenVectors(Vector3d.Exclude(orbit.GetOrbitNormal(), target.pos), orbit.pos);
? AngleHelper.GetAngleBetweenVectors(orbit.pos, Vector3d.Exclude(orbit.GetOrbitNormal(), target.pos)) return (orbit.semiMajorAxis < target.semiMajorAxis) ? angle : angle - 360.0;
: AngleHelper.GetAngleBetweenVectors(Vector3d.Exclude(orbit.GetOrbitNormal(), target.pos), orbit.pos);  
} }
   
public static double GetRelativeInclination(this Orbit orbit, Orbit target) public static double GetRelativeInclination(this Orbit orbit, Orbit target)
{ {
return Vector3d.Angle(orbit.GetOrbitNormal(), target.GetOrbitNormal()); return Vector3d.Angle(orbit.GetOrbitNormal(), target.GetOrbitNormal());
} }
   
public static double GetTimeToAscendingNode(this Orbit orbit) public static double GetTimeToAscendingNode(this Orbit orbit)
{ {
return GetTimeToTrueAnomaly(orbit, GetTrueAnomalyOfAscendingNode(orbit)); return GetTimeToTrueAnomaly(orbit, GetTrueAnomalyOfAscendingNode(orbit));
} }
   
public static double GetTimeToDescendingNode(this Orbit orbit) public static double GetTimeToDescendingNode(this Orbit orbit)
{ {
return GetTimeToTrueAnomaly(orbit, GetTrueAnomalyOfDescendingNode(orbit)); return GetTimeToTrueAnomaly(orbit, GetTrueAnomalyOfDescendingNode(orbit));
} }
   
public static double GetTimeToTrueAnomaly(this Orbit orbit, double trueAnomaly) public static double GetTimeToTrueAnomaly(this Orbit orbit, double trueAnomaly)
{ {
var time = orbit.GetDTforTrueAnomaly(trueAnomaly * Mathf.Deg2Rad, orbit.period); var time = orbit.GetDTforTrueAnomaly(trueAnomaly * Mathf.Deg2Rad, orbit.period);
return time < 0.0 ? time + orbit.period : time; return time < 0.0 ? time + orbit.period : time;
} }
   
public static double GetTimeToVector(this Orbit orbit, Vector3d vector) public static double GetTimeToVector(this Orbit orbit, Vector3d vector)
{ {
return GetTimeToTrueAnomaly(orbit, GetTrueAnomalyFromVector(orbit, vector)); return GetTimeToTrueAnomaly(orbit, GetTrueAnomalyFromVector(orbit, vector));
} }
   
public static double GetTrueAnomalyFromVector(this Orbit orbit, Vector3d vector) public static double GetTrueAnomalyFromVector(this Orbit orbit, Vector3d vector)
{ {
return orbit.GetTrueAnomalyOfZupVector(vector) * Mathf.Rad2Deg; return orbit.GetTrueAnomalyOfZupVector(vector) * Mathf.Rad2Deg;
} }
   
public static double GetTrueAnomalyOfAscendingNode(this Orbit orbit) public static double GetTrueAnomalyOfAscendingNode(this Orbit orbit)
{ {
return 360.0 - orbit.argumentOfPeriapsis; return 360.0 - orbit.argumentOfPeriapsis;
} }
   
public static double GetTrueAnomalyOfDescendingNode(this Orbit orbit) public static double GetTrueAnomalyOfDescendingNode(this Orbit orbit)
{ {
return 180.0 - orbit.argumentOfPeriapsis; return 180.0 - orbit.argumentOfPeriapsis;
} }
   
#endregion #endregion
} }
} }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives  
   
using System;  
using System.Collections.Generic;  
using System.Linq;  
   
#endregion  
   
namespace KerbalEngineer.Extensions namespace KerbalEngineer.Extensions
{ {
  using System;
  using System.Collections.Generic;
  using CompoundParts;
   
public static class PartExtensions public static class PartExtensions
{ {
#region Methods: public //private static Part cachePart;
  //private static PartModule cachePartModule;
  //private static PartResource cachePartResource;
   
/// <summary> /// <summary>
/// Gets whether the part contains a specific resource. /// Gets whether the part contains a specific resource.
/// </summary> /// </summary>
public static bool ContainsResource(this Part part, int resourceId) public static bool ContainsResource(this Part part, int resourceId)
{ {
return part.Resources.Contains(resourceId); return part.Resources.Contains(resourceId);
} }
   
/// <summary> /// <summary>
/// Gets whether the part contains resources. /// Gets whether the part contains resources.
/// </summary> /// </summary>
public static bool ContainsResources(this Part part) public static bool ContainsResources(this Part part)
{ {
return part.Resources.list.Count(p => p.amount > 0d) > 0; for (int i = 0; i < part.Resources.list.Count; ++i)
  {
  if (part.Resources.list[i].amount > 0.0)
  {
  return true;
  }
  }
  return false;
} }
   
/// <summary> /// <summary>
/// Gets whether the part has fuel. /// Gets whether the part has fuel.
/// </summary> /// </summary>
  /* not used
public static bool EngineHasFuel(this Part part) public static bool EngineHasFuel(this Part part)
{ {
if (part.HasModule<ModuleEngines>()) PartModule cachePartModule = GetModule<ModuleEngines>(part);
{ if (cachePartModule != null)
return part.GetModuleEngines().getFlameoutState; {
} return (cachePartModule as ModuleEngines).getFlameoutState;
if (part.HasModule<MultiModeEngine>()) }
{  
return part.GetModuleMultiModeEngine().getFlameoutState; cachePartModule = GetModuleMultiModeEngine(part);
  if (cachePartModule != null)
  {
  return (cachePartModule as ModuleEnginesFX).getFlameoutState;
} }
   
return false; return false;
} }
  */
/// <summary> /// <summary>
/// Gets the cost of the part excluding resources. /// Gets the cost of the part excluding resources.
/// </summary> /// </summary>
public static double GetCostDry(this Part part) public static double GetCostDry(this Part part)
{ {
return part.partInfo.cost - GetResourceCostMax(part) + part.GetModuleCosts(); return part.partInfo.cost - GetResourceCostMax(part) + part.GetModuleCosts(0.0f);
} }
   
/// <summary> /// <summary>
/// Gets the cost of the part including maximum resources. /// Gets the cost of the part including maximum resources.
/// </summary> /// </summary>
public static double GetCostMax(this Part part) public static double GetCostMax(this Part part)
{ {
return part.partInfo.cost + part.GetModuleCosts(); return part.partInfo.cost + part.GetModuleCosts(0.0f);
  }
   
  /// <summary>
  /// Gets the cost of the part modules
  /// Same as stock but without mem allocation
  /// </summary>
  public static double GetModuleCostsNoAlloc(this Part part, float defaultCost)
  {
  float cost = 0f;
  for (int i = 0; i < part.Modules.Count; i++)
  {
  PartModule pm = part.Modules[i];
  if (pm is IPartCostModifier)
  cost += (pm as IPartCostModifier).GetModuleCost(defaultCost);
  }
  return cost;
} }
   
/// <summary> /// <summary>
/// Gets the cost of the part including resources. /// Gets the cost of the part including resources.
/// </summary> /// </summary>
public static double GetCostWet(this Part part) public static double GetCostWet(this Part part)
{ {
return part.partInfo.cost - GetResourceCostInverted(part) + part.GetModuleCosts(); return part.partInfo.cost - GetResourceCostInverted(part) + part.GetModuleCostsNoAlloc(0.0f); // part.GetModuleCosts allocate 44B per call.
} }
   
/// <summary> /// <summary>
/// Gets the dry mass of the part. /// Gets the dry mass of the part.
/// </summary> /// </summary>
public static double GetDryMass(this Part part) public static double GetDryMass(this Part part)
{ {
return (part.physicalSignificance == Part.PhysicalSignificance.FULL) ? part.mass : 0d; return (part.physicalSignificance == Part.PhysicalSignificance.FULL) ? part.mass : 0d;
} }
   
/// <summary> /// <summary>
/// Gets the maximum thrust of the part if it's an engine. /// Gets the maximum thrust of the part if it's an engine.
/// </summary> /// </summary>
  /* not used
public static double GetMaxThrust(this Part part) public static double GetMaxThrust(this Part part)
{ {
if (part.HasModule<ModuleEngines>()) PartModule cachePartModule = GetModule<ModuleEngines>(part);
{ if (cachePartModule != null)
return part.GetModuleEngines().maxThrust; {
} return (cachePartModule as ModuleEngines).maxThrust;
if (part.HasModule<MultiModeEngine>()) }
{  
return part.GetModuleMultiModeEngine().maxThrust; cachePartModule = GetModuleMultiModeEngine(part) ?? GetModule<ModuleEnginesFX>(part);
} if (cachePartModule != null)
if (part.HasModule<ModuleEnginesFX>()) {
{ return (cachePartModule as ModuleEnginesFX).maxThrust;
return part.GetModuleEnginesFx().maxThrust; }
}  
  return 0.0;
return 0d; }
} */
   
/// <summary> /// <summary>
/// Gets the first typed PartModule in the part's module list. /// Gets the first typed PartModule in the part's module list.
/// </summary> /// </summary>
public static T GetModule<T>(this Part part) where T : PartModule public static T GetModule<T>(this Part part) where T : PartModule
{ {
return part.Modules.OfType<T>().FirstOrDefault(); for (int i = 0; i < part.Modules.Count; i++)
  {
  PartModule pm = part.Modules[i];
  if (pm is T)
  return (T)pm;
  }
  return null;
} }
   
/// <summary> /// <summary>
/// Gets a typed PartModule. /// Gets a typed PartModule.
/// </summary> /// </summary>
public static T GetModule<T>(this Part part, string className) where T : PartModule public static T GetModule<T>(this Part part, string className) where T : PartModule
{ {
return (T)Convert.ChangeType(part.Modules[className], typeof(T)); return part.Modules[className] as T;
} }
   
/// <summary> /// <summary>
/// Gets a typed PartModule. /// Gets a typed PartModule.
/// </summary> /// </summary>
public static T GetModule<T>(this Part part, int classId) where T : PartModule public static T GetModule<T>(this Part part, int classId) where T : PartModule
{ {
return (T)Convert.ChangeType(part.Modules[classId], typeof(T)); return part.Modules[classId] as T;
} }
   
/// <summary> /// <summary>
/// Gets a ModuleAlternator typed PartModule. /// Gets a ModuleAlternator typed PartModule.
/// </summary> /// </summary>
public static ModuleAlternator GetModuleAlternator(this Part part) public static ModuleAlternator GetModuleAlternator(this Part part)
{ {
return part.GetModule<ModuleAlternator>(); return GetModule<ModuleAlternator>(part);
} }
   
/// <summary> /// <summary>
/// Gets a ModuleDeployableSolarPanel typed PartModule. /// Gets a ModuleDeployableSolarPanel typed PartModule.
/// </summary> /// </summary>
public static ModuleDeployableSolarPanel GetModuleDeployableSolarPanel(this Part part) public static ModuleDeployableSolarPanel GetModuleDeployableSolarPanel(this Part part)
{ {
return part.GetModule<ModuleDeployableSolarPanel>(); return GetModule<ModuleDeployableSolarPanel>(part);
} }
   
/// <summary> /// <summary>
/// Gets a ModuleEngines typed PartModule. /// Gets a ModuleEngines typed PartModule.
/// </summary> /// </summary>
public static ModuleEngines GetModuleEngines(this Part part) public static ModuleEngines GetModuleEngines(this Part part)
{ {
return part.GetModule<ModuleEngines>(); return GetModule<ModuleEngines>(part);
} }
   
public static ModuleEnginesFX GetModuleEnginesFx(this Part part) /* public static ModuleEnginesFX GetModuleEnginesFx(this Part part)
{ {
return part.GetModule<ModuleEnginesFX>(); return GetModule<ModuleEnginesFX>(part);
} }*/
   
/// <summary> /// <summary>
/// Gets a ModuleGenerator typed PartModule. /// Gets a ModuleGenerator typed PartModule.
/// </summary> /// </summary>
public static ModuleGenerator GetModuleGenerator(this Part part) public static ModuleGenerator GetModuleGenerator(this Part part)
{ {
return part.GetModule<ModuleGenerator>(); return GetModule<ModuleGenerator>(part);
} }
   
/// <summary> /// <summary>
/// Gets a ModuleGimbal typed PartModule. /// Gets a ModuleGimbal typed PartModule.
/// </summary> /// </summary>
public static ModuleGimbal GetModuleGimbal(this Part part) public static ModuleGimbal GetModuleGimbal(this Part part)
{ {
return part.GetModule<ModuleGimbal>(); return GetModule<ModuleGimbal>(part);
} }
   
/// <summary> /// <summary>
/// Gets the current selected ModuleEnginesFX. /// Gets the current selected ModuleEnginesFX.
/// </summary> /// </summary>
public static ModuleEnginesFX GetModuleMultiModeEngine(this Part part) public static ModuleEngines GetModuleMultiModeEngine(this Part part)
{ {
var mode = part.GetModule<MultiModeEngine>().mode; ModuleEngines moduleEngines;
return part.Modules.OfType<ModuleEnginesFX>().FirstOrDefault(engine => engine.engineID == mode); MultiModeEngine multiMod = GetModule<MultiModeEngine>(part);
  if (multiMod != null)
  {
  string mode = multiMod.mode;
  for (int i = 0; i < part.Modules.Count; ++i)
  {
  moduleEngines = part.Modules[i] as ModuleEngines;
  if (moduleEngines != null && moduleEngines.engineID == mode)
  {
  return moduleEngines;
  }
  }
  }
  return null;
} }
   
/// <summary> /// <summary>
/// Gets a ModuleParachute typed PartModule. /// Gets a ModuleParachute typed PartModule.
/// </summary> /// </summary>
public static ModuleParachute GetModuleParachute(this Part part) public static ModuleParachute GetModuleParachute(this Part part)
{ {
return part.GetModule<ModuleParachute>(); return GetModule<ModuleParachute>(part);
} }
   
public static ModuleRCS GetModuleRcs(this Part part) public static ModuleRCS GetModuleRcs(this Part part)
{ {
return part.GetModule<ModuleRCS>(); return GetModule<ModuleRCS>(part);
} }
   
/// <summary> /// <summary>
/// Gets a typed list of PartModules. /// Gets a typed list of PartModules.
/// </summary> /// </summary>
public static List<T> GetModules<T>(this Part part) where T : PartModule public static List<T> GetModules<T>(this Part part) where T : PartModule
{ {
return part.Modules.OfType<T>().ToList(); List<T> list = new List<T>();
  for (int i = 0; i < part.Modules.Count; ++i)
  {
  T module = part.Modules[i] as T;
  if (module != null)
  {
  list.Add(module);
  }
  }
  return list;
} }
   
public static ProtoModuleDecoupler GetProtoModuleDecoupler(this Part part) public static ProtoModuleDecoupler GetProtoModuleDecoupler(this Part part)
{ {
if (HasModule<ModuleDecouple>(part)) PartModule cachePartModule = GetModule<ModuleDecouple>(part);
{ if (cachePartModule == null)
return new ProtoModuleDecoupler(GetModule<ModuleDecouple>(part)); {
} cachePartModule = GetModule<ModuleAnchoredDecoupler>(part);
if (HasModule<ModuleAnchoredDecoupler>(part)) }
{ if (cachePartModule != null)
return new ProtoModuleDecoupler(GetModule<ModuleAnchoredDecoupler>(part)); {
} return new ProtoModuleDecoupler(cachePartModule);
  }
   
return null; return null;
} }
   
/// <summary> /// <summary>
/// Gets a generic proto engine for the current engine module attached to the part. /// Gets a generic proto engine for the current engine module attached to the part.
/// </summary> /// </summary>
public static ProtoModuleEngine GetProtoModuleEngine(this Part part) public static ProtoModuleEngine GetProtoModuleEngine(this Part part)
{ {
if (HasModule<ModuleEngines>(part)) PartModule cachePartModule = GetModule<ModuleEngines>(part);
{ if (cachePartModule != null)
return new ProtoModuleEngine(GetModule<ModuleEngines>(part)); {
} return new ProtoModuleEngine(cachePartModule);
if (HasModule<MultiModeEngine>(part)) }
{  
return new ProtoModuleEngine(GetModuleMultiModeEngine(part)); cachePartModule = GetModuleMultiModeEngine(part) ?? GetModule<ModuleEnginesFX>(part);
} if (cachePartModule != null)
if (HasModule<ModuleEnginesFX>(part)) {
{ return new ProtoModuleEngine(cachePartModule);
return new ProtoModuleEngine(GetModule<ModuleEnginesFX>(part)); }
}  
return null; return null;
} }
   
/// <summary> /// <summary>
/// Gets the cost of the part's contained resources. /// Gets the cost of the part's contained resources.
/// </summary> /// </summary>
public static double GetResourceCost(this Part part) public static double GetResourceCost(this Part part)
{ {
return part.Resources.list.Sum(r => r.amount * r.info.unitCost); double cost = 0.0;
  for (int i = 0; i < part.Resources.list.Count; ++i)
  {
  PartResource cachePartResource = part.Resources.list[i];
  cost = cost + (cachePartResource.amount * cachePartResource.info.unitCost);
  }
  return cost;
} }
   
/// <summary> /// <summary>
/// Gets the cost of the part's contained resources, inverted. /// Gets the cost of the part's contained resources, inverted.
/// </summary> /// </summary>
public static double GetResourceCostInverted(this Part part) public static double GetResourceCostInverted(this Part part)
{ {
return part.Resources.list.Sum(r => (r.maxAmount - r.amount) * r.info.unitCost); double sum = 0;
  for (int i = 0; i < part.Resources.list.Count; i++)
  {
  PartResource r = part.Resources.list[i];
  sum += (r.maxAmount - r.amount) * r.info.unitCost;
  }
  return sum;
} }
   
/// <summary> /// <summary>
/// Gets the cost of the part's maximum contained resources. /// Gets the cost of the part's maximum contained resources.
/// </summary> /// </summary>
public static double GetResourceCostMax(this Part part) public static double GetResourceCostMax(this Part part)
{ {
return part.Resources.list.Sum(r => r.maxAmount * r.info.unitCost); double cost = 0.0;
  for (int i = 0; i < part.Resources.list.Count; ++i)
  {
  PartResource cachePartResource = part.Resources.list[i];
  cost = cost + (cachePartResource.maxAmount * cachePartResource.info.unitCost);
  }
  return cost;
} }
   
/// <summary> /// <summary>
/// Gets the current specific impulse for the engine. /// Gets the current specific impulse for the engine.
/// </summary> /// </summary>
  /* not used
public static double GetSpecificImpulse(this Part part, float atmosphere) public static double GetSpecificImpulse(this Part part, float atmosphere)
{ {
if (part.HasModule<ModuleEngines>()) PartModule cachePartModule = GetModule<ModuleEngines>(part);
{ if (cachePartModule != null)
return part.GetModuleEngines().atmosphereCurve.Evaluate(atmosphere); {
} return (cachePartModule as ModuleEngines).atmosphereCurve.Evaluate(atmosphere);
if (part.HasModule<MultiModeEngine>()) }
{  
return part.GetModuleMultiModeEngine().atmosphereCurve.Evaluate(atmosphere); cachePartModule = GetModuleMultiModeEngine(part) ?? GetModule<ModuleEnginesFX>(part);
} if (cachePartModule != null)
if (part.HasModule<ModuleEnginesFX>()) {
{ return (cachePartModule as ModuleEnginesFX).atmosphereCurve.Evaluate(atmosphere);
return part.GetModuleEnginesFx().atmosphereCurve.Evaluate(atmosphere); }
}  
  return 0.0;
return 0d; }
} */
   
/// <summary> /// <summary>
/// Gets the total mass of the part including resources. /// Gets the total mass of the part including resources.
/// </summary> /// </summary>
public static double GetWetMass(this Part part) public static double GetWetMass(this Part part)
{ {
return (part.physicalSignificance == Part.PhysicalSignificance.FULL) ? part.mass + part.GetResourceMass() : part.GetResourceMass(); return (part.physicalSignificance == Part.PhysicalSignificance.FULL) ? part.mass + part.GetResourceMass() : part.GetResourceMass();
} }
   
/// <summary> /// <summary>
/// Gets whether the part contains a PartModule. /// Gets whether the part contains a PartModule.
/// </summary> /// </summary>
public static bool HasModule<T>(this Part part) where T : PartModule public static bool HasModule<T>(this Part part) where T : PartModule
{ {
return part.Modules.OfType<T>().Any(); for (int i = 0; i < part.Modules.Count; i++)
  {
  if (part.Modules[i] is T)
  return true;
  }
  return false;
} }
   
/// <summary> /// <summary>
/// Gets whether the part contains a PartModule conforming to the supplied predicate. /// Gets whether the part contains a PartModule conforming to the supplied predicate.
/// </summary> /// </summary>
public static bool HasModule<T>(this Part part, Func<T, bool> predicate) where T : PartModule public static bool HasModule<T>(this Part part, Func<T, bool> predicate) where T : PartModule
{ {
return part.Modules.OfType<T>().Any(predicate); for (int i = 0; i < part.Modules.Count; i++)
  {
  PartModule pm = part.Modules[i];
  if (pm is T && predicate(pm as T))
  return true;
  }
  return false;
} }
   
/// <summary> /// <summary>
/// Gets whether the part contains a PartModule. /// Gets whether the part contains a PartModule.
/// </summary> /// </summary>
public static bool HasModule(this Part part, string className) public static bool HasModule(this Part part, string className)
{ {
return part.Modules.Contains(className); return part.Modules.Contains(className);
} }
   
/// <summary> /// <summary>
/// Gets whether the part contains a PartModule. /// Gets whether the part contains a PartModule.
/// </summary> /// </summary>
public static bool HasModule(this Part part, int moduleId) public static bool HasModule(this Part part, int moduleId)
{ {
return part.Modules.Contains(moduleId); return part.Modules.Contains(moduleId);
} }
   
/// <summary> /// <summary>
/// Gets whether the part has a one shot animation. /// Gets whether the part has a one shot animation.
/// </summary> /// </summary>
public static bool HasOneShotAnimation(this Part part) public static bool HasOneShotAnimation(this Part part)
{ {
return part.HasModule<ModuleAnimateGeneric>() && part.GetModule<ModuleAnimateGeneric>().isOneShot; PartModule cachePartModule = GetModule<ModuleAnimateGeneric>(part);
  return cachePartModule != null && (cachePartModule as ModuleAnimateGeneric).isOneShot;
} }
   
/// <summary> /// <summary>
/// Gets whether the part is a command module. /// Gets whether the part is a command module.
/// </summary> /// </summary>
public static bool IsCommandModule(this Part part) public static bool IsCommandModule(this Part part)
{ {
return part.HasModule<ModuleCommand>(); return HasModule<ModuleCommand>(part);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is decoupled in a specified stage. /// Gets whether the part is decoupled in a specified stage.
/// </summary> /// </summary>
public static bool IsDecoupledInStage(this Part part, int stage) public static bool IsDecoupledInStage(this Part part, int stage)
{ {
if ((part.IsDecoupler() || part.IsLaunchClamp()) && part.inverseStage == stage) if ((IsDecoupler(part) || IsLaunchClamp(part)) && part.inverseStage == stage)
{ {
return true; return true;
} }
if (part.parent == null) if (part.parent == null)
{ {
return false; return false;
} }
return part.parent.IsDecoupledInStage(stage); return IsDecoupledInStage(part.parent, stage);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is a decoupler. /// Gets whether the part is a decoupler.
/// </summary> /// </summary>
public static bool IsDecoupler(this Part part) public static bool IsDecoupler(this Part part)
{ {
return part.HasModule<ModuleDecouple>() || part.HasModule<ModuleAnchoredDecoupler>(); return HasModule<ModuleDecouple>(part) || HasModule<ModuleAnchoredDecoupler>(part);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is an active engine. /// Gets whether the part is an active engine.
/// </summary> /// </summary>
public static bool IsEngine(this Part part) public static bool IsEngine(this Part part)
{ {
return part.HasModule<ModuleEngines>() || part.HasModule<ModuleEnginesFX>(); return HasModule<ModuleEngines>(part);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is a fuel line. /// Gets whether the part is a fuel line.
/// </summary> /// </summary>
public static bool IsFuelLine(this Part part) public static bool IsFuelLine(this Part part)
{ {
return (part is FuelLine); return HasModule<CModuleFuelLine>(part);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is a generator. /// Gets whether the part is a generator.
/// </summary> /// </summary>
public static bool IsGenerator(this Part part) public static bool IsGenerator(this Part part)
{ {
return part.HasModule<ModuleGenerator>(); return HasModule<ModuleGenerator>(part);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is a launch clamp. /// Gets whether the part is a launch clamp.
/// </summary> /// </summary>
public static bool IsLaunchClamp(this Part part) public static bool IsLaunchClamp(this Part part)
{ {
return part.HasModule<LaunchClamp>(); return HasModule<LaunchClamp>(part);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is a parachute. /// Gets whether the part is a parachute.
/// </summary> /// </summary>
public static bool IsParachute(this Part part) public static bool IsParachute(this Part part)
{ {
return part.HasModule<ModuleParachute>(); return HasModule<ModuleParachute>(part);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is considered a primary part on the vessel. /// Gets whether the part is considered a primary part on the vessel.
/// </summary> /// </summary>
public static bool IsPrimary(this Part part, List<Part> partsList, PartModule module) public static bool IsPrimary(this Part part, List<Part> partsList, PartModule module)
{ {
foreach (var vesselPart in partsList) for (int i = 0; i < partsList.Count; i++)
{ {
  var vesselPart = partsList[i];
if (!vesselPart.HasModule(module.ClassID)) if (!vesselPart.HasModule(module.ClassID))
{ {
continue; continue;
} }
   
if (vesselPart == part) if (vesselPart == part)
{ {
return true; return true;
} }
break; break;
} }
   
return false; return false;
} }
   
public static bool IsRcsModule(this Part part) public static bool IsRcsModule(this Part part)
{ {
return part.HasModule<ModuleRCS>(); return HasModule<ModuleRCS>(part);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is a sepratron. /// Gets whether the part is a sepratron.
/// </summary> /// </summary>
public static bool IsSepratron(this Part part) public static bool IsSepratron(this Part part)
{ {
return (part.IsSolidRocket() && part.ActivatesEvenIfDisconnected && part.IsDecoupledInStage(part.inverseStage)); return IsSolidRocket(part) && part.ActivatesEvenIfDisconnected && IsDecoupledInStage(part, part.inverseStage);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is a deployable solar panel. /// Gets whether the part is a deployable solar panel.
/// </summary> /// </summary>
public static bool IsSolarPanel(this Part part) public static bool IsSolarPanel(this Part part)
{ {
return part.HasModule<ModuleDeployableSolarPanel>(); return HasModule<ModuleDeployableSolarPanel>(part);
} }
   
/// <summary> /// <summary>
/// Gets whether the part is a solid rocket motor. /// Gets whether the part is a solid rocket motor.
/// </summary> /// </summary>
public static bool IsSolidRocket(this Part part) public static bool IsSolidRocket(this Part part)
{ {
return part.HasModule<ModuleEngines>() && part.GetModuleEngines().throttleLocked; return (part.HasModule<ModuleEngines>() && part.GetModuleEngines().throttleLocked);
} }
   
#endregion  
   
#region Nested Type: ProtoModuleDecoupler  
   
public class ProtoModuleDecoupler public class ProtoModuleDecoupler
{ {
#region Fields  
   
private readonly PartModule module; private readonly PartModule module;
   
#endregion  
   
#region Constructors  
   
public ProtoModuleDecoupler(PartModule module) public ProtoModuleDecoupler(PartModule module)
{ {
this.module = module; this.module = module;
   
if (this.module is ModuleDecouple) if (this.module is ModuleDecouple)
{ {
this.SetModuleDecouple(); SetModuleDecouple();
} }
else if (this.module is ModuleAnchoredDecoupler) else if (this.module is ModuleAnchoredDecoupler)
{ {
this.SetModuleAnchoredDecoupler(); SetModuleAnchoredDecoupler();
} }
} }
   
#endregion  
   
#region Properties  
   
public double EjectionForce { get; private set; } public double EjectionForce { get; private set; }
public bool IsOmniDecoupler { get; private set; } public bool IsOmniDecoupler { get; private set; }
   
#endregion  
   
#region Methods: private  
   
private void SetModuleAnchoredDecoupler() private void SetModuleAnchoredDecoupler()
{ {
var decoupler = this.module as ModuleAnchoredDecoupler; ModuleAnchoredDecoupler decoupler = module as ModuleAnchoredDecoupler;
if (decoupler == null) if (decoupler == null)
{ {
return; return;
} }
   
this.EjectionForce = decoupler.ejectionForce; EjectionForce = decoupler.ejectionForce;
} }
   
private void SetModuleDecouple() private void SetModuleDecouple()
{ {
var decoupler = this.module as ModuleDecouple; ModuleDecouple decoupler = module as ModuleDecouple;
if (decoupler == null) if (decoupler == null)
{ {
return; return;
} }
   
this.EjectionForce = decoupler.ejectionForce; EjectionForce = decoupler.ejectionForce;
this.IsOmniDecoupler = decoupler.isOmniDecoupler; IsOmniDecoupler = decoupler.isOmniDecoupler;
} }
  }
#endregion  
} // This needs updating to handle multi-mode engines and engines with multiple ModuleEngines correctly.
  // It currently just shows the stats of the currently active module for multi-mode engines and just
#endregion // the first ModuleEngines for engines with multiple modules.
  // It should really show all the modes for multi-mode engines as separate sections.
#region Nested Type: ProtoModuleEngine // For other engines with multiple ModuleEngines it should combine the separate modules into a single set of data
  // The constructor should be changed to take the Part itself. It can be called if HasModule<ModuleEngines>() is true.
public class ProtoModuleEngine public class ProtoModuleEngine
{ {
#region Fields  
   
private readonly PartModule module; private readonly PartModule module;
   
#endregion  
   
#region Constructors  
   
public ProtoModuleEngine(PartModule module) public ProtoModuleEngine(PartModule module)
{ {
this.module = module; this.module = module;
   
if (module is ModuleEngines) if (module is ModuleEngines)
{ {
this.SetModuleEngines(); SetModuleEngines();
} }
else if (module is ModuleEnginesFX) }
{  
this.SetModuleEnginesFx();  
}  
}  
   
#endregion  
   
#region Properties  
   
public double MaximumThrust { get; private set; } public double MaximumThrust { get; private set; }
public double MinimumThrust { get; private set; } public double MinimumThrust { get; private set; }
public List<Propellant> Propellants { get; private set; } public List<Propellant> Propellants { get; private set; }
   
#endregion  
   
#region Methods: public  
   
public float GetSpecificImpulse(float atmosphere) public float GetSpecificImpulse(float atmosphere)
{ {
if (this.module is ModuleEngines) if (module is ModuleEngines)
{ {
return (this.module as ModuleEngines).atmosphereCurve.Evaluate(atmosphere); return (module as ModuleEngines).atmosphereCurve.Evaluate(atmosphere);
}  
if (this.module is ModuleEnginesFX)  
{  
return (this.module as ModuleEnginesFX).atmosphereCurve.Evaluate(atmosphere);  
} }
return 0.0f; return 0.0f;
} }
   
#endregion  
   
#region Methods: private  
   
private void SetModuleEngines() private void SetModuleEngines()
{ {
var engine = this.module as ModuleEngines; ModuleEngines engine = module as ModuleEngines;
if (engine == null) if (engine == null)
{ {
return; return;
} }
   
this.MaximumThrust = engine.maxThrust * (engine.thrustPercentage * 0.01); MaximumThrust = engine.maxThrust * (engine.thrustPercentage * 0.01);
this.MinimumThrust = engine.minThrust; MinimumThrust = engine.minThrust;
this.Propellants = engine.propellants; Propellants = engine.propellants;
} }
  }
private void SetModuleEnginesFx()  
{  
var engine = this.module as ModuleEnginesFX;  
if (engine == null)  
{  
return;  
}  
   
this.MaximumThrust = engine.maxThrust * (engine.thrustPercentage * 0.01);  
this.MinimumThrust = engine.minThrust;  
this.Propellants = engine.propellants;  
}  
   
#endregion  
}  
   
#endregion  
} }
} }
  //
  // Kerbal Engineer Redux
  //
  // Copyright (C) 2015 CYBUTEK
  //
  // This program is free software: you can redistribute it and/or modify
  // it under the terms of the GNU General Public License as published by
  // the Free Software Foundation, either version 3 of the License, or
  // (at your option) any later version.
  //
  // This program is distributed in the hope that it will be useful,
  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  // GNU General Public License for more details.
  //
  // You should have received a copy of the GNU General Public License
  // along with this program. If not, see <http://www.gnu.org/licenses/>.
  //
 
  namespace KerbalEngineer.Extensions
  {
  public static class StringExtensions
  {
  public static string ToLength(this string value, int length)
  {
  if (value != null && value.Length > length)
  {
  value = value.Substring(0, length) + "...";
  }
  return value;
  }
  }
  }
// //
// Kerbal Engineer Redux // Kerbal Engineer Redux
// //
// Copyright (C) 2014 CYBUTEK // Copyright (C) 2014 CYBUTEK
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
// //
   
#region Using Directives #region Using Directives
   
using System; using System;
   
using UnityEngine; using UnityEngine;
   
#endregion #endregion
   
namespace KerbalEngineer.Flight namespace KerbalEngineer.Flight
{ {
/// <summary> /// <summary>
/// Graphical controller for section interaction in the form of a menu system. /// Graphical controller for section interaction in the form of a menu system.
/// </summary> /// </summary>
[KSPAddon(KSPAddon.Startup.Flight, false)] [KSPAddon(KSPAddon.Startup.Flight, false)]
public class ActionMenu : MonoBehaviour public class ActionMenu : MonoBehaviour
{ {
#region Fields #region Fields
   
private ActionMenuGui actionMenuGui; private ActionMenuGui actionMenuGui;
private ApplicationLauncherButton button; private ApplicationLauncherButton button;
   
#endregion #endregion
   
#region Methods: protected #region Methods: protected
   
protected void Awake() protected void Awake()
{ {
try try
{ {
GameEvents.onGUIApplicationLauncherReady.Add(this.OnGuiAppLauncherReady); GameEvents.onGUIApplicationLauncherReady.Add(this.OnGuiAppLauncherReady);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
Logger.Log("ActionMenu was created."); Logger.Log("ActionMenu was created.");
} }
   
  protected void Start()
  {
  if (button == null)
  {
  OnGuiAppLauncherReady();
  }
  }
   
protected void OnDestroy() protected void OnDestroy()
{ {
try try
{ {
GameEvents.onGUIApplicationLauncherReady.Remove(this.OnGuiAppLauncherReady); GameEvents.onGUIApplicationLauncherReady.Remove(this.OnGuiAppLauncherReady);
GameEvents.onHideUI.Remove(this.OnHide); GameEvents.onHideUI.Remove(this.OnHide);
GameEvents.onShowUI.Remove(this.OnShow); GameEvents.onShowUI.Remove(this.OnShow);
ApplicationLauncher.Instance.RemoveModApplication(this.button); if (button != null)
  {
  ApplicationLauncher.Instance.RemoveModApplication(this.button);
  }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Exception(ex); Logger.Exception(ex);
} }
Logger.Log("ActionMenu was destroyed."); Logger.Log("ActionMenu was destroyed.");
} }
   
protected void Update() protected void Update()
{ {
try try
{ {
if (this.button == null) if (this.button == null)
{ {
return; return;
}