Merge remote-tracking branch 'cybutek/master'
Merge remote-tracking branch 'cybutek/master'

file:a/.gitattributes (deleted)
###############################################################################  
# Set default behavior to automatically normalize line endings.  
###############################################################################  
* text=auto  
 
###############################################################################  
# Set default behavior for command prompt diff.  
#  
# This is need for earlier builds of msysgit that does not have it on by  
# default for csharp files.  
# Note: This is only used by command line  
###############################################################################  
#*.cs diff=csharp  
 
###############################################################################  
# Set the merge driver for project and solution files  
#  
# Merging from the command prompt will add diff markers to the files if there  
# are conflicts (Merging from VS is not affected by the settings below, in VS  
# the diff markers are never inserted). Diff markers may cause the following  
# file extensions to fail to load in VS. An alternative would be to treat  
# these files as binary and thus will always conflict and require user  
# intervention with every merge. To do so, just uncomment the entries below  
###############################################################################  
#*.sln merge=binary  
#*.csproj merge=binary  
#*.vbproj merge=binary  
#*.vcxproj merge=binary  
#*.vcproj merge=binary  
#*.dbproj merge=binary  
#*.fsproj merge=binary  
#*.lsproj merge=binary  
#*.wixproj merge=binary  
#*.modelproj merge=binary  
#*.sqlproj merge=binary  
#*.wwaproj merge=binary  
 
###############################################################################  
# behavior for image files  
#  
# image files are treated as binary by default.  
###############################################################################  
#*.jpg binary  
#*.png binary  
#*.gif binary  
 
###############################################################################  
# diff behavior for common document formats  
#  
# Convert binary document formats to text before diffing them. This feature  
# is only available from the command line. Turn it on by uncommenting the  
# entries below.  
###############################################################################  
#*.doc diff=astextplain  
#*.DOC diff=astextplain  
#*.docx diff=astextplain  
#*.DOCX diff=astextplain  
#*.dot diff=astextplain  
#*.DOT diff=astextplain  
#*.pdf diff=astextplain  
#*.PDF diff=astextplain  
#*.rtf diff=astextplain  
#*.RTF diff=astextplain  
 
file:a/.gitignore (deleted)
# Build Folders (you can keep bin if you'd like, to store dlls and pdbs)  
[Bb]in/  
[Oo]bj/  
 
# mstest test results  
TestResults  
 
## Ignore Visual Studio temporary files, build results, and  
## files generated by popular Visual Studio add-ons.  
 
# User-specific files  
*.suo  
*.user  
*.sln.docstates  
 
# Build results  
[Dd]ebug/  
x64/  
*_i.c  
*_p.c  
*.ilk  
*.meta  
*.obj  
*.pch  
*.pdb  
*.pgc  
*.pgd  
*.rsp  
*.sbr  
*.tlb  
*.tli  
*.tlh  
*.tmp  
*.log  
*.vspscc  
*.vssscc  
.builds  
 
# Visual C++ cache files  
ipch/  
*.aps  
*.ncb  
*.opensdf  
*.sdf  
 
# Visual Studio profiler  
*.psess  
*.vsp  
*.vspx  
 
# Guidance Automation Toolkit  
*.gpState  
 
# ReSharper is a .NET coding add-in  
_ReSharper*  
 
# Mindbench SASS cache  
.sass-cache/  
 
# NCrunch  
*.ncrunch*  
.*crunch*.local.xml  
 
# Installshield output folder  
[Ee]xpress  
 
# DocProject is a documentation generator add-in  
DocProject/buildhelp/  
DocProject/Help/*.HxT  
DocProject/Help/*.HxC  
DocProject/Help/*.hhc  
DocProject/Help/*.hhk  
DocProject/Help/*.hhp  
DocProject/Help/Html2  
DocProject/Help/html  
 
# Click-Once directory  
publish  
 
# Publish Web Output  
*.Publish.xml  
 
# NuGet Packages Directory  
packages  
 
# Windows Azure Build Output  
csx  
*.build.csdef  
 
# Windows Store app package directory  
AppPackages/  
 
# Others  
sql  
TestResults  
[Tt]est[Rr]esult*  
*.Cache  
ClientBin  
[Ss]tyle[Cc]op.*  
~$*  
*.dbmdl  
Generated_Code #added for RIA/Silverlight projects  
 
# Backup & report files from converting an old project file to a newer  
# Visual Studio version. Backup files are not needed, because we have git ;-)  
_UpgradeReport_Files/  
Backup*/  
UpgradeLog*.XML  
 
# SQL Server files  
App_Data/*.mdf  
App_Data/*.ldf  
 
[Gg]ame/  
[Rr]elease/  
file:a/Assets/CurseLogo.png (deleted)
 Binary files a/Assets/CurseLogo.png and /dev/null differ
file:a/Assets/CurseLogo.psd (deleted)
 Binary files a/Assets/CurseLogo.psd and /dev/null differ
 Binary files a/Assets/DropDownBackground.psd and /dev/null differ
 Binary files a/Assets/ToolbarBackground.psd and /dev/null differ
file:a/Assets/ToolbarIcon.psd (deleted)
 Binary files a/Assets/ToolbarIcon.psd and /dev/null differ
file:b/AttachNodeSim.cs (new)
  //
  // Kerbal Engineer Redux
  //
  // Copyright (C) 2014 CYBUTEK
  //
  // This program is free software: you can redistribute it and/or modify
  // it under the terms of the GNU General Public License as published by
  // the Free Software Foundation, either version 3 of the License, or
  // (at your option) any later version.
  //
  // This program is distributed in the hope that it will be useful,
  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  // GNU General Public License for more details.
  //
  // You should have received a copy of the GNU General Public License
  // along with this program. If not, see <http://www.gnu.org/licenses/>.
  //
 
  #region Using Directives
 
  #endregion
 
  namespace KerbalEngineer.VesselSimulator
  {
  using System;
  using System.Text;
 
  internal class AttachNodeSim
  {
 
  private static readonly Pool<AttachNodeSim> pool = new Pool<AttachNodeSim>(Create, Reset);
 
  public PartSim attachedPartSim;
  public String id;
  public AttachNode.NodeType nodeType;
 
  private static AttachNodeSim Create()
  {
  return new AttachNodeSim();
  }
 
  public static AttachNodeSim New(PartSim partSim, String newId, AttachNode.NodeType newNodeType)
  {
  AttachNodeSim nodeSim = pool.Borrow();
 
  nodeSim.attachedPartSim = partSim;
  nodeSim.nodeType = newNodeType;
  nodeSim.id = newId;
 
  return nodeSim;
  }
 
  static private void Reset(AttachNodeSim attachNodeSim)
  {
  attachNodeSim.attachedPartSim = null;
  }
 
 
  public void Release()
  {
  pool.Release(this);
  }
 
  public void DumpToBuffer(StringBuilder buffer)
  {
  if (attachedPartSim == null)
  {
  buffer.Append("<staged>:<n>");
  }
  else
  {
  buffer.Append(attachedPartSim.name);
  buffer.Append(":");
  buffer.Append(attachedPartSim.partId);
  }
  buffer.Append("#");
  buffer.Append(nodeType);
  buffer.Append(":");
  buffer.Append(id);
  }
  }
  }
file:b/Averager.cs (new)
  //
  // Kerbal Engineer Redux
  //
  // Copyright (C) 2014 CYBUTEK
  //
  // This program is free software: you can redistribute it and/or modify
  // it under the terms of the GNU General Public License as published by
  // the Free Software Foundation, either version 3 of the License, or
  // (at your option) any later version.
  //
  // This program is distributed in the hope that it will be useful,
  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  // GNU General Public License for more details.
  //
  // You should have received a copy of the GNU General Public License
  // along with this program. If not, see <http://www.gnu.org/licenses/>.
  //
 
  using System;
 
  namespace KerbalEngineer
  {
  public class VectorAverager
  {
  private Vector3d sum = Vector3d.zero;
  private uint count = 0;
 
  public void Add(Vector3d v) {
  sum += v;
  count += 1;
  }
 
  public Vector3d Get() {
  if (count > 0) {
  return sum / count;
  } else {
  return Vector3d.zero;
  }
  }
 
  public void Reset()
  {
  sum = Vector3d.zero;
  count = 0;
  }
  }
 
  public class WeightedVectorAverager
  {
  private Vector3d sum = Vector3d.zero;
  private double totalweight = 0;
 
  public void Add(Vector3d v, double weight) {
  sum += v * weight;
  totalweight += weight;
  }
 
  public Vector3d Get() {
  if (totalweight > 0) {
  return sum / totalweight;
  } else {
  return Vector3d.zero;
  }
  }
 
  public double GetTotalWeight() {
  return totalweight;
  }
 
  public void Reset()
  {
  sum = Vector3d.zero;
  totalweight = 0.0;
  }
  }
  }
 
 
  //
  // Kerbal Engineer Redux
  //
  // Copyright (C) 2014 CYBUTEK
  //
  // This program is free software: you can redistribute it and/or modify
  // it under the terms of the GNU General Public License as published by
  // the Free Software Foundation, either version 3 of the License, or
  // (at your option) any later version.
  //
  // This program is distributed in the hope that it will be useful,
  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  // GNU General Public License for more details.
  //
  // You should have received a copy of the GNU General Public License
  // along with this program. If not, see <http://www.gnu.org/licenses/>.
  //
 
  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
  * the best way of getting the celestial body information dynamically using PSystemManager.
  *
  */
 
  public static class CelestialBodies
  {
  static CelestialBodies()
  {
  try
  {
  SystemBody = new BodyInfo(PSystemManager.Instance.localBodies.Find(b => b.referenceBody == null || b.referenceBody == b));
  String homeCBName = Planetarium.fetch.Home.bodyName;
  if (!SetSelectedBody(homeCBName))
  {
  SelectedBody = SystemBody;
  SelectedBody.SetSelected(true);
  }
  }
  catch (Exception ex)
  {
  Logger.Exception(ex);
  }
  }
 
  public static BodyInfo SelectedBody { get; private set; }
  public static BodyInfo SystemBody { get; private set; }
 
  /// <summary>
  /// Gets a body given a supplied body name.
  /// </summary>
  public static BodyInfo GetBodyInfo(string bodyName)
  {
  try
  {
  return SystemBody.GetBodyInfo(bodyName);
  }
  catch (Exception ex)
  {
  Logger.Exception(ex);
  }
  return null;
  }
 
  /// <summary>
  /// Sets the selected body to one matching the supplied body name. Returns true if successful.
  /// </summary>
  public static bool SetSelectedBody(string bodyName)
  {
  try
  {
  BodyInfo body = GetBodyInfo(bodyName);
  if (body != null)
  {
  if (SelectedBody != null)
  {
  SelectedBody.SetSelected(false);
  }
  SelectedBody = body;
  SelectedBody.SetSelected(true);
  return true;
  }
  }
  catch (Exception ex)
  {
  Logger.Exception(ex);
  }
  return false;
  }
 
  public class BodyInfo
  {
  public BodyInfo(CelestialBody body, BodyInfo parent = null)
  {
  try
  {
  // Set the body information.
  CelestialBody = body;
  Name = body.bodyName;
  Gravity = 9.81 * body.GeeASL;
  Parent = parent;
 
  // Set orbiting bodies information.
  Children = new List<BodyInfo>();
  foreach (CelestialBody orbitingBody in body.orbitingBodies)
  {
  Children.Add(new BodyInfo(orbitingBody, this));
  }
 
  SelectedDepth = 0;
  }
  catch (Exception ex)
  {
  Logger.Exception(ex);
  }
  }
 
  public CelestialBody CelestialBody { get; private set; }
  public List<BodyInfo> Children { get; private set; }
  public double Gravity { get; private set; }
  public string Name { get; private set; }
  public BodyInfo Parent { get; private set; }
  public bool Selected { get; private set; }
  public int SelectedDepth { get; private set; }
 
  public BodyInfo GetBodyInfo(string bodyName)
  {
  try
  {
  // This is the searched body.
  if (String.Equals(Name, bodyName, StringComparison.CurrentCultureIgnoreCase))
  {
  return this;
  }
 
  // Check to see if any of this bodies children are the searched body.
  foreach (BodyInfo child in Children)
  {
  BodyInfo body = child.GetBodyInfo(bodyName);
  if (body != null)
  {
  return body;
  }
  }
  }
  catch (Exception ex)
  {
  Logger.Exception(ex);
  }
 
  // A body with the specified name was not found.
  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)
  {
  Selected = state;
  SelectedDepth = depth;
  if (Parent != null)
  {
  Parent.SetSelected(state, depth + 1);
  }
  }
 
  public override string ToString()
  {
  string log = "\n" + Name +
  "\n\tGravity: " + Gravity +
  "\n\tSelected: " + Selected;
 
  return Children.Aggregate(log, (current, child) => current + "\n" + child);
  }
  }
  }
  }
file:a/Documents/CHANGES.txt (deleted)
Changed: Thermal flux is now correctly indicated in kilowatts.  
 
1.0.19.4, 12-02-16  
Fixed: Only 'STAGE_STACK_FLOW' and 'STAGE_STACK_FLOW_BALANCE' resources include surface mounted parts as fuel targets.  
Fixed: Fairing mass being doubled in the VAB (removed workaround for a KSP bug which has been fixed).  
 
1.0.19.3, 09-02-16  
Fixed: Fuel cross-feed from surface attached parts.  
 
1.0.19.2, 19-11-15  
Rebuild for KSP 1.0.5.1028 silent update.  
 
1.0.19.1, 09-11-15  
Added: Key binding editor accessible under 'Settings' on the Build Engineer.  
Added: Added current vessel name readout. (antplant)  
Added: 'Relative Radial Velocity' and 'Time To Rendezvous' readouts. (itwtx)  
Added: Readout help strings. (harryyoung)  
Changed: The 'Torque' value in the editor is now precise to two decimal places.  
Changed: Time formatting reference (Kerbin/Earth) is now based on the in-game setting.  
Changed: Eccentric Anomaly, Mean Anomaly and Mean Anomaly At Epoc now display in degrees rather than radians.  
Fixed: Optimised time formatting. (itwtx)  
Fixed: TimeToAtmosphere checks that the Apoapsis is outside atmosphere. (Kerbas-ad-astra)  
Fixed: Issue with stage priority flow. Caused Rapier calculations to fail if LF and O are drawn from different tanks. (Padishar)  
Fixed: Issue with angle to prograde/retrograde calculations on highly inclined orbits.  
Fixed: Editor input locks not being reset when a scene change is forced (e.g. via Kerbal Construction Time).  
Fixed: Roll axis readout now shows the correct sign.  
Removed: Time Formatter readout as it's not required anymore.  
 
1.0.18.0  
Added: Orbital readouts - "Speed at Periapsis" and "Speed at Apoapsis". (Padishar)  
Added: Manoeuvre readouts - "Post-burn Apoapsis" and "Post-burn Periapsis". (Padishar)  
Added: Orbital readout - "Time to Atmosphere".  
Fixed: Synched the minimum simulation time sliders and stopped them from snapping back after 999ms. (saybur)  
Fixed: Added workaround for the bug in Vessel.horizontalSrfSpeed (Padishar)  
Fixed: Physically insignificant part mass was not being correctly cascaded down through multiple parent parts.  
Fixed: Intake air demand calculation not working.  
Fixed: Some build engineer settings labels do not scale with UI size.  
 
1.0.17.0  
Added: 'Mach Number' readout under the 'Surface' category and included it on the default surface HUD.  
Added: Stock sections in the Flight Engineer can now become HUDs.  
Added 'Thermal' readouts category including:  
Internal Flux  
Convection Flux  
Radiation Flux  
Critical Part Name  
Critical Part Temperature  
Critical Part Skin Temperature  
Critical Part Thermal Percentage of Max Temperature  
Hottest Part Name  
Hottest Part Temperature  
Hottest Part Skin Temperature  
Coldest Part Name  
Coldest Part Temperature  
Coldest Part Skin Temperature  
 
Changed: Mach on the Build Engineer now accurate to 2 decimal places.  
Changed: Max mach in the Build Engineer defaults to 1.00 even when no jet engines are present.  
Changed: Increased eccentricity readout to 5 decimal places.  
Changed: Implemented Sarbian's object pooling.  
Changed: The default selected body is now assigned via 'Planitarium.Home'.  
Changed: HUDs to clamp fully inside the screen instead of allowing them to run off the edge by a certain amount.  
Fixed: Physically insignificant part mass is now associated with the parent part.  
Fixed: Longitude and Latitude readouts now use a KER formatter instead of Squad's incorrect implementation.  
Fixed: Possible null reference in the Rendezvous Processor.  
Fixed: Fairing mass issues introduced with regards to simulation changes.  
Fixed: Use of per-propellant fuel flow mode override.  
Fixed: Burn times calculated for jet engines.  
Fixed: Thrust issues introduced with Sarbian's simulation alterations.  
Fixed: Issue where HUDs positioned close to the top/bottom of the screen could be pushed out of position.  
 
1.0.16.6, 02-05-15  
Fixed: Separately staged fairing mass jettisons are now calculated in the editor.  
 
1.0.16.5, 02-05-2015  
Fixed: Delta-V not being correctly calculated.  
Changed: Editor locking now uses the InputLockManager.  
 
1.0.16.4, 01-05-2015  
Fixed: Physically insignificant part mass is now accounted for.  
Changed: Module mass accounted for as it now makes its way onto the launch pad (e.g. fairings).  
 
Various optimisations:  
Object pooling.  
Removed LINQ expressions.  
Converted foreach to for loops.  
 
1.0.16.3, 27-04-2015  
Fixed issue with the toolbar icons not being created.  
Removed superfluous 'm/s' on the mach slider in the build engineer.  
 
1.0.16.2, 27-04-2015  
Changed the atmospheric slider on the build engineer to default to 0km when changing bodies.  
 
1.0.16.1, 26-04-2015, KSP Build #828  
Merged Sarbian's mach adjustments.  
Fixed bugs relating to thrust and atmosphere/velocity curves.  
Changed the atmospheric slider on the Build Engineer to work based on altitude.  
Changed the atmospheric slider to clamp to the maximum altitude for the selected body.  
Changed the velocity slider to clamp to the maximum usable mach value for the current vessel.  
 
1.0.16.0, 25-04-2015, KSP Build #821  
Fixed errors relating to KSP 1.0 update.  
Fixed fuel simulation to account for new thrust system.  
Fixed atmospheric engines to use the new velocity curve.  
Fixed atmospheric readouts to work with the new atmospheric model.  
 
1.0.15.2, 13-02-2015  
Padishar's Fixes:  
Fixed: Calculation of per-stage resource mass.  
 
1.0.15.1, 13-02-2015  
Rebuild  
 
1.0.15.0, 08-02-2015  
Padishar's Fixes:  
Added: Support KIDS ISP thrust correction.  
Fixed: Log spam for stage priority mode.  
Fixed: Locked tanks preventing simulation from staging.  
Fixed: No flow and all vessel modes to respect flow states.  
 
1.0.14.1, 28-12-2014  
Fixed: Missing texture on the ER-7500 model.  
 
1.0.14.0, 28-12-2014  
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: New readout to the surface category:  
- Vertical Acceleration  
- Horizontal Acceleration  
 
Changed: Atmospheric efficiency readout now shows as a percentage.  
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.  
 
1.0.9.2, 07-10-2014  
Updated for KSP v0.25.0  
Changed: Prettyfied Latitude and Longitude readouts.  
Changed: ModuleLandingGear now uses the physical significance flag.  
Changed: Updated MiniAVC to 1.0.2.4.  
 
1.0.9.1, 17-09-2014  
Fixed: Part size bug caused by TweakScale's cost calculator.  
 
1.0.9.0, 15-09-2014  
Added: Build Engineer now also implements the '\' backslash show/hide shortcut.  
Added: New readouts to the vessel category:  
- Current Stage DeltaV  
- Surface Thrust to Weight Ratio  
 
Added: New editor overlay system.  
- Sleeker design.  
- Hover over part information options:  
- Name only  
- Middle click to show  
- Always show  
- Slide out overlay displays:  
- Vessel information  
- Resources list  
 
Fixed: Cost calculation now works with mods implementing IPartCostModifier.  
 
1.0.8.1, 06-09-2014  
Fixed: Bug which caused rendezvous readouts to freeze the game or show all zeros.  
 
1.0.8.0, 06-09-2014  
Added: New readouts to the vessel category:  
- Intake Air (Usage)  
 
Added: New readouts to the rendezvous category:  
- Relative Velocity  
- Relative Speed  
 
Fixed: An issue where deltaV would not be calculated whilst flying.  
Fixed: NullRef whilst loading the in flight Action Menu.  
 
1.0.7.1, 02-09-2014  
Changed: Reversed Intake Air readout from 'S/D' to 'D/S' for easier reading.  
Changed: Increased Intake Air readout precision to 4 decimal places.  
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: Thrust now scales with velocity for atmospheric engines. (Padishar's fix)  
 
1.0.7.0, 01-09-2014  
Added: Part count information to the Build Engineer.  
Added: Reset button to the G-Force readout.  
Added: Preset system to the Flight Engineer.  
Added: New stock presets:  
- Orbital  
- Surface  
- Vessel  
- Rendezvous  
 
Added: New readouts to the orbital category:  
- True Anomaly  
- Eccentric Anomaly  
- Mean Anomaly  
- Argument of Periapsis  
- Angle to Prograde  
- Angle to Retrograde  
 
Added: New readouts to the vessel category:  
- Intake Air (Demand)  
- Intake Air (Supply)  
- Intake Air (Supply/Demand)  
 
Added: New readouts to the rendezvous category.  
- Semi-major Axis  
- Semi-minor Axis  
 
Added: Time formatter which can show time as referenced by any celestial body.  
Added: New readouts to the miscellaneous category:  
- Time Reference Adjuster  
 
Changed: Moved Sim Delay readout into the Miscellaneous category.  
Changed: Updated MiniAVC to v1.0.2.3.  
Fixed: Issues with large value wrap around in the Flight Engineer.  
Fixed: Bug in the phase angle calculation.  
 
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 relative ascending/descending nodes in the rendezvous display.  
Added: Overlay tooltip information delay adjustment slider to the Build Engineer settings.  
Added: Ability to rename the stock displays in the Flight Engineer.  
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: 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).  
 
1.0.5.0, 13-08-2014  
Added: Acceleration readout to the Vessel category (current / maximum).  
Added: Category library system for the Flight Engineer readouts.  
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).  
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: 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.  
 
1.0.4.0, 12-08-2014  
Added: Better stock toolbar support in the flight engineer.  
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: Extended logging system has been improved.  
Changed: Swapped out integrated MiniAVC in place of the official bundle version.  
Changed: Increased general distance precision to 1 decimal place.  
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.  
 
1.0.3.0, 30-07-2014  
Added: Integrated KSP-AVC support with MiniAVC.  
Added: Setting to change the simulation delay in the Build Engineer.  
Added: Setting to enable and disable the build overlay system.  
Added: Burn time to Delta-V readouts.  
Added: Atmospheric readouts fully support FAR.  
Added: Atmospheric readouts are disabled with NEAR.  
Changed: Force formatting inversely scales decimal precision with value.  
Fixed: Flickering in VAB and Vessel display.  
Fixed: Bug saving the GUI display size.  
 
1.0.2.0, 27-07-2014  
Added: Separator readout module under Misc in the Flight Engineer.  
Added: Adjustable GUI display size.  
Added: Display size can be adjusted in the Build Engineer settings.  
Added: Misc readout for adjusting display size in the Flight Engineer.  
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: Engines that have a minimum thrust are now calculated properly. (Thanks to nosscire.)  
Fixed: Compact collapse mode is now saved in the Build Engineer.  
 
1.0.1.0, 26-07-2014  
Added: Part-less Flight Engineer.  
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: Biome, Impact Biome and Slope readouts.  
Added: Extra logging and exception handling.  
Added: The original Engineer Chip part.  
Added: "Show Engineer" toggle on the Flight Engineer toolbar.  
Changed: Extended logging system now also writes to the standard KSP logs.  
Changed: Extended logging saves next to the .dll file.  
Changed: ER7500 part has no physical significance.  
Fixed: ActionMenu and DisplayStack destruction bug.  
 
1.0.0.1, 24-07-2014  
Added: Stock toolbar support in the Flight Engineer.  
Changed: Orbital Period has higher precision.  
Fixed: Various NullRefs in editor window and overlay.  
 
1.0.0.0, 24-07-2014  
Initial release for public testing.  
 
file:a/Documents/LICENCE.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>.  
 
file:a/Documents/README.htm (deleted)
<!DOCTYPE html>  
<html>  
<head>  
<meta charset='UTF-8'>  
<title>Kerbal Engineer Redux - README</title>  
<link href='http://fonts.googleapis.com/css?family=PT+Sans:400,700' rel='stylesheet' type='text/css'>  
<script>  
function resizeIframe(obj) {  
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';  
}  
</script>  
<style>  
* {  
margin: 0; padding: 0;  
box-sizing: border-box; moz-box-sizing: border-box; webkit-box-sizing: border-box;  
}  
 
html, body {  
height: 100%;  
font-family: 'PT Sans', Verdana, Geneva, sans-serif;  
}  
 
a {  
text-decoration: none;  
font-weight: 700;  
color: inherit;  
}  
 
a:hover {  
text-decoration: underline;  
}  
 
h3 {  
display: block;  
line-height: 1.5em;  
font-size: 1.1em;  
font-weight: 700;  
}  
 
p {  
display: block;  
margin: 0 0.5em;  
text-align: justify;  
}  
 
ul {  
display: block;  
margin-left: 1.5em;  
list-style-type: square;  
}  
 
li {  
margin-top: 0.5em;  
text-align: justify;  
}  
 
iframe {  
width: 100%;  
border: none;  
}  
 
header {  
display: block;  
padding: 25px;  
text-align: center;  
font-size: 3rem;  
font-weight: 700;  
letter-spacing: 0.2em;  
color: white;  
background-color: black;  
}  
 
section {  
display: block;  
margin: 10px;  
padding: 0.5em 1em;  
line-height: 1.5em;  
background-color: #DDD;  
}  
 
footer {  
display: block;  
text-align: center;  
line-height: 50px;  
font-size: 0.8rem;  
letter-spacing: 0.2em;  
color: white;  
background-color: black;  
}  
 
.nested_list > li {  
margin-top: 1em;  
}  
 
.nested_list > li:first-child {  
margin-top: 0.5em;  
}  
 
#root {  
clear: both;  
min-height: 100%;  
height: auto !important;  
height: 100%;  
margin-bottom: -50px;  
}  
 
#root > #root_footer {  
height: 50px;  
}  
 
#footer {  
clear: both;  
position: relative;  
height: 50px;  
}  
</style>  
</head>  
<body>  
<div id='root'>  
<header>Kerbal Engineer Redux v1.0</header>  
 
<section>  
<h3>Developers</h3>  
<p>  
CYBUTEK: Primary Development<br>  
Padishar: Simulation Logic  
</p>  
</section>  
 
<section>  
<h3>Honourable Mentions</h3>  
<p>  
Mic_E: Impact Readouts  
</p>  
</section>  
 
<section>  
<h3>Goto the Forum Thread</h3>  
<p>  
<a href="http://forum.kerbalspaceprogram.com/threads/18230" target='_blank'>http://forum.kerbalspaceprogram.com/threads/18230</a>  
</p>  
</section>  
 
<section>  
<h3>KSP-AVC Ready</h3>  
<p>  
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>.  
</p>  
</section>  
 
<section>  
<h3>Contains MiniAVC</h3>  
<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>.  
</p>  
</section>  
 
<section>  
<h3>Description</h3>  
<p>  
This plugin will allow you to view important statistics about your ship on the fly, whilst constructing and in flight.  
</p>  
</section>  
 
<section>  
<h3>Installation</h3>  
<ul>  
<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>  
</ul>  
</section>  
 
<section>  
<h3>Change Log</h3>  
<iframe src='CHANGES.txt' onload="this.style.height = this.contentWindow.document.body.scrollHeight + 'px'"></iframe>  
</section>  
 
<section>  
<h3>Software License</h3>  
<p>  
Licensed under the <a href='LICENCE.txt'>GNU General Public License v3</a>.  
</p>  
</section>  
 
<div id='root_footer'></div>  
</div>  
 
<footer id='footer'>  
README design by <a href='http://ksp.cybutek.net' target='_blank'><strong>CYBUTEK</strong></a> (GPLv3)  
</footer>  
</body>  
</html>  
file:b/EngineSim.cs (new)
  //
  // Kerbal Engineer Redux
  //
  // Copyright (C) 2014 CYBUTEK
  //
  // This program is free software: you can redistribute it and/or modify
  // it under the terms of the GNU General Public License as published by
  // the Free Software Foundation, either version 3 of the License, or
  // (at your option) any later version.
  //
  // This program is distributed in the hope that it will be useful,
  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  // GNU General Public License for more details.
  //
  // You should have received a copy of the GNU General Public License
  // along with this program. If not, see <http://www.gnu.org/licenses/>.
  //
 
  namespace KerbalEngineer.VesselSimulator
  {
  using System;
  using System.Collections.Generic;
  using System.Text;
  using Editor;
  using Helpers;
  using UnityEngine;
 
  public class EngineSim
  {
  private static readonly Pool<EngineSim> pool = new Pool<EngineSim>(Create, Reset);
 
  private readonly ResourceContainer resourceConsumptions = new ResourceContainer();
  private readonly ResourceContainer resourceFlowModes = new ResourceContainer();
 
  public double actualThrust = 0;
  public bool isActive = false;
  public double isp = 0;
  public PartSim partSim;
  public List<AppliedForce> appliedForces = new List<AppliedForce>();
  public float maxMach;
  public bool isFlamedOut;
 
  public double thrust = 0;
 
  // Add thrust vector to account for directional losses
  public Vector3 thrustVec;
 
  private static EngineSim Create()
  {
  return new EngineSim();
  }
 
  private static void Reset(EngineSim engineSim)
  {
  engineSim.resourceConsumptions.Reset();
  engineSim.resourceFlowModes.Reset();
  engineSim.partSim = null;
  engineSim.actualThrust = 0;
  engineSim.isActive = false;
  engineSim.isp = 0;
  for (int i = 0; i < engineSim.appliedForces.Count; i++)
  {
  engineSim.appliedForces[i].Release();
  }
  engineSim.appliedForces.Clear();
  engineSim.thrust = 0;
  engineSim.maxMach = 0f;
  engineSim.isFlamedOut = false;
  }
 
  public void Release()
  {
  pool.Release(this);
  }
 
  public static EngineSim New(PartSim theEngine,
  ModuleEngines engineMod,
  double atmosphere,
  float machNumber,
  bool vectoredThrust,
  bool fullThrust,
  LogMsg log)
  {
  float maxFuelFlow = engineMod.maxFuelFlow;
  float minFuelFlow = engineMod.minFuelFlow;
  float thrustPercentage = engineMod.thrustPercentage;
  List<Transform> thrustTransforms = engineMod.thrustTransforms;
  List<float> thrustTransformMultipliers = engineMod.thrustTransformMultipliers;
  Vector3 vecThrust = CalculateThrustVector(vectoredThrust ? thrustTransforms : null,
  vectoredThrust ? thrustTransformMultipliers : null,
  log);
  FloatCurve atmosphereCurve = engineMod.atmosphereCurve;
  bool atmChangeFlow = engineMod.atmChangeFlow;
  FloatCurve atmCurve = engineMod.useAtmCurve ? engineMod.atmCurve : null;
  FloatCurve velCurve = engineMod.useVelCurve ? engineMod.velCurve : null;
  float currentThrottle = engineMod.currentThrottle;
  float IspG = engineMod.g;
  bool throttleLocked = engineMod.throttleLocked || fullThrust;
  List<Propellant> propellants = engineMod.propellants;
  bool active = engineMod.isOperational;
  float resultingThrust = engineMod.resultingThrust;
  bool isFlamedOut = engineMod.flameout;
 
  EngineSim engineSim = pool.Borrow();
 
  engineSim.isp = 0.0;
  engineSim.maxMach = 0.0f;
  engineSim.actualThrust = 0.0;
  engineSim.partSim = theEngine;
  engineSim.isActive = active;
  engineSim.thrustVec = vecThrust;
  engineSim.isFlamedOut = isFlamedOut;
  engineSim.resourceConsumptions.Reset();
  engineSim.resourceFlowModes.Reset();
  engineSim.appliedForces.Clear();
 
  double flowRate = 0.0;
  if (engineSim.partSim.hasVessel)
  {
  if (log != null) log.buf.AppendLine("hasVessel is true");
 
  float flowModifier = GetFlowModifier(atmChangeFlow, atmCurve, engineSim.partSim.part.atmDensity, velCurve, machNumber, ref engineSim.maxMach);
  engineSim.isp = atmosphereCurve.Evaluate((float)atmosphere);
  engineSim.thrust = GetThrust(Mathf.Lerp(minFuelFlow, maxFuelFlow, GetThrustPercent(thrustPercentage)) * flowModifier, engineSim.isp);
  engineSim.actualThrust = engineSim.isActive ? resultingThrust : 0.0;
  if (log != null)
  {
  log.buf.AppendFormat("flowMod = {0:g6}\n", flowModifier);
  log.buf.AppendFormat("isp = {0:g6}\n", engineSim.isp);
  log.buf.AppendFormat("thrust = {0:g6}\n", engineSim.thrust);
  log.buf.AppendFormat("actual = {0:g6}\n", engineSim.actualThrust);
  }
 
  if (throttleLocked)
  {
  if (log != null) log.buf.AppendLine("throttleLocked is true, using thrust for flowRate");
  flowRate = GetFlowRate(engineSim.thrust, engineSim.isp);
  }
  else
  {
  if (currentThrottle > 0.0f && engineSim.partSim.isLanded == false)
  {
  // TODO: This bit doesn't work for RF engines
  if (log != null) log.buf.AppendLine("throttled up and not landed, using actualThrust for flowRate");
  flowRate = GetFlowRate(engineSim.actualThrust, engineSim.isp);
  }
  else
  {
  if (log != null) log.buf.AppendLine("throttled down or landed, using thrust for flowRate");
  flowRate = GetFlowRate(engineSim.thrust, engineSim.isp);
  }
  }
  }
  else
  {
  if (log != null) log.buf.AppendLine("hasVessel is false");
  float flowModifier = GetFlowModifier(atmChangeFlow, atmCurve, CelestialBodies.SelectedBody.GetDensity(BuildAdvanced.Altitude), velCurve, machNumber, ref engineSim.maxMach);
  engineSim.isp = atmosphereCurve.Evaluate((float)atmosphere);
  engineSim.thrust = GetThrust(Mathf.Lerp(minFuelFlow, maxFuelFlow, GetThrustPercent(thrustPercentage)) * flowModifier, engineSim.isp);
  engineSim.actualThrust = 0d;
  if (log != null)
  {
  log.buf.AppendFormat("flowMod = {0:g6}\n", flowModifier);
  log.buf.AppendFormat("isp = {0:g6}\n", engineSim.isp);
  log.buf.AppendFormat("thrust = {0:g6}\n", engineSim.thrust);
  log.buf.AppendFormat("actual = {0:g6}\n", engineSim.actualThrust);
  }
 
  if (log != null) log.buf.AppendLine("no vessel, using thrust for flowRate");
  flowRate = GetFlowRate(engineSim.thrust, engineSim.isp);
  }
 
  if (log != null) log.buf.AppendFormat("flowRate = {0:g6}\n", flowRate);
 
  float flowMass = 0f;
  for (int i = 0; i < propellants.Count; ++i)
  {
  Propellant propellant = propellants[i];
  if (!propellant.ignoreForIsp)
  flowMass += propellant.ratio * ResourceContainer.GetResourceDensity(propellant.id);
  }
 
  if (log != null) log.buf.AppendFormat("flowMass = {0:g6}\n", flowMass);
 
  for (int i = 0; i < propellants.Count; ++i)
  {
  Propellant propellant = propellants[i];
 
  if (propellant.name == "ElectricCharge" || propellant.name == "IntakeAir")
  {
  continue;
  }
 
  double consumptionRate = propellant.ratio * flowRate / flowMass;
  if (log != null) log.buf.AppendFormat(
  "Add consumption({0}, {1}:{2:d}) = {3:g6}\n",
  ResourceContainer.GetResourceName(propellant.id),
  theEngine.name,
  theEngine.partId,
  consumptionRate);
  engineSim.resourceConsumptions.Add(propellant.id, consumptionRate);
  engineSim.resourceFlowModes.Add(propellant.id, (double)propellant.GetFlowMode());
  }
 
  for (int i = 0; i < thrustTransforms.Count; i++)
  {
  Transform thrustTransform = thrustTransforms[i];
  Vector3d direction = thrustTransform.forward.normalized;
  Vector3d position = thrustTransform.position;
 
  AppliedForce appliedForce = AppliedForce.New(direction * engineSim.thrust * thrustTransformMultipliers[i], position);
  engineSim.appliedForces.Add(appliedForce);
  }
 
  return engineSim;
  }
 
  private static Vector3 CalculateThrustVector(List<Transform> thrustTransforms, List<float> thrustTransformMultipliers, LogMsg log)
  {
  if (thrustTransforms == null)
  {
  return Vector3.forward;
  }
 
  Vector3 thrustvec = Vector3.zero;
  for (int i = 0; i < thrustTransforms.Count; ++i)
  {
  Transform trans = thrustTransforms[i];
 
  if (log != null) log.buf.AppendFormat("Transform = ({0:g6}, {1:g6}, {2:g6}) length = {3:g6}\n", trans.forward.x, trans.forward.y, trans.forward.z, trans.forward.magnitude);
 
  thrustvec -= (trans.forward * thrustTransformMultipliers[i]);
  }
 
  if (log != null) log.buf.AppendFormat("ThrustVec = ({0:g6}, {1:g6}, {2:g6}) length = {3:g6}\n", thrustvec.x, thrustvec.y, thrustvec.z, thrustvec.magnitude);
 
  thrustvec.Normalize();
 
  if (log != null) log.buf.AppendFormat("ThrustVecN = ({0:g6}, {1:g6}, {2:g6}) length = {3:g6}\n", thrustvec.x, thrustvec.y, thrustvec.z, thrustvec.magnitude);
 
  return thrustvec;
  }
 
  public ResourceContainer ResourceConsumptions
  {
  get
  {
  return resourceConsumptions;
  }
  }
 
  public static double GetExhaustVelocity(double isp)
  {
  return isp * Units.GRAVITY;
  }
 
  public static float GetFlowModifier(bool atmChangeFlow, FloatCurve atmCurve, double atmDensity, FloatCurve velCurve, float machNumber, ref float maxMach)
  {
  float flowModifier = 1.0f;
  if (atmChangeFlow)
  {
  flowModifier = (float)(atmDensity / 1.225);
  if (atmCurve != null)
  {
  flowModifier = atmCurve.Evaluate(flowModifier);
  }
  }
  if (velCurve != null)
  {
  flowModifier = flowModifier * velCurve.Evaluate(machNumber);
  maxMach = velCurve.maxTime;
  }
  if (flowModifier < float.Epsilon)
  {
  flowModifier = float.Epsilon;
  }
  return flowModifier;
  }
 
  public static double GetFlowRate(double thrust, double isp)
  {
  return thrust / GetExhaustVelocity(isp);
  }
 
  public static float GetThrottlePercent(float currentThrottle, float thrustPercentage)
  {
  return currentThrottle * GetThrustPercent(thrustPercentage);
  }
 
  public static double GetThrust(double flowRate, double isp)
  {
  return flowRate * GetExhaustVelocity(isp);
  }
 
  public static float GetThrustPercent(float thrustPercentage)
  {
  return thrustPercentage * 0.01f;
  }
 
  public void DumpEngineToBuffer(StringBuilder buffer, String prefix)
  {
  buffer.Append(prefix);
  buffer.AppendFormat("[thrust = {0:g6}, actual = {1:g6}, isp = {2:g6}\n", thrust, actualThrust, isp);
  }
 
  // A dictionary to hold a set of parts for each resource
  Dictionary<int, HashSet<PartSim>> sourcePartSets = new Dictionary<int, HashSet<PartSim>>();
 
  Dictionary<int, HashSet<PartSim>> stagePartSets = new Dictionary<int, HashSet<PartSim>>();
 
  HashSet<PartSim> visited = new HashSet<PartSim>();
 
  public void DumpSourcePartSets(String msg)
  {
  MonoBehaviour.print("DumpSourcePartSets " + msg);
  foreach (int type in sourcePartSets.Keys)
  {
  MonoBehaviour.print("SourcePartSet for " + ResourceContainer.GetResourceName(type));
  HashSet<PartSim> sourcePartSet = sourcePartSets[type];
  if (sourcePartSet.Count > 0)
  {
  foreach (PartSim partSim in sourcePartSet)
  {
  MonoBehaviour.print("Part " + partSim.name + ":" + partSim.partId);
  }
  }
  else
  {
  MonoBehaviour.print("No parts");
  }
  }
  }
 
  public bool SetResourceDrains(List<PartSim> allParts, List<PartSim> allFuelLines, HashSet<PartSim> drainingParts)
  {
  LogMsg log = null;
  //DumpSourcePartSets("before clear");
  foreach (HashSet<PartSim> sourcePartSet in sourcePartSets.Values)
  {
  sourcePartSet.Clear();
  }
  //DumpSourcePartSets("after clear");
 
  for (int index = 0; index < this.resourceConsumptions.Types.Count; index++)
  {
  int type = this.resourceConsumptions.Types[index];
 
  HashSet<PartSim> sourcePartSet;
  if (!sourcePartSets.TryGetValue(type, out sourcePartSet))
  {
  sourcePartSet = new HashSet<PartSim>();
  sourcePartSets.Add(type, sourcePartSet);
  }
 
  switch ((ResourceFlowMode)this.resourceFlowModes[type])
  {
  case ResourceFlowMode.NO_FLOW:
  if (partSim.resources[type] > SimManager.RESOURCE_MIN && partSim.resourceFlowStates[type] != 0)
  {
  //sourcePartSet = new HashSet<PartSim>();
  //MonoBehaviour.print("SetResourceDrains(" + name + ":" + partId + ") setting sources to just this");
  sourcePartSet.Add(partSim);
  }
  break;
 
  case ResourceFlowMode.ALL_VESSEL:
  case ResourceFlowMode.ALL_VESSEL_BALANCE:
  for (int i = 0; i < allParts.Count; i++)
  {
  PartSim aPartSim = allParts[i];
  if (aPartSim.resources[type] > SimManager.RESOURCE_MIN && aPartSim.resourceFlowStates[type] != 0)
  {
  sourcePartSet.Add(aPartSim);
  }
  }
  break;
 
  case ResourceFlowMode.STAGE_PRIORITY_FLOW:
  case ResourceFlowMode.STAGE_PRIORITY_FLOW_BALANCE:
 
  foreach (HashSet<PartSim> stagePartSet in stagePartSets.Values)
  {
  stagePartSet.Clear();
  }
  var maxStage = -1;
 
  //Logger.Log(type);
  for (int i = 0; i < allParts.Count; i++)
  {
  var aPartSim = allParts[i];
  if (aPartSim.resources[type] <= SimManager.RESOURCE_MIN || aPartSim.resourceFlowStates[type] == 0)
  {
  continue;
  }
 
  int stage = aPartSim.DecouplerCount();
  if (stage > maxStage)
  {
  maxStage = stage;
  }
 
  HashSet<PartSim> tempPartSet;
  if (!stagePartSets.TryGetValue(stage, out tempPartSet))
  {
  tempPartSet = new HashSet<PartSim>();
  stagePartSets.Add(stage, tempPartSet);
  }
  tempPartSet.Add(aPartSim);
  }
 
  for (int j = maxStage; j >= 0; j--)
  {
  HashSet<PartSim> stagePartSet;
  if (stagePartSets.TryGetValue(j, out stagePartSet) && stagePartSet.Count > 0)
  {
  // We have to copy the contents of the set here rather than copying the set reference or
  // bad things (tm) happen
  foreach (PartSim aPartSim in stagePartSet)
  {
  sourcePartSet.Add(aPartSim);
  }
  break;
  }
  }
  break;
 
  case ResourceFlowMode.STACK_PRIORITY_SEARCH:
  visited.Clear();
 
  if (SimManager.logOutput)
  {
  log = new LogMsg();
  log.buf.AppendLine("Find " + ResourceContainer.GetResourceName(type) + " sources for " + partSim.name + ":" + partSim.partId);
  }
 
  // TODO: check fuel flow as 'PhysicsGlobals.Stack_PriUsesSurf' changed to false to subdue error
  partSim.GetSourceSet(type, false, allParts, visited, sourcePartSet, log, "");
  if (SimManager.logOutput && log != null)
  {
  MonoBehaviour.print(log.buf);
  }
  break;
 
  case ResourceFlowMode.STAGE_STACK_FLOW:
  case ResourceFlowMode.STAGE_STACK_FLOW_BALANCE:
  visited.Clear();
 
  if (SimManager.logOutput)
  {
  log = new LogMsg();
  log.buf.AppendLine("Find " + ResourceContainer.GetResourceName(type) + " sources for " + partSim.name + ":" + partSim.partId);
  }
  partSim.GetSourceSet(type, true, allParts, visited, sourcePartSet, log, "");
  if (SimManager.logOutput && log != null)
  {
  MonoBehaviour.print(log.buf);
  }
  break;
 
  default:
  MonoBehaviour.print("SetResourceDrains(" + partSim.name + ":" + partSim.partId + ") Unexpected flow type for " + ResourceContainer.GetResourceName(type) + ")");
  break;
  }
 
  if (SimManager.logOutput)
  {
  if (sourcePartSet.Count > 0)
  {
  log = new LogMsg();
  log.buf.AppendLine("Source parts for " + ResourceContainer.GetResourceName(type) + ":");
  foreach (PartSim partSim in sourcePartSet)
  {
  log.buf.AppendLine(partSim.name + ":" + partSim.partId);
  }
  MonoBehaviour.print(log.buf);
  }
  }
 
  //DumpSourcePartSets("after " + ResourceContainer.GetResourceName(type));
  }
 
  // If we don't have sources for all the needed resources then return false without setting up any drains
  for (int i = 0; i < this.resourceConsumptions.Types.Count; i++)
  {
  int type = this.resourceConsumptions.Types[i];
  HashSet<PartSim> sourcePartSet;
  if (!sourcePartSets.TryGetValue(type, out sourcePartSet) || sourcePartSet.Count == 0)
  {
  if (SimManager.logOutput)
  {
  MonoBehaviour.print("No source of " + ResourceContainer.GetResourceName(type));
  }
 
  isActive = false;
  return false;
  }
  }
 
  // Now we set the drains on the members of the sets and update the draining parts set
  for (int i = 0; i < this.resourceConsumptions.Types.Count; i++)
  {
  int type = this.resourceConsumptions.Types[i];
  HashSet<PartSim> sourcePartSet = sourcePartSets[type];
  // Loop through the members of the set
  double amount = resourceConsumptions[type] / sourcePartSet.Count;
  foreach (PartSim partSim in sourcePartSet)
  {
  if (SimManager.logOutput)
  {
  MonoBehaviour.print(
  "Adding drain of " + amount + " " + ResourceContainer.GetResourceName(type) + " to " + partSim.name + ":" +
  partSim.partId);
  }
 
  partSim.resourceDrains.Add(type, amount);
  drainingParts.Add(partSim);
  }
  }
  return true;
  }
  }
  }
  //
  // Kerbal Engineer Redux
  //
  // Copyright (C) 2014 CYBUTEK
  //
  // This program is free software: you can redistribute it and/or modify
  // it under the terms of the GNU General Public License as published by
  // the Free Software Foundation, either version 3 of the License, or
  // (at your option) any later version.
  //
  // This program is distributed in the hope that it will be useful,
  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  // GNU General Public License for more details.
  //
  // You should have received a copy of the GNU General Public License
  // along with this program. If not, see <http://www.gnu.org/licenses/>.
  //
 
  using System;
  using System.Collections.Generic;
  using KerbalEngineer.VesselSimulator;
 
  namespace KerbalEngineer
  {
  // a (force, application point) tuple
  public class AppliedForce
  {
  private static readonly Pool<AppliedForce> pool = new Pool<AppliedForce>(Create, Reset);
 
  public Vector3d vector;
  public Vector3d applicationPoint;
 
  static private AppliedForce Create()
  {
  return new AppliedForce();
  }
 
  static private void Reset(AppliedForce appliedForce) { }
 
  static public AppliedForce New(Vector3d vector, Vector3d applicationPoint)
  {
  AppliedForce force = pool.Borrow();
  force.vector = vector;
  force.applicationPoint = applicationPoint;
  return force;
  }
 
  public void Release()
  {
  pool.Release(this);
  }
 
 
  }
 
  // This class was mostly adapted from FARCenterQuery, part of FAR, by ferram4, GPLv3
  // https://github.com/ferram4/Ferram-Aerospace-Research/blob/master/FerramAerospaceResearch/FARCenterQuery.cs
  // Also see https://en.wikipedia.org/wiki/Resultant_force
 
  // It accumulates forces and their points of applications, and provides methods for
  // calculating the effective torque at any position, as well as the minimum-torque net force application point.
  //
  // The latter is a non-trivial issue; there is a 1-dimensional line of physically-equivalent solutions parallel
  // to the resulting force vector; the solution closest to the weighted average of force positions is chosen.
  // In the case of non-parallel forces, there usually is an infinite number of such lines, all of which have
  // some amount of residual torque. The line with the least amount of residual torque is chosen.
  public class ForceAccumulator
  {
  // Total force.
  private Vector3d totalForce = Vector3d.zero;
  // Torque needed to compensate if force were applied at origin.
  private Vector3d totalZeroOriginTorque = Vector3d.zero;
 
  // Weighted average of force application points.
  private WeightedVectorAverager avgApplicationPoint = new WeightedVectorAverager();
 
  // Feed an force to the accumulator.
  public void AddForce(Vector3d applicationPoint, Vector3d force)
  {
  totalForce += force;
  totalZeroOriginTorque += Vector3d.Cross(applicationPoint, force);
  avgApplicationPoint.Add(applicationPoint, force.magnitude);
  }
 
  public Vector3d GetAverageForceApplicationPoint() {
  return avgApplicationPoint.Get();
  }
 
  public void AddForce(AppliedForce force) {
  AddForce(force.applicationPoint, force.vector);
  }
 
  // Residual torque for given force application point.
  public Vector3d TorqueAt(Vector3d origin)
  {
  return totalZeroOriginTorque - Vector3d.Cross(origin, totalForce);
  }
 
  // Total force vector.
  public Vector3d GetTotalForce()
  {
  return totalForce;
  }
 
  // Returns the minimum-residual-torque force application point that is closest to origin.
  // Note that TorqueAt(GetMinTorquePos()) is always parallel to totalForce.
  public Vector3d GetMinTorqueForceApplicationPoint(Vector3d origin)
  {
  double fmag = totalForce.sqrMagnitude;
  if (fmag <= 0) {
  return origin;
  }
 
  return origin + Vector3d.Cross(totalForce, TorqueAt(origin)) / fmag;
  }
 
  public Vector3d GetMinTorqueForceApplicationPoint()
  {
  return GetMinTorqueForceApplicationPoint(avgApplicationPoint.Get());
  }
 
  public void Reset()
  {
  totalForce = Vector3d.zero;
  totalZeroOriginTorque = Vector3d.zero;
  avgApplicationPoint.Reset();
  }
  }
  }
file:a/KerbalEngineer.sln (deleted)
  
Microsoft Visual Studio Solution File, Format Version 12.00  
# Visual Studio 2013  
VisualStudioVersion = 12.0.30110.0  
MinimumVisualStudioVersion = 10.0.40219.1  
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KerbalEngineer", "KerbalEngineer\KerbalEngineer.csproj", "{39806613-E0B7-46E0-89A6-A569EC538CBB}"  
EndProject  
Global  
GlobalSection(SolutionConfigurationPlatforms) = preSolution  
Debug|Any CPU = Debug|Any CPU  
Release|Any CPU = Release|Any CPU  
EndGlobalSection  
GlobalSection(ProjectConfigurationPlatforms) = postSolution  
{39806613-E0B7-46E0-89A6-A569EC538CBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU  
{39806613-E0B7-46E0-89A6-A569EC538CBB}.Debug|Any CPU.Build.0 = Debug|Any CPU  
{39806613-E0B7-46E0-89A6-A569EC538CBB}.Release|Any CPU.ActiveCfg = Release|Any CPU  
{39806613-E0B7-46E0-89A6-A569EC538CBB}.Release|Any CPU.Build.0 = Release|Any CPU  
EndGlobalSection  
GlobalSection(SolutionProperties) = preSolution  
HideSolutionNode = FALSE  
EndGlobalSection  
EndGlobal  
 
//  
// Kerbal Engineer Redux  
//  
// Copyright (C) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
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  
* the best way of getting the celestial body information dynamically using PSystemManager.  
*  
*/  
 
public static class CelestialBodies  
{  
static CelestialBodies()  
{  
try  
{  
SystemBody = new BodyInfo(PSystemManager.Instance.localBodies.Find(b => b.referenceBody == null || b.referenceBody == b));  
String homeCBName = Planetarium.fetch.Home.bodyName;  
if (!SetSelectedBody(homeCBName))  
{  
SelectedBody = SystemBody;  
SelectedBody.SetSelected(true);  
}  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
public static BodyInfo SelectedBody { get; private set; }  
public static BodyInfo SystemBody { get; private set; }  
 
/// <summary>  
/// Gets a body given a supplied body name.  
/// </summary>  
public static BodyInfo GetBodyInfo(string bodyName)  
{  
try  
{  
return SystemBody.GetBodyInfo(bodyName);  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
return null;  
}  
 
/// <summary>  
/// Sets the selected body to one matching the supplied body name. Returns true if successful.  
/// </summary>  
public static bool SetSelectedBody(string bodyName)  
{  
try  
{  
BodyInfo body = GetBodyInfo(bodyName);  
if (body != null)  
{  
if (SelectedBody != null)  
{  
SelectedBody.SetSelected(false);  
}  
SelectedBody = body;  
SelectedBody.SetSelected(true);  
return true;  
}  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
return false;  
}  
 
public class BodyInfo  
{  
public BodyInfo(CelestialBody body, BodyInfo parent = null)  
{  
try  
{  
// Set the body information.  
CelestialBody = body;  
Name = body.bodyName;  
Gravity = 9.81 * body.GeeASL;  
Parent = parent;  
 
// Set orbiting bodies information.  
Children = new List<BodyInfo>();  
foreach (CelestialBody orbitingBody in body.orbitingBodies)  
{  
Children.Add(new BodyInfo(orbitingBody, this));  
}  
 
SelectedDepth = 0;  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
public CelestialBody CelestialBody { get; private set; }  
public List<BodyInfo> Children { get; private set; }  
public double Gravity { get; private set; }  
public string Name { get; private set; }  
public BodyInfo Parent { get; private set; }  
public bool Selected { get; private set; }  
public int SelectedDepth { get; private set; }  
 
public BodyInfo GetBodyInfo(string bodyName)  
{  
try  
{  
// This is the searched body.  
if (String.Equals(Name, bodyName, StringComparison.CurrentCultureIgnoreCase))  
{  
return this;  
}  
 
// Check to see if any of this bodies children are the searched body.  
foreach (BodyInfo child in Children)  
{  
BodyInfo body = child.GetBodyInfo(bodyName);  
if (body != null)  
{  
return body;  
}  
}  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
 
// A body with the specified name was not found.  
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)  
{  
Selected = state;  
SelectedDepth = depth;  
if (Parent != null)  
{  
Parent.SetSelected(state, depth + 1);  
}  
}  
 
public override string ToString()  
{  
string log = "\n" + Name +  
"\n\tGravity: " + Gravity +  
"\n\tSelected: " + Selected;  
 
return Children.Aggregate(log, (current, child) => current + "\n" + child);  
}  
}  
}  
}  
//  
// Kerbal Engineer Redux  
//  
// Copyright (C) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
#region Using Directives  
 
using System;  
using System.Collections.Generic;  
 
using KerbalEngineer.Control.Panels;  
 
using UnityEngine;  
 
#endregion  
 
namespace KerbalEngineer.Control  
{  
[KSPAddon(KSPAddon.Startup.Instantly, false)]  
public class ControlCentre : MonoBehaviour  
{  
#region Fields  
 
private static readonly List<IControlPanel> panels = new List<IControlPanel>();  
 
private static GUIStyle button;  
private static ControlCentre instance;  
private static GUIStyle label;  
private static GUIStyle title;  
 
private Vector2 contentsScrollPosition;  
private GUIStyle panelSelectorStyle;  
private Rect position = new Rect(Screen.width, Screen.height, 900.0f, 500.0f);  
private IControlPanel selectedPanel;  
private bool shouldCentre = true;  
 
#endregion  
 
#region Properties  
 
public static GUIStyle Button  
{  
get  
{  
return button ?? (button = new GUIStyle(HighLogic.Skin.button)  
{  
normal =  
{  
textColor = Color.white  
},  
fixedHeight = 30.0f  
});  
}  
}  
 
public static bool Enabled  
{  
get { return instance.enabled; }  
set { instance.enabled = value; }  
}  
 
public static GUIStyle Label  
{  
get  
{  
return label ?? (label = new GUIStyle(HighLogic.Skin.label)  
{  
normal =  
{  
textColor = Color.white  
},  
fontStyle = FontStyle.Bold,  
fixedHeight = 30.0f,  
alignment = TextAnchor.MiddleLeft,  
stretchWidth = true,  
});  
}  
}  
 
public static List<IControlPanel> Panels  
{  
get { return panels; }  
}  
 
public static GUIStyle Title  
{  
get  
{  
return title ?? (title = new GUIStyle(HighLogic.Skin.label)  
{  
normal =  
{  
textColor = Color.white  
},  
fontSize = 26,  
fontStyle = FontStyle.Bold,  
alignment = TextAnchor.UpperCenter,  
stretchWidth = true,  
});  
}  
}  
 
#endregion  
 
#region Methods: protected  
 
protected void Awake()  
{  
try  
{  
if (instance == null)  
{  
DontDestroyOnLoad(this);  
instance = this;  
this.enabled = false;  
return;  
}  
Destroy(this);  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
protected void OnGUI()  
{  
try  
{  
GUI.skin = null;  
this.position = GUILayout.Window(this.GetInstanceID(), this.position, this.Window, "KERBAL ENGINEER REDUX " + EngineerGlobals.ASSEMBLY_VERSION + " - CONTROL CENTRE", HighLogic.Skin.window);  
this.CentreWindow();  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
protected void Start()  
{  
try  
{  
this.InitialiseStyles();  
LoadPanels();  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
#endregion  
 
#region Methods: private  
 
private static void LoadPanels()  
{  
panels.Add(new BuildEngineerPanel());  
panels.Add(new BuildOverlayPanel());  
}  
 
private void CentreWindow()  
{  
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.shouldCentre = false;  
}  
}  
 
private void DrawContents()  
{  
GUI.skin = HighLogic.Skin;  
this.contentsScrollPosition = GUILayout.BeginScrollView(this.contentsScrollPosition, false, true);  
GUI.skin = null;  
 
if (this.selectedPanel != null)  
{  
this.selectedPanel.Draw();  
}  
 
GUILayout.FlexibleSpace();  
GUILayout.EndScrollView();  
}  
 
private void DrawSelectors()  
{  
GUILayout.BeginVertical(HighLogic.Skin.box, GUILayout.Width(225.0f));  
foreach (var panel in panels)  
{  
if (GUILayout.Toggle(this.selectedPanel == panel, panel.Name, this.panelSelectorStyle))  
{  
this.selectedPanel = panel;  
}  
}  
GUILayout.FlexibleSpace();  
if (GUILayout.Button("CLOSE", Button))  
{  
this.enabled = false;  
}  
GUILayout.EndVertical();  
}  
 
private void InitialiseStyles()  
{  
this.panelSelectorStyle = new GUIStyle(Button)  
{  
fontSize = 16,  
fixedHeight = 40.0f  
};  
}  
 
private void Window(int windowId)  
{  
try  
{  
GUILayout.BeginHorizontal();  
this.DrawSelectors();  
this.DrawContents();  
GUILayout.EndHorizontal();  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
#endregion  
}  
}  
//  
// Kerbal Engineer Redux  
//  
// Copyright (C) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
namespace KerbalEngineer.Control  
{  
public interface IControlPanel  
{  
#region Properties  
 
string Name { get; }  
 
#endregion  
 
#region Methods: public  
 
void Draw();  
 
#endregion  
}  
}  
//  
// Kerbal Engineer Redux  
//  
// Copyright (C) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
namespace KerbalEngineer.Control.Panels  
{  
public class BuildEngineerPanel : IControlPanel  
{  
#region Properties  
 
public string Name  
{  
get { return "Build Engineer"; }  
}  
 
#endregion  
 
#region Methods: public  
 
public void Draw() { }  
 
#endregion  
}  
}  
//  
// Kerbal Engineer Redux  
//  
// Copyright (C) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
#region Using Directives  
 
using KerbalEngineer.Editor;  
 
using UnityEngine;  
 
#endregion  
 
namespace KerbalEngineer.Control.Panels  
{  
public class BuildOverlayPanel : IControlPanel  
{  
#region Properties  
 
public string Name  
{  
get { return "Build Overlay"; }  
}  
 
#endregion  
 
#region Methods: public  
 
public void Draw()  
{  
GUILayout.Label("Build Overlay", ControlCentre.Title);  
DrawPartInfo();  
GUILayout.Space(10.0f);  
DrawDisplays();  
}  
 
#endregion  
 
#region Methods: private  
 
private static void DrawPartInfo()  
{  
GUILayout.Label("Part Information (Hover Tooltips)", ControlCentre.Label);  
GUILayout.BeginHorizontal();  
BuildOverlayPartInfo.Visible = GUILayout.Toggle(BuildOverlayPartInfo.Visible, "Visible", ControlCentre.Button, GUILayout.Width(150.0f));  
if (BuildOverlayPartInfo.Visible)  
{  
BuildOverlayPartInfo.NamesOnly = GUILayout.Toggle(BuildOverlayPartInfo.NamesOnly, "Show Names Only", ControlCentre.Button, GUILayout.Width(150.0f));  
if (!BuildOverlayPartInfo.NamesOnly)  
{  
BuildOverlayPartInfo.ClickToOpen = GUILayout.Toggle(BuildOverlayPartInfo.ClickToOpen, "Click To Open", ControlCentre.Button, GUILayout.Width(150.0f));  
}  
}  
 
 
GUILayout.EndHorizontal();  
}  
 
private static void DrawDisplays()  
{  
GUILayout.Label("Informational Displays", ControlCentre.Label);  
GUILayout.BeginHorizontal();  
BuildOverlayVessel.Visible = GUILayout.Toggle(BuildOverlayVessel.Visible, "Vessel Details", ControlCentre.Button, GUILayout.Width(150.0f));  
BuildOverlayResources.Visible = GUILayout.Toggle(BuildOverlayResources.Visible, "Resources List", ControlCentre.Button, GUILayout.Width(150.0f));  
GUILayout.EndHorizontal();  
}  
 
#endregion  
}  
}  
//  
// 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.Editor  
{  
using System;  
using Extensions;  
using Flight;  
using Helpers;  
using KeyBinding;  
using Settings;  
using UIControls;  
using UnityEngine;  
using VesselSimulator;  
 
[KSPAddon(KSPAddon.Startup.EditorAny, false)]  
public class BuildAdvanced : MonoBehaviour  
{  
public static float Altitude;  
 
private static Rect compactModeRect = new Rect(0.0f, 5.0f, 0.0f, 20.0f);  
private static Stage stage;  
private static int stagesCount;  
private static int stagesLength;  
private static string title;  
 
private GUIStyle areaSettingStyle;  
private GUIStyle areaStyle;  
private float atmosphericMach;  
private GUIStyle bodiesButtonActiveStyle;  
private GUIStyle bodiesButtonStyle;  
private DropDown bodiesList;  
private Rect bodiesListPosition;  
private GUIStyle buttonStyle;  
private int compactCheck;  
private bool compactCollapseRight;  
private bool compactMode;  
private float compactRight;  
private bool hasChanged;  
private GUIStyle infoStyle;  
private bool isEditorLocked;  
private float maxMach;  
private int numberOfStages;  
private Rect position = new Rect(265.0f, 45.0f, 0, 0);  
private GUIStyle settingAtmoStyle;  
private GUIStyle settingStyle;  
private bool showAllStages;  
private bool showAtmosphericDetails;  
private bool showSettings;  
private Stage[] stages;  
private GUIStyle titleStyle;  
private bool visible = true;  
private GUIStyle windowStyle;  
 
/// <summary>  
/// Gets the current instance if started or returns null.  
/// </summary>  
public static BuildAdvanced Instance { get; private set; }  
 
/// <summary>  
/// Gets and sets whether to show in compact mode.  
/// </summary>  
public bool CompactMode  
{  
get  
{  
return compactMode;  
}  
set  
{  
compactMode = value;  
}  
}  
 
/// <summary>  
/// Gets and sets whether to show all stages.  
/// </summary>  
public bool ShowAllStages  
{  
get  
{  
return showAllStages;  
}  
set  
{  
showAllStages = value;  
}  
}  
 
/// <summary>  
/// Gets and sets whether to use atmospheric details.  
/// </summary>  
public bool ShowAtmosphericDetails  
{  
get  
{  
return showAtmosphericDetails;  
}  
set  
{  
showAtmosphericDetails = value;  
}  
}  
 
/// <summary>  
/// Gets and sets whether to show the settings display.  
/// </summary>  
public bool ShowSettings  
{  
get  
{  
return showSettings;  
}  
set  
{  
showSettings = value;  
}  
}  
 
/// <summary>  
/// Gets and sets whether the display is enabled.  
/// </summary>  
public bool Visible  
{  
get  
{  
return visible;  
}  
set  
{  
visible = value;  
}  
}  
 
protected void Awake()  
{  
try  
{  
Instance = this;  
bodiesList = gameObject.AddComponent<DropDown>();  
bodiesList.DrawCallback = DrawBodiesList;  
Load();  
 
SimManager.UpdateModSettings();  
SimManager.OnReady -= GetStageInfo;  
SimManager.OnReady += GetStageInfo;  
}  
catch (Exception ex)  
{  
Logger.Exception(ex, "BuildAdvanced.Awake()");  
}  
}  
 
/// <summary>  
/// Saves the settings when this object is destroyed.  
/// </summary>  
protected void OnDestroy()  
{  
Logger.Log("BuildAdvanced->OnDestroy");  
 
try  
{  
SettingHandler handler = new SettingHandler();  
handler.Set("visible", visible);  
handler.Set("windowPositionX", position.x);  
handler.Set("windowPositionY", position.y);  
handler.Set("compactMode", compactMode);  
handler.Set("compactCollapseRight", compactCollapseRight);  
handler.Set("showAllStages", showAllStages);  
handler.Set("showAtmosphericDetails", showAtmosphericDetails);  
handler.Set("showSettings", showSettings);  
handler.Set("selectedBodyName", CelestialBodies.SelectedBody.Name);  
handler.Save("BuildAdvanced.xml");  
GuiDisplaySize.OnSizeChanged -= OnSizeChanged;  
}  
catch (Exception ex)  
{  
Logger.Exception(ex, "BuildAdvanced.OnDestroy()");  
}  
 
EditorLock(false);  
}  
 
protected void OnGUI()  
{  
try  
{  
if (!visible || EditorLogic.fetch == null || EditorLogic.fetch.ship.parts.Count == 0 || EditorLogic.fetch.editorScreen != EditorScreen.Parts)  
{  
return;  
}  
 
if (stages == null)  
{  
return;  
}  
 
// Change the window title based on whether in compact mode or not.  
title = !compactMode ? "KERBAL ENGINEER REDUX " + EngineerGlobals.ASSEMBLY_VERSION : "K.E.R. " + EngineerGlobals.ASSEMBLY_VERSION;  
 
// Reset the window size when the staging or something else has changed.  
stagesLength = stages.Length;  
if (showAllStages)  
{  
stagesCount = stagesLength;  
}  
if (showAllStages == false)  
{  
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;  
position = GUILayout.Window(GetInstanceID(), position, Window, title, windowStyle).ClampToScreen();  
 
if (compactCheck > 0 && compactCollapseRight)  
{  
position.x = compactRight - position.width;  
compactCheck--;  
}  
else if (compactCheck > 0)  
{  
compactCheck = 0;  
}  
 
// Check editor lock to manage click-through.  
CheckEditorLock();  
}  
catch (Exception ex)  
{  
Logger.Exception(ex, "BuildAdvanced.OnGUI()");  
}  
}  
 
protected void Start()  
{  
try  
{  
InitialiseStyles();  
GuiDisplaySize.OnSizeChanged += OnSizeChanged;  
}  
catch (Exception ex)  
{  
Logger.Exception(ex, "BuildAdvanced.Start()");  
}  
}  
 
protected void Update()  
{  
try  
{  
if (Input.GetKeyDown(KeyBinder.EditorShowHide))  
{  
visible = !visible;  
if (!visible)  
{  
EditorLock(false);  
}  
}  
 
if (!visible || EditorLogic.fetch == null || EditorLogic.fetch.ship.parts.Count == 0)  
{  
bodiesList.enabled = false;  
return;  
}  
 
// Configure the simulation parameters based on the selected reference body.  
SimManager.Gravity = CelestialBodies.SelectedBody.Gravity;  
 
if (showAtmosphericDetails)  
{  
SimManager.Atmosphere = CelestialBodies.SelectedBody.GetAtmospheres(Altitude);  
}  
else  
{  
SimManager.Atmosphere = 0;  
}  
 
SimManager.Mach = atmosphericMach;  
 
SimManager.RequestSimulation();  
SimManager.TryStartSimulation();  
}  
catch (Exception ex)  
{  
Logger.Exception(ex, "BuildAdvanced.Update()");  
}  
}  
 
/// <summary>  
/// Checks whether the editor should be locked to stop click-through.  
/// </summary>  
private void CheckEditorLock()  
{  
if ((position.MouseIsOver() || bodiesList.Position.MouseIsOver()) && !isEditorLocked)  
{  
EditorLock(true);  
}  
else if (!position.MouseIsOver() && !bodiesList.Position.MouseIsOver() && isEditorLocked)  
{  
EditorLock(false);  
}  
}  
 
/// <summary>  
/// Draws the atmospheric settings.  
/// </summary>  
private void DrawAtmosphericDetails()  
{  
try  
{  
GUILayout.BeginHorizontal();  
GUILayout.BeginVertical();  
GUILayout.Label("Altitude: " + (Altitude * 0.001f).ToString("F1") + "km", settingAtmoStyle, GUILayout.Width(125.0f * GuiDisplaySize.Offset));  
GUI.skin = HighLogic.Skin;  
Altitude = GUILayout.HorizontalSlider(Altitude, 0.0f, (float)(CelestialBodies.SelectedBody.CelestialBody.atmosphereDepth));  
GUI.skin = null;  
GUILayout.EndVertical();  
 
GUILayout.Space(5.0f);  
 
GUILayout.BeginVertical();  
GUILayout.Label("Mach: " + atmosphericMach.ToString("F2"), settingAtmoStyle, GUILayout.Width(125.0f * GuiDisplaySize.Offset));  
GUI.skin = HighLogic.Skin;  
atmosphericMach = GUILayout.HorizontalSlider(Mathf.Clamp(atmosphericMach, 0.0f, maxMach), 0.0f, maxMach);  
GUI.skin = null;  
GUILayout.EndVertical();  
GUILayout.EndHorizontal();  
}  
catch (Exception ex)  
{  
Logger.Exception(ex, "BuildAdvanced.DrawAtmosphericDetails()");  
}  
}  
 
private void DrawBodiesList()  
{  
if (CelestialBodies.SystemBody == CelestialBodies.SelectedBody)  
{  
DrawBody(CelestialBodies.SystemBody);  
}  
else  
{  
foreach (CelestialBodies.BodyInfo body in CelestialBodies.SystemBody.Children)  
{  
DrawBody(body);  
}  
}  
}  
 
private void DrawBody(CelestialBodies.BodyInfo bodyInfo, int depth = 0)  
{  
GUILayout.BeginHorizontal();  
GUILayout.Space(20.0f * depth);  
if (GUILayout.Button(bodyInfo.Children.Count > 0 ? bodyInfo.Name + " [" + bodyInfo.Children.Count + "]" : bodyInfo.Name, bodyInfo.Selected && bodyInfo.SelectedDepth == 0 ? bodiesButtonActiveStyle : bodiesButtonStyle))  
{  
CelestialBodies.SetSelectedBody(bodyInfo.Name);  
Altitude = 0.0f;  
bodiesList.Resize = true;  
}  
GUILayout.EndHorizontal();  
 
if (bodyInfo.Selected)  
{  
for (int i = 0; i < bodyInfo.Children.Count; ++i)  
{  
DrawBody(bodyInfo.Children[i], depth + 1);  
}  
}  
}  
 
/// <summary>  
/// Draws the burn time column.  
/// </summary>  
private void DrawBurnTime()  
{  
GUILayout.BeginVertical(GUILayout.Width(75.0f * GuiDisplaySize.Offset));  
GUILayout.Label("BURN", titleStyle);  
for (int i = 0; i < stagesLength; ++i)  
{  
stage = stages[i];  
if (showAllStages || stage.deltaV > 0.0)  
{  
GUILayout.Label(TimeFormatter.ConvertToString(stage.time), infoStyle);  
}  
}  
GUILayout.EndVertical();  
}  
 
/// <summary>  
/// Draws the cost column.  
/// </summary>  
private void DrawCost()  
{  
GUILayout.BeginVertical(GUILayout.Width(110.0f * GuiDisplaySize.Offset));  
GUILayout.Label("COST", titleStyle);  
for (int i = 0; i < stagesLength; ++i)  
{  
stage = stages[i];  
if (showAllStages || stage.deltaV > 0.0)  
{  
GUILayout.Label(Units.Cost(stage.cost, stage.totalCost), infoStyle);  
}  
}  
GUILayout.EndVertical();  
}  
 
/// <summary>  
/// Draws the deltaV column.  
/// </summary>  
private void DrawDeltaV()  
{  
GUILayout.BeginVertical(GUILayout.Width(100.0f * GuiDisplaySize.Offset));  
GUILayout.Label("DELTA-V", titleStyle);  
for (int i = 0; i < stagesLength; ++i)  
{  
stage = stages[i];  
if (showAllStages || stage.deltaV > 0.0)  
{  
GUILayout.Label(stage.deltaV.ToString("N0") + " / " + stage.inverseTotalDeltaV.ToString("N0") + "m/s", infoStyle);  
}  
}  
GUILayout.EndVertical();  
}  
 
/// <summary>  
/// Draws the specific impluse column.  
/// </summary>  
private void DrawIsp()  
{  
GUILayout.BeginVertical(GUILayout.Width(75.0f * GuiDisplaySize.Offset));  
GUILayout.Label("ISP", titleStyle);  
for (int i = 0; i < stagesLength; ++i)  
{  
stage = stages[i];  
if (showAllStages || stage.deltaV > 0.0)  
{  
GUILayout.Label(stage.isp.ToString("F1") + "s", infoStyle);  
}  
}  
GUILayout.EndVertical();  
}  
 
/// <summary>  
/// Draws the mass column.  
/// </summary>  
private void DrawMass()  
{  
GUILayout.BeginVertical(GUILayout.Width(110.0f * GuiDisplaySize.Offset));  
GUILayout.Label("MASS", titleStyle);  
for (int i = 0; i < stagesLength; ++i)  
{  
stage = stages[i];  
if (showAllStages || stage.deltaV > 0.0)  
{  
GUILayout.Label(Units.ToMass(stage.mass, stage.totalMass), infoStyle);  
}  
}  
GUILayout.EndVertical();  
}  
 
/// <summary>  
/// Draws the part count column.  
/// </summary>  
private void DrawPartCount()  
{  
GUILayout.BeginVertical(GUILayout.Width(50.0f * GuiDisplaySize.Offset));  
GUILayout.Label("PARTS", titleStyle);  
for (int i = 0; i < stagesLength; ++i)  
{  
stage = stages[i];  
if (showAllStages || stage.deltaV > 0.0)  
{  
GUILayout.Label(stage.partCount + " / " + stage.totalPartCount, infoStyle);  
}  
}  
GUILayout.EndVertical();  
}  
 
/// <summary>  
/// Draws the settings panel.  
/// </summary>  
private void DrawSettings()  
{  
GUILayout.BeginHorizontal();  
GUILayout.Label("Compact mode collapses to the:", settingStyle);  
compactCollapseRight = !GUILayout.Toggle(!compactCollapseRight, "LEFT", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));  
compactCollapseRight = GUILayout.Toggle(compactCollapseRight, "RIGHT", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));  
GUILayout.EndHorizontal();  
 
GUILayout.BeginHorizontal();  
GUILayout.Label("Simulate using vectored thrust values:", settingStyle);  
SimManager.vectoredThrust = GUILayout.Toggle(SimManager.vectoredThrust, "ENABLED", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));  
GUILayout.EndHorizontal();  
 
GUILayout.BeginHorizontal();  
GUILayout.Label("Verbose Simulation Log:", settingStyle);  
SimManager.logOutput = GUILayout.Toggle(SimManager.logOutput, "ENABLED", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset));  
GUILayout.EndHorizontal();  
 
GUILayout.BeginHorizontal();  
GUILayout.Label("Build Engineer Overlay:", settingStyle);  
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("Key Bindings:", settingStyle);  
if (GUILayout.Button("EDIT KEY BINDINGS", buttonStyle, GUILayout.Width(200.0f * GuiDisplaySize.Offset)))  
{  
KeyBinder.Show();  
}  
GUILayout.EndHorizontal();  
 
GUILayout.BeginHorizontal();  
GUILayout.Label("GUI Size: " + GuiDisplaySize.Increment, settingStyle);  
if (GUILayout.Button("<", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)))  
{  
GuiDisplaySize.Increment--;  
}  
if (GUILayout.Button(">", buttonStyle, GUILayout.Width(100.0f * GuiDisplaySize.Offset)))  
{  
GuiDisplaySize.Increment++;  
}  
GUILayout.EndHorizontal();  
 
GUILayout.Label("Minimum delay between simulations: " + SimManager.minSimTime.TotalMilliseconds + "ms", settingStyle);  
GUI.skin = HighLogic.Skin;  
SimManager.minSimTime = TimeSpan.FromMilliseconds(GUILayout.HorizontalSlider((float)SimManager.minSimTime.TotalMilliseconds, 0, 2000.0f));  
 
GUI.skin = null;  
}  
 
/// <summary>  
/// Draws the stage number column.  
/// </summary>  
private void DrawStageNumbers()  
{  
GUILayout.BeginVertical(GUILayout.Width(30.0f * GuiDisplaySize.Offset));  
GUILayout.Label(string.Empty, titleStyle);  
for (int i = 0; i < stagesLength; ++i)  
{  
stage = stages[i];  
if (showAllStages || stage.deltaV > 0.0)  
{  
GUILayout.Label("S" + stage.number, titleStyle);  
}  
}  
GUILayout.EndVertical();  
}  
 
/// <summary>  
/// Draws the thrust column.  
/// </summary>  
private void DrawThrust()  
{  
GUILayout.BeginVertical(GUILayout.Width(75.0f * GuiDisplaySize.Offset));  
GUILayout.Label("THRUST", titleStyle);  
for (int i = 0; i < stagesLength; ++i)  
{  
stage = stages[i];  
if (showAllStages || stage.deltaV > 0.0)  
{  
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();  
}  
 
/// <summary>  
/// Drwas the thrust to weight ratio column.  
/// </summary>  
private void DrawTwr()  
{  
GUILayout.BeginVertical(GUILayout.Width(100.0f * GuiDisplaySize.Offset));  
GUILayout.Label("TWR (MAX)", titleStyle);  
for (int i = 0; i < stagesLength; ++i)  
{  
stage = stages[i];  
if (showAllStages || stage.deltaV > 0.0)  
{  
GUILayout.Label(stage.thrustToWeight.ToString("F2") + " (" + stage.maxThrustToWeight.ToString("F2") + ")", infoStyle);  
}  
}  
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>  
/// Initialises all the styles that are required.  
/// </summary>  
private void InitialiseStyles()  
{  
windowStyle = new GUIStyle(HighLogic.Skin.window)  
{  
alignment = TextAnchor.UpperLeft  
};  
 
areaStyle = new GUIStyle(HighLogic.Skin.box)  
{  
padding = new RectOffset(0, 0, 9, 0)  
};  
 
areaSettingStyle = new GUIStyle(HighLogic.Skin.box)  
{  
padding = new RectOffset(10, 10, 10, 10)  
};  
 
buttonStyle = new GUIStyle(HighLogic.Skin.button)  
{  
normal =  
{  
textColor = Color.white  
},  
fontSize = (int)(11 * GuiDisplaySize.Offset),  
fontStyle = FontStyle.Bold,  
alignment = TextAnchor.MiddleCenter  
};  
 
titleStyle = new GUIStyle(HighLogic.Skin.label)  
{  
normal =  
{  
textColor = Color.white  
},  
fontSize = (int)(11 * GuiDisplaySize.Offset),  
fontStyle = FontStyle.Bold,  
alignment = TextAnchor.MiddleCenter,  
stretchWidth = true  
};  
 
infoStyle = new GUIStyle(HighLogic.Skin.label)  
{  
fontSize = (int)(11 * GuiDisplaySize.Offset),  
fontStyle = FontStyle.Bold,  
alignment = TextAnchor.MiddleCenter,  
stretchWidth = true  
};  
 
settingStyle = new GUIStyle(titleStyle)  
{  
alignment = TextAnchor.MiddleLeft,  
stretchWidth = true,  
stretchHeight = true  
};  
 
settingAtmoStyle = new GUIStyle(titleStyle)  
{  
margin = new RectOffset(),  
padding = new RectOffset(),  
alignment = TextAnchor.UpperLeft  
};  
 
bodiesButtonStyle = new GUIStyle(HighLogic.Skin.button)  
{  
margin = new RectOffset(0, 0, 2, 0),  
padding = new RectOffset(5, 5, 5, 5),  
normal =  
{  
textColor = Color.white  
},  
active =  
{  
textColor = Color.white  
},  
fontSize = (int)(11 * GuiDisplaySize.Offset),  
fontStyle = FontStyle.Bold,  
alignment = TextAnchor.MiddleCenter,  
fixedHeight = 20.0f  
};  
 
bodiesButtonActiveStyle = new GUIStyle(bodiesButtonStyle)  
{  
normal = bodiesButtonStyle.onNormal,  
hover = bodiesButtonStyle.onHover  
};  
}  
 
/// <summary>  
/// Loads the settings when this object is created.  
/// </summary>  
private void Load()  
{  
try  
{  
SettingHandler handler = SettingHandler.Load("BuildAdvanced.xml");  
handler.Get("visible", ref visible);  
position.x = handler.Get("windowPositionX", position.x);  
position.y = handler.Get("windowPositionY", position.y);  
handler.Get("compactMode", ref compactMode);  
handler.Get("compactCollapseRight", ref compactCollapseRight);  
handler.Get("showAllStages", ref showAllStages);  
handler.Get("showAtmosphericDetails", ref showAtmosphericDetails);  
handler.Get("showSettings", ref showSettings);  
CelestialBodies.SetSelectedBody(handler.Get("selectedBodyName", CelestialBodies.SelectedBody.Name));  
}  
catch (Exception ex)  
{  
Logger.Exception(ex, "BuildAdvanced.Load()");  
}  
}  
 
private void OnSizeChanged()  
{  
InitialiseStyles();  
hasChanged = true;  
}  
 
/// <summary>  
/// Draws the OnGUI window.  
/// </summary>  
private void Window(int windowId)  
{  
try  
{  
compactModeRect = new Rect(position.width - 70.0f * GuiDisplaySize.Offset, 5.0f, 65.0f * GuiDisplaySize.Offset, 20.0f);  
 
// Draw the compact mode toggle.  
if (GUI.Toggle(compactModeRect, compactMode, "COMPACT", buttonStyle) != compactMode)  
{  
hasChanged = true;  
compactCheck = 2;  
compactRight = position.xMax;  
compactMode = !compactMode;  
}  
 
// When not in compact mode draw the 'All Stages' and 'Atmospheric' toggles.  
if (!compactMode)  
{  
if (GUI.Toggle(new Rect(position.width - 143.0f * GuiDisplaySize.Offset, 5.0f, 70.0f * GuiDisplaySize.Offset, 20.0f), showSettings, "SETTINGS", buttonStyle) != showSettings)  
{  
hasChanged = true;  
showSettings = !showSettings;  
}  
 
if (GUI.Toggle(new Rect(position.width - 226.0f * GuiDisplaySize.Offset, 5.0f, 80.0f * GuiDisplaySize.Offset, 20.0f), showAllStages, "ALL STAGES", buttonStyle) != showAllStages)  
{  
hasChanged = true;  
showAllStages = !showAllStages;  
}  
 
if (GUI.Toggle(new Rect(position.width - 324.0f * GuiDisplaySize.Offset, 5.0f, 95.0f * GuiDisplaySize.Offset, 20.0f), showAtmosphericDetails, "ATMOSPHERIC", buttonStyle) != showAtmosphericDetails)  
{  
hasChanged = true;  
showAtmosphericDetails = !showAtmosphericDetails;  
}  
 
bodiesListPosition = new Rect(position.width - 452.0f * GuiDisplaySize.Offset, 5.0f, 125.0f * GuiDisplaySize.Offset, 20.0f);  
bodiesList.enabled = GUI.Toggle(bodiesListPosition, bodiesList.enabled, "BODY: " + CelestialBodies.SelectedBody.Name.ToUpper(), buttonStyle);  
bodiesList.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.  
if (!compactMode)  
{  
GUILayout.BeginHorizontal(areaStyle);  
DrawStageNumbers();  
DrawPartCount();  
DrawCost();  
DrawMass();  
DrawIsp();  
DrawThrust();  
DrawTorque();  
DrawTwr();  
DrawDeltaV();  
DrawBurnTime();  
GUILayout.EndHorizontal();  
 
if (showAtmosphericDetails && !compactMode)  
{  
GUILayout.BeginVertical(areaSettingStyle);  
DrawAtmosphericDetails();  
GUILayout.EndVertical();  
}  
 
if (showSettings)  
{  
GUILayout.BeginVertical(areaSettingStyle);  
DrawSettings();  
GUILayout.EndVertical();  
}  
}  
else // Draw only a few details when in compact mode.  
{  
GUILayout.BeginHorizontal(areaStyle);  
DrawStageNumbers();  
DrawTwr();  
DrawDeltaV();  
GUILayout.EndHorizontal();  
}  
 
GUI.DragWindow();  
}  
catch (Exception ex)  
{  
Logger.Exception(ex, "BuildAdvanced.Window()");  
}  
}  
}  
}  
//  
// Kerbal Engineer Redux  
//  
// Copyright (C) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
#region Using Directives  
 
 
 
#endregion  
 
namespace KerbalEngineer.Editor  
{  
#region Using Directives  
 
using System;  
using Helpers;  
using Settings;  
using UnityEngine;  
 
#endregion  
 
[KSPAddon(KSPAddon.Startup.EditorAny, false)]  
public class BuildOverlay : MonoBehaviour  
{  
#region Fields  
 
private static BuildOverlayPartInfo buildOverlayPartInfo;  
private static BuildOverlayResources buildOverlayResources;  
private static BuildOverlayVessel buildOverlayVessel;  
private static BuildOverlay instance;  
 
private static float minimumWidth = 200.0f;  
private static GUIStyle nameStyle;  
private static float tabSpeed = 5.0f;  
private static GUIStyle tabStyle;  
private static GUIStyle titleStyle;  
private static GUIStyle valueStyle;  
private static GUIStyle windowStyle;  
 
#endregion  
 
#region Properties  
 
public static BuildOverlayPartInfo BuildOverlayPartInfo  
{  
get { return buildOverlayPartInfo; }  
}  
 
public static BuildOverlayResources BuildOverlayResources  
{  
get { return buildOverlayResources; }  
}  
 
public static BuildOverlayVessel BuildOverlayVessel  
{  
get { return buildOverlayVessel; }  
}  
 
public static float MinimumWidth  
{  
get { return minimumWidth; }  
set { minimumWidth = value; }  
}  
 
public static GUIStyle NameStyle  
{  
get  
{  
return nameStyle ?? (nameStyle = new GUIStyle  
{  
normal =  
{  
textColor = Color.white  
},  
fontSize = 11,  
fontStyle = FontStyle.Bold,  
alignment = TextAnchor.UpperLeft,  
stretchWidth = true  
});  
}  
}  
 
public static float TabSpeed  
{  
get { return tabSpeed; }  
set { tabSpeed = value; }  
}  
 
public static GUIStyle TabStyle  
{  
get  
{  
return tabStyle ?? (tabStyle = new GUIStyle  
{  
normal =  
{  
background = TextureHelper.CreateTextureFromColour(new Color(0.0f, 0.0f, 0.0f, 0.5f)),  
textColor = Color.yellow  
},  
hover =  
{  
background = TextureHelper.CreateTextureFromColour(new Color(0.0f, 0.0f, 0.0f, 0.75f)),  
textColor = Color.yellow  
},  
onNormal =  
{  
background = TextureHelper.CreateTextureFromColour(new Color(0.0f, 0.0f, 0.0f, 0.5f)),  
textColor = Color.yellow  
},  
onHover =  
{  
background = TextureHelper.CreateTextureFromColour(new Color(0.0f, 0.0f, 0.0f, 0.75f)),  
textColor = Color.yellow  
},  
padding = new RectOffset(20, 20, 0, 0),  
fontSize = 11,  
fontStyle = FontStyle.Bold,  
alignment = TextAnchor.MiddleCenter,  
fixedHeight = 15.0f,  
stretchWidth = true  
});  
}  
}  
 
public static GUIStyle TitleStyle  
{  
get  
{  
return titleStyle ?? (titleStyle = new GUIStyle  
{  
normal =  
{  
textColor = Color.yellow  
},  
fontSize = 11,  
fontStyle = FontStyle.Bold,  
stretchWidth = true  
});  
}  
}  
 
public static GUIStyle ValueStyle  
{  
get  
{  
return valueStyle ?? (valueStyle = new GUIStyle  
{  
normal =  
{  
textColor = Color.white  
},  
fontSize = 11,  
fontStyle = FontStyle.Normal,  
alignment = TextAnchor.UpperRight,  
stretchWidth = true  
});  
}  
}  
 
public static bool Visible  
{  
get { return BuildOverlayPartInfo.Visible && BuildOverlayVessel.Visible && BuildOverlayResources.Visible; }  
set { BuildOverlayPartInfo.Visible = BuildOverlayVessel.Visible = BuildOverlayResources.Visible = value; }  
}  
 
public static GUIStyle WindowStyle  
{  
get  
{  
return windowStyle ?? (windowStyle = new GUIStyle  
{  
normal =  
{  
background = TextureHelper.CreateTextureFromColour(new Color(0.0f, 0.0f, 0.0f, 0.5f))  
},  
padding = new RectOffset(5, 5, 3, 3),  
});  
}  
}  
 
#endregion  
 
#region Methods  
 
public static void Load()  
{  
var handler = SettingHandler.Load("BuildOverlay.xml");  
Visible = handler.GetSet("visible", Visible);  
BuildOverlayPartInfo.NamesOnly = handler.GetSet("namesOnly", BuildOverlayPartInfo.NamesOnly);  
BuildOverlayPartInfo.ClickToOpen = handler.GetSet("clickToOpen", BuildOverlayPartInfo.ClickToOpen);  
buildOverlayVessel.Open = handler.GetSet("vesselOpen", buildOverlayVessel.Open);  
buildOverlayResources.Open = handler.GetSet("resourcesOpen", buildOverlayResources.Open);  
buildOverlayVessel.WindowX = handler.GetSet("vesselWindowX", buildOverlayVessel.WindowX);  
handler.Save("BuildOverlay.xml");  
}  
 
public static void Save()  
{  
var handler = SettingHandler.Load("BuildOverlay.xml");  
handler.Set("visible", Visible);  
handler.Set("namesOnly", BuildOverlayPartInfo.NamesOnly);  
handler.Set("clickToOpen", BuildOverlayPartInfo.ClickToOpen);  
handler.Set("vesselOpen", buildOverlayVessel.Open);  
handler.Set("resourcesOpen", buildOverlayResources.Open);  
handler.Set("vesselWindowX", buildOverlayVessel.WindowX);  
handler.Save("BuildOverlay.xml");  
}  
 
protected void Awake()  
{  
try  
{  
if (instance != null)  
{  
Destroy(this);  
return;  
}  
instance = this;  
buildOverlayPartInfo = this.gameObject.AddComponent<BuildOverlayPartInfo>();  
buildOverlayVessel = this.gameObject.AddComponent<BuildOverlayVessel>();  
buildOverlayResources = this.gameObject.AddComponent<BuildOverlayResources>();  
Load();  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
protected void OnDestroy()  
{  
try  
{  
Save();  
if (buildOverlayPartInfo != null)  
{  
Destroy(buildOverlayPartInfo);  
}  
if (buildOverlayVessel != null)  
{  
Destroy(buildOverlayVessel);  
}  
if (buildOverlayResources != null)  
{  
Destroy(buildOverlayResources);  
}  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
#endregion  
}  
}  
//  
// Kerbal Engineer Redux  
//  
// Copyright (C) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
namespace KerbalEngineer.Editor  
{  
using System;  
using System.Collections.Generic;  
using Extensions;  
using Helpers;  
using UnityEngine;  
 
public class BuildOverlayPartInfo : MonoBehaviour  
{  
private static bool clickToOpen = true;  
private static ModuleResource 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 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 readonly List<PartInfoItem> infoItems = new List<PartInfoItem>();  
 
private Rect position;  
private Part selectedPart;  
private bool showInfo;  
private bool skipFrame;  
 
public static bool ClickToOpen  
{  
get  
{  
return clickToOpen;  
}  
set  
{  
clickToOpen = value;  
}  
}  
 
public static bool Hidden { get; set; }  
 
public static bool NamesOnly  
{  
get  
{  
return namesOnly;  
}  
set  
{  
namesOnly = value;  
}  
}  
 
public static bool Visible  
{  
get  
{  
return visible;  
}  
set  
{  
visible = value;  
}  
}  
 
protected void OnGUI()  
{  
try  
{  
if (!Visible || Hidden || selectedPart == null)  
{  
return;  
}  
 
position = GUILayout.Window(GetInstanceID(), position, Window, String.Empty, BuildOverlay.WindowStyle);  
}  
catch (Exception ex)  
 
{  
Logger.Exception(ex);  
}  
}  
 
protected void Update()  
{  
try  
{  
if (!Visible || Hidden || EditorLogic.RootPart == null || EditorLogic.fetch.editorScreen != EditorScreen.Parts)  
{  
return;  
}  
 
position.x = Mathf.Clamp(Input.mousePosition.x + 16.0f, 0.0f, Screen.width - position.width);  
position.y = Mathf.Clamp(Screen.height - Input.mousePosition.y, 0.0f, Screen.height - position.height);  
if (position.x < Input.mousePosition.x + 20.0f)  
{  
position.y = Mathf.Clamp(position.y + 20.0f, 0.0f, Screen.height - position.height);  
}  
if (position.x < Input.mousePosition.x + 16.0f && position.y < Screen.height - Input.mousePosition.y)  
{  
position.x = Input.mousePosition.x - 3 - position.width;  
}  
 
part = EditorLogic.fetch.ship.parts.Find(p => p.stackIcon.Highlighted) ?? EditorLogic.SelectedPart;  
if (part != null)  
{  
if (!part.Equals(selectedPart))  
{  
selectedPart = part;  
ResetInfo();  
}  
if (NamesOnly || skipFrame)  
{  
skipFrame = false;  
return;  
}  
 
if (!showInfo && Input.GetMouseButtonDown(2))  
{  
showInfo = true;  
}  
else if (ClickToOpen && showInfo && Input.GetMouseButtonDown(2))  
{  
ResetInfo();  
}  
 
if (showInfo)  
{  
PartInfoItem.Release(infoItems);  
infoItems.Clear();  
SetCostInfo();  
SetMassItems();  
SetResourceItems();  
SetEngineInfo();  
SetAlternatorInfo();  
SetGimbalInfo();  
SetRcsInfo();  
SetParachuteInfo();  
SetSasInfo();  
SetReactionWheelInfo();  
SetSolarPanelInfo();  
SetGeneratorInfo();  
SetDecouplerInfo();  
SetTransmitterInfo();  
SetScienceExperimentInfo();  
SetScienceContainerInfo();  
SetSingleActivationInfo();  
}  
}  
else  
{  
selectedPart = null;  
}  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
private void ResetInfo()  
{  
showInfo = !clickToOpen;  
skipFrame = true;  
position.width = namesOnly || clickToOpen ? 0.0f : 200.0f;  
position.height = 0.0f;  
}  
 
private void SetAlternatorInfo()  
{  
moduleAlternator = selectedPart.GetModule<ModuleAlternator>();  
if (moduleAlternator != null)  
{  
infoItems.Add(PartInfoItem.Create("Alternator"));  
for (int i = 0; i < moduleAlternator.outputResources.Count; ++i)  
{  
moduleResource = moduleAlternator.outputResources[i];  
infoItems.Add(PartInfoItem.Create("\t" + moduleResource.name, moduleResource.rate.ToRate()));  
}  
}  
}  
 
private void SetCostInfo()  
{  
infoItems.Add(PartInfoItem.Create("Cost", Units.ConcatF(selectedPart.GetCostDry(), selectedPart.GetCostWet())));  
}  
 
private void SetDecouplerInfo()  
{  
protoModuleDecoupler = selectedPart.GetProtoModuleDecoupler();  
if (protoModuleDecoupler != null)  
{  
infoItems.Add(PartInfoItem.Create("Ejection Force", protoModuleDecoupler.EjectionForce.ToForce()));  
if (protoModuleDecoupler.IsOmniDecoupler)  
{  
infoItems.Add(PartInfoItem.Create("Omni-directional"));  
}  
}  
}  
 
private void SetEngineInfo()  
{  
protoModuleEngine = selectedPart.GetProtoModuleEngine();  
if (protoModuleEngine != null)  
{  
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"));  
if (protoModuleEngine.Propellants.Count > 0)  
{  
infoItems.Add(PartInfoItem.Create("Propellants"));  
 
float totalRatio = 0.0f;  
for (int i = 0; i < protoModuleEngine.Propellants.Count; ++i)  
{  
totalRatio = totalRatio + protoModuleEngine.Propellants[i].ratio;  
}  
 
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()  
{  
moduleGenerator = selectedPart.GetModule<ModuleGenerator>();  
if (moduleGenerator != null)  
{  
if (moduleGenerator.inputList.Count > 0)  
{  
infoItems.Add(PartInfoItem.Create("Generator Input"));  
for (int i = 0; i < moduleGenerator.inputList.Count; ++i)  
{  
generatorResource = moduleGenerator.inputList[i];  
infoItems.Add(PartInfoItem.Create("\t" + generatorResource.name, generatorResource.rate.ToRate()));  
}  
}  
if (moduleGenerator.outputList.Count > 0)  
{  
infoItems.Add(PartInfoItem.Create("Generator Output"));  
for (int i = 0; i < moduleGenerator.outputList.Count; ++i)  
{  
generatorResource = moduleGenerator.outputList[i];  
infoItems.Add(PartInfoItem.Create("\t" + generatorResource.name, generatorResource.rate.ToRate()));  
}  
}  
if (moduleGenerator.isAlwaysActive)  
{  
infoItems.Add(PartInfoItem.Create("Generator is Always Active"));  
}  
}  
}  
 
private void SetGimbalInfo()  
{  
moduleGimbal = selectedPart.GetModule<ModuleGimbal>();  
if (moduleGimbal != null)  
{  
infoItems.Add(PartInfoItem.Create("Thrust Vectoring", moduleGimbal.gimbalRange.ToString("F2")));  
}  
}  
 
private void SetMassItems()  
{  
if (selectedPart.physicalSignificance == Part.PhysicalSignificance.FULL)  
{  
infoItems.Add(PartInfoItem.Create("Mass", Units.ToMass(selectedPart.GetDryMass(), selectedPart.GetWetMass())));  
}  
}  
 
private void SetParachuteInfo()  
{  
moduleParachute = selectedPart.GetModule<ModuleParachute>();  
if (moduleParachute != null)  
{  
infoItems.Add(PartInfoItem.Create("Deployed Drag", Units.ConcatF(moduleParachute.semiDeployedDrag, moduleParachute.fullyDeployedDrag)));  
infoItems.Add(PartInfoItem.Create("Deployment Altitude", moduleParachute.deployAltitude.ToDistance()));  
infoItems.Add(PartInfoItem.Create("Deployment Pressure", moduleParachute.minAirPressureToOpen.ToString("F2")));  
}  
}  
 
private void SetRcsInfo()  
{  
moduleRcs = selectedPart.GetModule<ModuleRCS>();  
if (moduleRcs != null)  
{  
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"));  
}  
}  
 
private void SetReactionWheelInfo()  
{  
moduleReactionWheel = selectedPart.GetModule<ModuleReactionWheel>();  
if (moduleReactionWheel != null)  
{  
infoItems.Add(PartInfoItem.Create("Reaction Wheel Torque"));  
infoItems.Add(PartInfoItem.Create("\tPitch", moduleReactionWheel.PitchTorque.ToTorque()));  
infoItems.Add(PartInfoItem.Create("\tRoll", moduleReactionWheel.RollTorque.ToTorque()));  
infoItems.Add(PartInfoItem.Create("\tYaw", moduleReactionWheel.YawTorque.ToTorque()));  
for (int i = 0; i < moduleReactionWheel.inputResources.Count; ++i)  
{  
moduleResource = moduleReactionWheel.inputResources[i];  
infoItems.Add(PartInfoItem.Create("\t" + moduleResource.name, moduleResource.rate.ToRate()));  
}  
}  
}  
 
private void SetResourceItems()  
{  
bool visibleResources = false;  
for (int i = 0; i < selectedPart.Resources.list.Count; ++i)  
{  
if (selectedPart.Resources.list[i].hideFlow == false)  
{  
visibleResources = true;  
break;  
}  
}  
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()  
{  
if (selectedPart.HasModule<ModuleSAS>())  
{  
infoItems.Add(PartInfoItem.Create("SAS Equiped"));  
}  
}  
 
private void SetScienceContainerInfo()  
{  
if (selectedPart.HasModule<ModuleScienceContainer>())  
{  
infoItems.Add(PartInfoItem.Create("Science Container"));  
}  
}  
 
private void SetScienceExperimentInfo()  
{  
moduleScienceExperiment = selectedPart.GetModule<ModuleScienceExperiment>();  
if (moduleScienceExperiment != null)  
{  
infoItems.Add(PartInfoItem.Create("Science Experiment", moduleScienceExperiment.experimentActionName));  
infoItems.Add(PartInfoItem.Create("\tTransmit Efficiency", moduleScienceExperiment.xmitDataScalar.ToPercent()));  
if (moduleScienceExperiment.rerunnable == false)  
{  
infoItems.Add(PartInfoItem.Create("\tSingle Usage"));  
}  
}  
}  
 
private void SetSingleActivationInfo()  
{  
if (selectedPart.HasModule<ModuleAnimateGeneric>(m => m.isOneShot))  
{  
infoItems.Add(PartInfoItem.Create("Single Activation"));  
}  
}  
 
private void SetSolarPanelInfo()  
{  
moduleDeployableSolarPanel = selectedPart.GetModule<ModuleDeployableSolarPanel>();  
if (moduleDeployableSolarPanel != null)  
{  
infoItems.Add(PartInfoItem.Create("Charge Rate", moduleDeployableSolarPanel.chargeRate.ToRate()));  
if (moduleDeployableSolarPanel.isBreakable)  
{  
infoItems.Add(PartInfoItem.Create("Breakable"));  
}  
if (moduleDeployableSolarPanel.sunTracking)  
{  
infoItems.Add(PartInfoItem.Create("Sun Tracking"));  
}  
}  
}  
 
private void SetTransmitterInfo()  
{  
moduleDataTransmitter = selectedPart.GetModule<ModuleDataTransmitter>();  
if (moduleDataTransmitter != null)  
{  
infoItems.Add(PartInfoItem.Create("Packet Size", moduleDataTransmitter.packetSize.ToString("F2") + " Mits"));  
infoItems.Add(PartInfoItem.Create("Bandwidth", (moduleDataTransmitter.packetInterval * moduleDataTransmitter.packetSize).ToString("F2") + "Mits/sec"));  
infoItems.Add(PartInfoItem.Create(moduleDataTransmitter.requiredResource, moduleDataTransmitter.packetResourceCost.ToString("F2") + "/Packet"));  
}  
}  
 
private void Window(int windowId)  
{  
try  
{  
GUILayout.Label(selectedPart.partInfo.title, BuildOverlay.TitleStyle);  
if (showInfo)  
{  
for (int i = 0; i < infoItems.Count; ++i)  
{  
partInfoItem = infoItems[i];  
GUILayout.Space(2.0f);  
GUILayout.BeginHorizontal();  
if (partInfoItem.Value != null)  
{  
GUILayout.Label(partInfoItem.Name + ":", BuildOverlay.NameStyle);  
GUILayout.Space(25.0f);  
GUILayout.Label(partInfoItem.Value, BuildOverlay.ValueStyle);  
}  
else  
{  
GUILayout.Label(partInfoItem.Name, BuildOverlay.NameStyle);  
}  
GUILayout.EndHorizontal();  
}  
}  
else if (clickToOpen && namesOnly == false)  
{  
GUILayout.Space(2.0f);  
GUILayout.Label("Click middle mouse to show more info...", BuildOverlay.NameStyle);  
}  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
}  
}  
//  
// Kerbal Engineer Redux  
//  
// Copyright (C) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
#region Using Directives  
 
#endregion  
 
namespace KerbalEngineer.Editor  
{  
using System;  
using System.Collections.Generic;  
using Extensions;  
using UnityEngine;  
 
public class BuildOverlayResources : MonoBehaviour  
{  
#region Fields  
private static bool visible = true;  
 
private readonly Dictionary<int, ResourceInfoItem> resources = new Dictionary<int, ResourceInfoItem>();  
 
private bool open = true;  
private float openPercent;  
private GUIContent tabContent;  
private Rect tabPosition;  
private Vector2 tabSize;  
private Rect windowPosition = new Rect(0.0f, 0.0f, BuildOverlay.MinimumWidth, 0.0f);  
#endregion  
 
#region Properties  
public static bool Visible  
{  
get  
{  
return visible;  
}  
set  
{  
visible = value;  
}  
}  
 
public bool Open  
{  
get  
{  
return open;  
}  
set  
{  
open = value;  
}  
}  
#endregion  
 
#region Methods: protected  
protected void OnGUI()  
{  
try  
{  
if (!Visible || resources.Count == 0 || EditorLogic.fetch.editorScreen != EditorScreen.Parts)  
{  
return;  
}  
 
open = GUI.Toggle(tabPosition, open, tabContent, BuildOverlay.TabStyle);  
if (openPercent > 0.0)  
{  
windowPosition = GUILayout.Window(GetInstanceID(), windowPosition, Window, String.Empty, BuildOverlay.WindowStyle);  
}  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
protected void Start()  
{  
try  
{  
tabContent = new GUIContent("RESOURCES");  
tabSize = BuildOverlay.TabStyle.CalcSize(tabContent);  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
protected void Update()  
{  
try  
{  
if (!Visible)  
{  
return;  
}  
 
SetResources();  
SetSlidePosition();  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
#endregion  
 
#region Methods: private  
private static Part part;  
private static PartResource partResource;  
 
private void SetResources()  
{  
int previousCount = resources.Count;  
resources.Clear();  
 
for (int i = 0; i < EditorLogic.fetch.ship.parts.Count; ++i)  
{  
part = EditorLogic.fetch.ship.parts[i];  
for (int j = 0; j < part.Resources.list.Count; ++j)  
{  
partResource = part.Resources.list[j];  
 
if (resources.ContainsKey(partResource.info.id))  
{  
resources[partResource.info.id].Amount += partResource.amount;  
}  
else  
{  
resources.Add(partResource.info.id, new ResourceInfoItem(partResource));  
}  
}  
}  
 
if (resources.Count < previousCount)  
{  
windowPosition.height = 0;  
}  
}  
 
private void SetSlidePosition()  
{  
if (open && openPercent < 1.0f)  
{  
openPercent = Mathf.Clamp(openPercent + Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f);  
}  
else if (!open && openPercent > 0.0f)  
{  
openPercent = Mathf.Clamp(openPercent - Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f);  
}  
 
windowPosition.x = BuildOverlay.BuildOverlayVessel.WindowPosition.xMax + 5.0f;  
windowPosition.y = Mathf.Lerp(Screen.height, Screen.height - windowPosition.height, openPercent);  
tabPosition.width = tabSize.x;  
tabPosition.height = tabSize.y;  
tabPosition.x = windowPosition.x;  
tabPosition.y = windowPosition.y - tabPosition.height;  
}  
 
private void Window(int windowId)  
{  
try  
{  
bool firstItem = true;  
foreach (KeyValuePair<int, ResourceInfoItem> resource in resources)  
{  
if (!firstItem)  
{  
GUILayout.Space(2.0f);  
}  
firstItem = false;  
 
GUILayout.BeginHorizontal();  
 
GUILayout.Label(resource.Value.Name + ":", BuildOverlay.NameStyle);  
GUILayout.Space(50.0f);  
if (resource.Value.Mass > 0.0)  
{  
GUILayout.Label("(" + resource.Value.Mass.ToMass() + ") " + resource.Value.Amount.ToString("N1"), BuildOverlay.ValueStyle);  
}  
else  
{  
GUILayout.Label(resource.Value.Amount.ToString("N1"), BuildOverlay.ValueStyle);  
}  
 
GUILayout.EndHorizontal();  
}  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
#endregion  
}  
}  
//  
// Kerbal Engineer Redux  
//  
// Copyright (C) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
#region Using Directives  
#endregion  
 
namespace KerbalEngineer.Editor  
{  
#region Using Directives  
using System;  
using System.Collections.Generic;  
using Helpers;  
using UnityEngine;  
using VesselSimulator;  
 
#endregion  
 
public class BuildOverlayVessel : MonoBehaviour  
{  
#region Constants  
private const float Width = 175.0f;  
#endregion  
 
#region Fields  
private static bool visible = true;  
 
private readonly List<PartInfoItem> infoItems = new List<PartInfoItem>();  
 
private Stage lastStage;  
private bool open = true;  
private float openPercent;  
private GUIContent tabContent;  
private Rect tabPosition;  
private Vector2 tabSize;  
private Rect windowPosition = new Rect(330.0f, 0.0f, Width, 0.0f);  
#endregion  
 
#region Properties  
public static bool Visible  
{  
get  
{  
return visible;  
}  
set  
{  
visible = value;  
}  
}  
 
public bool Open  
{  
get  
{  
return open;  
}  
set  
{  
open = value;  
}  
}  
 
public Rect WindowPosition  
{  
get  
{  
return windowPosition;  
}  
}  
 
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()  
{  
try  
{  
if (!Visible || EditorLogic.RootPart == null || EditorLogic.fetch.editorScreen != EditorScreen.Parts)  
{  
return;  
}  
 
open = GUI.Toggle(tabPosition, open, tabContent, BuildOverlay.TabStyle);  
if (openPercent > 0.0)  
{  
windowPosition = GUILayout.Window(GetInstanceID(), windowPosition, VesselWindow, String.Empty, BuildOverlay.WindowStyle);  
}  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
protected void Start()  
{  
try  
{  
tabContent = new GUIContent("VESSEL");  
tabSize = BuildOverlay.TabStyle.CalcSize(tabContent);  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
protected void Update()  
{  
try  
{  
if (!Visible || EditorLogic.RootPart == null)  
{  
return;  
}  
 
if (openPercent > 0.0)  
{  
SetVesselInfo();  
}  
 
SetSlidePosition();  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
private void GetStageInfo()  
{  
lastStage = SimManager.LastStage;  
}  
 
private void SetSlidePosition()  
{  
if (open && openPercent < 1.0f)  
{  
openPercent = Mathf.Clamp(openPercent + Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f);  
}  
else if (!open && openPercent > 0.0f)  
{  
openPercent = Mathf.Clamp(openPercent - Time.deltaTime * BuildOverlay.TabSpeed, 0.0f, 1.0f);  
}  
 
windowPosition.y = Mathf.Lerp(Screen.height, Screen.height - windowPosition.height, openPercent);  
if (windowPosition.width < Width)  
{  
windowPosition.width = Width;  
}  
tabPosition.width = tabSize.x;  
tabPosition.height = tabSize.y;  
tabPosition.x = windowPosition.x;  
tabPosition.y = windowPosition.y - tabPosition.height;  
}  
 
private void SetVesselInfo()  
{  
SimManager.Gravity = CelestialBodies.SelectedBody.Gravity;  
 
if (BuildAdvanced.Instance.ShowAtmosphericDetails)  
{  
SimManager.Atmosphere = CelestialBodies.SelectedBody.GetAtmospheres(BuildAdvanced.Altitude);  
}  
else  
{  
SimManager.Atmosphere = 0.0;  
}  
 
SimManager.RequestSimulation();  
SimManager.TryStartSimulation();  
 
if (lastStage != null)  
{  
PartInfoItem.Release(infoItems);  
infoItems.Clear();  
infoItems.Add(PartInfoItem.Create("Delta-V", lastStage.deltaV.ToString("N0") + " / " + lastStage.totalDeltaV.ToString("N0") + "m/s"));  
infoItems.Add(PartInfoItem.Create("Mass", Units.ToMass(lastStage.mass, lastStage.totalMass)));  
infoItems.Add(PartInfoItem.Create("TWR", lastStage.thrustToWeight.ToString("F2") + " (" + lastStage.maxThrustToWeight.ToString("F2") + ")"));  
infoItems.Add(PartInfoItem.Create("Parts", lastStage.partCount + " / " + lastStage.totalPartCount));  
}  
}  
 
private void VesselWindow(int windowId)  
{  
try  
{  
bool firstItem = true;  
foreach (PartInfoItem item in infoItems)  
{  
if (!firstItem)  
{  
GUILayout.Space(2.0f);  
}  
firstItem = false;  
 
GUILayout.BeginHorizontal();  
if (item.Value != null)  
{  
GUILayout.Label(item.Name + ":", BuildOverlay.NameStyle);  
GUILayout.FlexibleSpace();  
GUILayout.Label(item.Value, BuildOverlay.ValueStyle);  
}  
else  
{  
GUILayout.Label(item.Name, BuildOverlay.NameStyle);  
}  
GUILayout.EndHorizontal();  
}  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
#endregion  
}  
}  
//  
// Kerbal Engineer Redux  
//  
// Copyright (C) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
#region Using Directives  
 
using System;  
 
using UnityEngine;  
 
#endregion  
 
namespace KerbalEngineer.Editor  
{  
using KSP.UI;  
using KSP.UI.Screens;  
 
[KSPAddon(KSPAddon.Startup.EditorAny, false)]  
public class BuildToolbar : MonoBehaviour  
{  
#region Fields  
 
private ApplicationLauncherButton button;  
 
#endregion  
 
#region Methods: private  
 
private void Awake()  
{  
GameEvents.onGUIApplicationLauncherReady.Add(this.OnGuiAppLauncherReady);  
Logger.Log("BuildToolbar->Awake");  
}  
 
private void Start()  
{  
if (button == null)  
{  
OnGuiAppLauncherReady();  
}  
}  
 
private void OnDestroy()  
{  
GameEvents.onGUIApplicationLauncherReady.Remove(this.OnGuiAppLauncherReady);  
if (this.button != null)  
{  
ApplicationLauncher.Instance.RemoveModApplication(this.button);  
}  
Logger.Log("BuildToolbar->OnDestroy");  
}  
 
private void OnGuiAppLauncherReady()  
{  
try  
{  
this.button = ApplicationLauncher.Instance.AddModApplication(  
() => BuildAdvanced.Instance.Visible = true,  
() => BuildAdvanced.Instance.Visible = false,  
null,  
null,  
null,  
null,  
ApplicationLauncher.AppScenes.ALWAYS,  
GameDatabase.Instance.GetTexture("KerbalEngineer/Textures/ToolbarIcon", false)  
);  
Logger.Log("BuildToolbar->OnGuiAppLauncherReady");  
}  
catch (Exception ex)  
{  
Logger.Exception(ex, "BuildToolbar->OnGuiAppLauncherReady");  
}  
}  
 
private void Update()  
{  
try  
{  
if (this.button == null)  
{  
return;  
}  
 
if (EditorLogic.fetch != null && EditorLogic.fetch.ship.parts.Count > 0)  
{  
if (BuildAdvanced.Instance.Visible && this.button.toggleButton.CurrentState != UIRadioButton.State.True)  
{  
this.button.SetTrue();  
}  
else if (!BuildAdvanced.Instance.Visible && this.button.toggleButton.CurrentState != UIRadioButton.State.False)  
{  
this.button.SetFalse();  
}  
}  
else if (this.button.toggleButton.Interactable)  
{  
this.button.Disable();  
}  
}  
catch (Exception ex)  
{  
Logger.Exception(ex, "BuildToolbar->Update");  
}  
}  
 
#endregion  
}  
}  
//  
// Kerbal Engineer Redux  
//  
// Copyright (C) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
namespace KerbalEngineer.Editor  
{  
using System.Collections.Generic;  
using VesselSimulator;  
 
public class PartInfoItem  
{  
private static readonly Pool<PartInfoItem> pool = new Pool<PartInfoItem>(Create, Reset);  
 
public string Name { get; set; }  
 
public string Value { get; set; }  
 
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) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
#region Using Directives  
 
using KerbalEngineer.Extensions;  
 
#endregion  
 
namespace KerbalEngineer.Editor  
{  
public class ResourceInfoItem  
{  
#region Constructors  
 
public ResourceInfoItem(PartResource resource)  
{  
this.Definition = resource.GetDefinition();  
this.Name = this.Definition.name;  
this.Amount = resource.amount;  
}  
 
#endregion  
 
#region Properties  
 
public double Amount { get; set; }  
 
public PartResourceDefinition Definition { get; set; }  
 
public double Mass  
{  
get { return this.Amount * this.Definition.density; }  
}  
 
public string Name { get; set; }  
 
#endregion  
}  
}  
//  
// 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  
{  
using System.IO;  
using System.Reflection;  
 
public static class EngineerGlobals  
{  
/// <summary>  
/// Current version of the Kerbal Engineer assembly.  
/// </summary>  
public const string ASSEMBLY_VERSION = "1.0.19.4";  
 
private static string assemblyFile;  
private static string assemblyName;  
private static string assemblyPath;  
private static string settingsPath;  
 
/// <summary>  
/// Gets the Kerbal Engineer assembly's path including the file name.  
/// </summary>  
public static string AssemblyFile  
{  
get  
{  
return assemblyFile ?? (assemblyFile = Assembly.GetExecutingAssembly().Location);  
}  
}  
 
/// <summary>  
/// Gets the Kerbal Engineer assembly's file name.  
/// </summary>  
public static string AssemblyName  
{  
get  
{  
return assemblyName ?? (assemblyName = new FileInfo(AssemblyFile).Name);  
}  
}  
 
/// <summary>  
/// Gets the Kerbal Engineer assembly's path excluding the file name.  
/// </summary>  
public static string AssemblyPath  
{  
get  
{  
return assemblyPath ?? (assemblyPath = AssemblyFile.Replace(new FileInfo(AssemblyFile).Name, ""));  
}  
}  
 
/// <summary>  
/// Gets the settings directory path.  
/// </summary>  
public static string SettingsPath  
{  
get  
{  
if (string.IsNullOrEmpty(settingsPath))  
{  
settingsPath = Path.Combine(AssemblyPath, "Settings");  
}  
return settingsPath;  
}  
}  
}  
}  
//  
// Kerbal Engineer Redux  
//  
// 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  
{  
using Helpers;  
 
public static class DoubleExtensions  
{  
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)  
{  
return Units.ToAcceleration(value);  
}  
 
public static string ToAngle(this double value)  
{  
return Units.ToAngle(value);  
}  
 
public static string ToDistance(this double value)  
{  
return Units.ToDistance(value);  
}  
 
public static string ToFlux(this double value)  
{  
return Units.ToFlux(value);  
}  
 
public static string ToForce(this double value)  
{  
return Units.ToForce(value);  
}  
 
public static string ToMach(this double value)  
{  
return Units.ToMach(value);  
}  
 
public static string ToMass(this double value)  
{  
return Units.ToMass(value);  
}  
 
public static string ToPercent(this double value)  
{  
return Units.ToPercent(value);  
}  
 
public static string ToRate(this double value)  
{  
return Units.ToRate(value);  
}  
 
public static string ToSpeed(this double value)  
{  
return Units.ToSpeed(value);  
}  
 
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  
//  
// 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  
{  
using Helpers;  
 
public static class FloatExtensions  
{  
public static string ToAcceleration(this float value)  
{  
return Units.ToAcceleration(value);  
}  
 
public static string ToAngle(this float value)  
{  
return Units.ToAngle(value);  
}  
 
public static string ToDistance(this float value)  
{  
return Units.ToDistance(value);  
}  
 
public static string ToFlux(this float value)  
{  
return Units.ToFlux(value);  
}  
 
public static string ToForce(this float value)  
{  
return Units.ToForce(value);  
}  
 
public static string ToMach(this float value)  
{  
return Units.ToMach(value);  
}  
 
public static string ToMass(this float value)  
{  
return Units.ToMass(value);  
}  
 
public static string ToPercent(this float value)  
{  
return Units.ToPercent(value);  
}  
 
public static string ToRate(this float value)  
{  
return Units.ToRate(value);  
}  
 
public static string ToSpeed(this float value)  
{  
return Units.ToSpeed(value);  
}  
 
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  
//  
// Copyright (C) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
#region Using Directives  
 
using System;  
 
using KerbalEngineer.Helpers;  
 
using UnityEngine;  
 
#endregion  
 
namespace KerbalEngineer.Extensions  
{  
public static class OrbitExtensions  
{  
#region Constants  
 
public const double Tau = Math.PI * 2.0;  
 
#endregion  
 
#region Methods: public  
 
public static double GetAngleToAscendingNode(this Orbit orbit)  
{  
return GetAngleToTrueAnomaly(orbit, GetTrueAnomalyOfAscendingNode(orbit));  
}  
 
public static double GetAngleToDescendingNode(this Orbit orbit)  
{  
return GetAngleToTrueAnomaly(orbit, GetTrueAnomalyOfDescendingNode(orbit));  
}  
 
public static double GetAngleToPrograde(this Orbit orbit)  
{  
return GetAngleToPrograde(orbit, Planetarium.GetUniversalTime());  
}  
 
public static double GetAngleToPrograde(this Orbit orbit, double universalTime)  
{  
if (orbit.referenceBody == CelestialBodies.SystemBody.CelestialBody)  
{  
return 0.0;  
}  
 
Vector3d orbitVector = orbit.getRelativePositionAtUT(universalTime);  
orbitVector.z = 0.0;  
 
Vector3d bodyVector = orbit.referenceBody.orbit.getOrbitalVelocityAtUT(universalTime);  
bodyVector.z = 0.0;  
 
double angle = AngleHelper.GetAngleBetweenVectors(bodyVector, orbitVector);  
 
return AngleHelper.Clamp360(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;  
}  
 
Vector3d orbitVector = orbit.getRelativePositionAtUT(universalTime);  
orbitVector.z = 0.0;  
 
Vector3d bodyVector = orbit.referenceBody.orbit.getOrbitalVelocityAtUT(universalTime);  
bodyVector.z = 0.0;  
 
double angle = AngleHelper.GetAngleBetweenVectors(-bodyVector, orbitVector);  
 
return AngleHelper.Clamp360(orbit.inclination < 90.0 ? angle : 360.0 - angle);  
}  
 
public static double GetAngleToTrueAnomaly(this Orbit orbit, double trueAnomaly)  
{  
return AngleHelper.Clamp360(trueAnomaly - orbit.trueAnomaly);  
}  
 
public static double GetAngleToVector(this Orbit orbit, Vector3d vector)  
{  
return GetAngleToTrueAnomaly(orbit, GetTrueAnomalyFromVector(orbit, Vector3d.Exclude(orbit.GetOrbitNormal(), vector)));  
}  
 
public static double GetPhaseAngle(this Orbit orbit, Orbit target)  
{  
var angle = AngleHelper.GetAngleBetweenVectors(Vector3d.Exclude(orbit.GetOrbitNormal(), target.pos), orbit.pos);  
return (orbit.semiMajorAxis < target.semiMajorAxis) ? angle : angle - 360.0;  
}  
 
public static double GetRelativeInclination(this Orbit orbit, Orbit target)  
{  
return Vector3d.Angle(orbit.GetOrbitNormal(), target.GetOrbitNormal());  
}  
 
public static double GetTimeToAscendingNode(this Orbit orbit)  
{  
return GetTimeToTrueAnomaly(orbit, GetTrueAnomalyOfAscendingNode(orbit));  
}  
 
public static double GetTimeToDescendingNode(this Orbit orbit)  
{  
return GetTimeToTrueAnomaly(orbit, GetTrueAnomalyOfDescendingNode(orbit));  
}  
 
public static double GetTimeToTrueAnomaly(this Orbit orbit, double trueAnomaly)  
{  
var time = orbit.GetDTforTrueAnomaly(trueAnomaly * Mathf.Deg2Rad, orbit.period);  
return time < 0.0 ? time + orbit.period : time;  
}  
 
public static double GetTimeToVector(this Orbit orbit, Vector3d vector)  
{  
return GetTimeToTrueAnomaly(orbit, GetTrueAnomalyFromVector(orbit, vector));  
}  
 
public static double GetTrueAnomalyFromVector(this Orbit orbit, Vector3d vector)  
{  
return orbit.GetTrueAnomalyOfZupVector(vector) * Mathf.Rad2Deg;  
}  
 
public static double GetTrueAnomalyOfAscendingNode(this Orbit orbit)  
{  
return 360.0 - orbit.argumentOfPeriapsis;  
}  
 
public static double GetTrueAnomalyOfDescendingNode(this Orbit orbit)  
{  
return 180.0 - orbit.argumentOfPeriapsis;  
}  
 
#endregion  
}  
}  
//  
// Kerbal Engineer Redux  
//  
// Copyright (C) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
namespace KerbalEngineer.Extensions  
{  
using System;  
using System.Collections.Generic;  
using CompoundParts;  
 
public static class PartExtensions  
{  
//private static Part cachePart;  
//private static PartModule cachePartModule;  
//private static PartResource cachePartResource;  
 
/// <summary>  
/// Gets whether the part contains a specific resource.  
/// </summary>  
public static bool ContainsResource(this Part part, int resourceId)  
{  
return part.Resources.Contains(resourceId);  
}  
 
/// <summary>  
/// Gets whether the part contains resources.  
/// </summary>  
public static bool ContainsResources(this Part part)  
{  
for (int i = 0; i < part.Resources.list.Count; ++i)  
{  
if (part.Resources.list[i].amount > 0.0)  
{  
return true;  
}  
}  
return false;  
}  
 
/// <summary>  
/// Gets whether the part has fuel.  
/// </summary>  
/* not used  
public static bool EngineHasFuel(this Part part)  
{  
PartModule cachePartModule = GetModule<ModuleEngines>(part);  
if (cachePartModule != null)  
{  
return (cachePartModule as ModuleEngines).getFlameoutState;  
}  
 
cachePartModule = GetModuleMultiModeEngine(part);  
if (cachePartModule != null)  
{  
return (cachePartModule as ModuleEnginesFX).getFlameoutState;  
}  
 
return false;  
}  
*/  
/// <summary>  
/// Gets the cost of the part excluding resources.  
/// </summary>  
public static double GetCostDry(this Part part)  
{  
return part.partInfo.cost - GetResourceCostMax(part) + part.GetModuleCosts(0.0f);  
}  
 
/// <summary>  
/// Gets the cost of the part including maximum resources.  
/// </summary>  
public static double GetCostMax(this Part part)  
{  
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>  
/// Gets the cost of the part including resources.  
/// </summary>  
public static double GetCostWet(this Part part)  
{  
return part.partInfo.cost - GetResourceCostInverted(part) + part.GetModuleCostsNoAlloc(0.0f); // part.GetModuleCosts allocate 44B per call.  
}  
 
/// <summary>  
/// Gets the dry mass of the part.  
/// </summary>  
public static double GetDryMass(this Part part)  
{  
return (part.physicalSignificance == Part.PhysicalSignificance.FULL) ? part.mass : 0d;  
}  
 
/// <summary>  
/// Gets the maximum thrust of the part if it's an engine.  
/// </summary>  
/* not used  
public static double GetMaxThrust(this Part part)  
{  
PartModule cachePartModule = GetModule<ModuleEngines>(part);  
if (cachePartModule != null)  
{  
return (cachePartModule as ModuleEngines).maxThrust;  
}  
 
cachePartModule = GetModuleMultiModeEngine(part) ?? GetModule<ModuleEnginesFX>(part);  
if (cachePartModule != null)  
{  
return (cachePartModule as ModuleEnginesFX).maxThrust;  
}  
 
return 0.0;  
}  
*/  
 
/// <summary>  
/// Gets the first typed PartModule in the part's module list.  
/// </summary>  
public static T GetModule<T>(this Part part) where T : PartModule  
{  
for (int i = 0; i < part.Modules.Count; i++)  
{  
PartModule pm = part.Modules[i];  
if (pm is T)  
return (T)pm;  
}  
return null;  
}  
 
/// <summary>  
/// Gets a typed PartModule.  
/// </summary>  
public static T GetModule<T>(this Part part, string className) where T : PartModule  
{  
return part.Modules[className] as T;  
}  
 
/// <summary>  
/// Gets a typed PartModule.  
/// </summary>  
public static T GetModule<T>(this Part part, int classId) where T : PartModule  
{  
return part.Modules[classId] as T;  
}  
 
/// <summary>  
/// Gets a ModuleAlternator typed PartModule.  
/// </summary>  
public static ModuleAlternator GetModuleAlternator(this Part part)  
{  
return GetModule<ModuleAlternator>(part);  
}  
 
/// <summary>  
/// Gets a ModuleDeployableSolarPanel typed PartModule.  
/// </summary>  
public static ModuleDeployableSolarPanel GetModuleDeployableSolarPanel(this Part part)  
{  
return GetModule<ModuleDeployableSolarPanel>(part);  
}  
 
/// <summary>  
/// Gets a ModuleEngines typed PartModule.  
/// </summary>  
public static ModuleEngines GetModuleEngines(this Part part)  
{  
return GetModule<ModuleEngines>(part);  
}  
 
/* public static ModuleEnginesFX GetModuleEnginesFx(this Part part)  
{  
return GetModule<ModuleEnginesFX>(part);  
}*/  
 
/// <summary>  
/// Gets a ModuleGenerator typed PartModule.  
/// </summary>  
public static ModuleGenerator GetModuleGenerator(this Part part)  
{  
return GetModule<ModuleGenerator>(part);  
}  
 
/// <summary>  
/// Gets a ModuleGimbal typed PartModule.  
/// </summary>  
public static ModuleGimbal GetModuleGimbal(this Part part)  
{  
return GetModule<ModuleGimbal>(part);  
}  
 
/// <summary>  
/// Gets the current selected ModuleEnginesFX.  
/// </summary>  
public static ModuleEngines GetModuleMultiModeEngine(this Part part)  
{  
ModuleEngines moduleEngines;  
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>  
/// Gets a ModuleParachute typed PartModule.  
/// </summary>  
public static ModuleParachute GetModuleParachute(this Part part)  
{  
return GetModule<ModuleParachute>(part);  
}  
 
public static ModuleRCS GetModuleRcs(this Part part)  
{  
return GetModule<ModuleRCS>(part);  
}  
 
/// <summary>  
/// Gets a typed list of PartModules.  
/// </summary>  
public static List<T> GetModules<T>(this Part part) where T : PartModule  
{  
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)  
{  
PartModule cachePartModule = GetModule<ModuleDecouple>(part);  
if (cachePartModule == null)  
{  
cachePartModule = GetModule<ModuleAnchoredDecoupler>(part);  
}  
if (cachePartModule != null)  
{  
return new ProtoModuleDecoupler(cachePartModule);  
}  
 
return null;  
}  
 
/// <summary>  
/// Gets a generic proto engine for the current engine module attached to the part.  
/// </summary>  
public static ProtoModuleEngine GetProtoModuleEngine(this Part part)  
{  
PartModule cachePartModule = GetModule<ModuleEngines>(part);  
if (cachePartModule != null)  
{  
return new ProtoModuleEngine(cachePartModule);  
}  
 
cachePartModule = GetModuleMultiModeEngine(part) ?? GetModule<ModuleEnginesFX>(part);  
if (cachePartModule != null)  
{  
return new ProtoModuleEngine(cachePartModule);  
}  
 
return null;  
}  
 
/// <summary>  
/// Gets the cost of the part's contained resources.  
/// </summary>  
public static double GetResourceCost(this Part part)  
{  
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>  
/// Gets the cost of the part's contained resources, inverted.  
/// </summary>  
public static double GetResourceCostInverted(this Part part)  
{  
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>  
/// Gets the cost of the part's maximum contained resources.  
/// </summary>  
public static double GetResourceCostMax(this Part part)  
{  
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>  
/// Gets the current specific impulse for the engine.  
/// </summary>  
/* not used  
public static double GetSpecificImpulse(this Part part, float atmosphere)  
{  
PartModule cachePartModule = GetModule<ModuleEngines>(part);  
if (cachePartModule != null)  
{  
return (cachePartModule as ModuleEngines).atmosphereCurve.Evaluate(atmosphere);  
}  
 
cachePartModule = GetModuleMultiModeEngine(part) ?? GetModule<ModuleEnginesFX>(part);  
if (cachePartModule != null)  
{  
return (cachePartModule as ModuleEnginesFX).atmosphereCurve.Evaluate(atmosphere);  
}  
 
return 0.0;  
}  
*/  
 
/// <summary>  
/// Gets the total mass of the part including resources.  
/// </summary>  
public static double GetWetMass(this Part part)  
{  
return (part.physicalSignificance == Part.PhysicalSignificance.FULL) ? part.mass + part.GetResourceMass() : part.GetResourceMass();  
}  
 
/// <summary>  
/// Gets whether the part contains a PartModule.  
/// </summary>  
public static bool HasModule<T>(this Part part) where T : PartModule  
{  
for (int i = 0; i < part.Modules.Count; i++)  
{  
if (part.Modules[i] is T)  
return true;  
}  
return false;  
}  
 
/// <summary>  
/// Gets whether the part contains a PartModule conforming to the supplied predicate.  
/// </summary>  
public static bool HasModule<T>(this Part part, Func<T, bool> predicate) where T : PartModule  
{  
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>  
/// Gets whether the part contains a PartModule.  
/// </summary>  
public static bool HasModule(this Part part, string className)  
{  
return part.Modules.Contains(className);  
}  
 
/// <summary>  
/// Gets whether the part contains a PartModule.  
/// </summary>  
public static bool HasModule(this Part part, int moduleId)  
{  
return part.Modules.Contains(moduleId);  
}  
 
/// <summary>  
/// Gets whether the part has a one shot animation.  
/// </summary>  
public static bool HasOneShotAnimation(this Part part)  
{  
PartModule cachePartModule = GetModule<ModuleAnimateGeneric>(part);  
return cachePartModule != null && (cachePartModule as ModuleAnimateGeneric).isOneShot;  
}  
 
/// <summary>  
/// Gets whether the part is a command module.  
/// </summary>  
public static bool IsCommandModule(this Part part)  
{  
return HasModule<ModuleCommand>(part);  
}  
 
/// <summary>  
/// Gets whether the part is decoupled in a specified stage.  
/// </summary>  
public static bool IsDecoupledInStage(this Part part, int stage)  
{  
if ((IsDecoupler(part) || IsLaunchClamp(part)) && part.inverseStage == stage)  
{  
return true;  
}  
if (part.parent == null)  
{  
return false;  
}  
return IsDecoupledInStage(part.parent, stage);  
}  
 
/// <summary>  
/// Gets whether the part is a decoupler.  
/// </summary>  
public static bool IsDecoupler(this Part part)  
{  
return HasModule<ModuleDecouple>(part) || HasModule<ModuleAnchoredDecoupler>(part);  
}  
 
/// <summary>  
/// Gets whether the part is an active engine.  
/// </summary>  
public static bool IsEngine(this Part part)  
{  
return HasModule<ModuleEngines>(part);  
}  
 
/// <summary>  
/// Gets whether the part is a fuel line.  
/// </summary>  
public static bool IsFuelLine(this Part part)  
{  
return HasModule<CModuleFuelLine>(part);  
}  
 
/// <summary>  
/// Gets whether the part is a generator.  
/// </summary>  
public static bool IsGenerator(this Part part)  
{  
return HasModule<ModuleGenerator>(part);  
}  
 
/// <summary>  
/// Gets whether the part is a launch clamp.  
/// </summary>  
public static bool IsLaunchClamp(this Part part)  
{  
return HasModule<LaunchClamp>(part);  
}  
 
/// <summary>  
/// Gets whether the part is a parachute.  
/// </summary>  
public static bool IsParachute(this Part part)  
{  
return HasModule<ModuleParachute>(part);  
}  
 
/// <summary>  
/// Gets whether the part is considered a primary part on the vessel.  
/// </summary>  
public static bool IsPrimary(this Part part, List<Part> partsList, PartModule module)  
{  
for (int i = 0; i < partsList.Count; i++)  
{  
var vesselPart = partsList[i];  
if (!vesselPart.HasModule(module.ClassID))  
{  
continue;  
}  
if (vesselPart == part)  
{  
return true;  
}  
break;  
}  
 
return false;  
}  
 
public static bool IsRcsModule(this Part part)  
{  
return HasModule<ModuleRCS>(part);  
}  
 
/// <summary>  
/// Gets whether the part is a sepratron.  
/// </summary>  
public static bool IsSepratron(this Part part)  
{  
return IsSolidRocket(part) && part.ActivatesEvenIfDisconnected && IsDecoupledInStage(part, part.inverseStage);  
}  
 
/// <summary>  
/// Gets whether the part is a deployable solar panel.  
/// </summary>  
public static bool IsSolarPanel(this Part part)  
{  
return HasModule<ModuleDeployableSolarPanel>(part);  
}  
 
/// <summary>  
/// Gets whether the part is a solid rocket motor.  
/// </summary>  
public static bool IsSolidRocket(this Part part)  
{  
return (part.HasModule<ModuleEngines>() && part.GetModuleEngines().throttleLocked);  
}  
 
public class ProtoModuleDecoupler  
{  
private readonly PartModule module;  
 
public ProtoModuleDecoupler(PartModule module)  
{  
this.module = module;  
 
if (this.module is ModuleDecouple)  
{  
SetModuleDecouple();  
}  
else if (this.module is ModuleAnchoredDecoupler)  
{  
SetModuleAnchoredDecoupler();  
}  
}  
 
public double EjectionForce { get; private set; }  
public bool IsOmniDecoupler { get; private set; }  
 
private void SetModuleAnchoredDecoupler()  
{  
ModuleAnchoredDecoupler decoupler = module as ModuleAnchoredDecoupler;  
if (decoupler == null)  
{  
return;  
}  
 
EjectionForce = decoupler.ejectionForce;  
}  
 
private void SetModuleDecouple()  
{  
ModuleDecouple decoupler = module as ModuleDecouple;  
if (decoupler == null)  
{  
return;  
}  
 
EjectionForce = decoupler.ejectionForce;  
IsOmniDecoupler = decoupler.isOmniDecoupler;  
}  
}  
 
// 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  
// the first ModuleEngines for engines with multiple modules.  
// It should really show all the modes for multi-mode engines as separate sections.  
// 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  
{  
private readonly PartModule module;  
 
public ProtoModuleEngine(PartModule module)  
{  
this.module = module;  
 
if (module is ModuleEngines)  
{  
SetModuleEngines();  
}  
}  
 
public double MaximumThrust { get; private set; }  
public double MinimumThrust { get; private set; }  
public List<Propellant> Propellants { get; private set; }  
 
public float GetSpecificImpulse(float atmosphere)  
{  
if (module is ModuleEngines)  
{  
return (module as ModuleEngines).atmosphereCurve.Evaluate(atmosphere);  
}  
return 0.0f;  
}  
 
private void SetModuleEngines()  
{  
ModuleEngines engine = module as ModuleEngines;  
if (engine == null)  
{  
return;  
}  
 
MaximumThrust = engine.maxThrust * (engine.thrustPercentage * 0.01);  
MinimumThrust = engine.minThrust;  
Propellants = engine.propellants;  
}  
}  
}  
}  
//  
// Kerbal Engineer Redux  
//  
// Copyright (C) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
namespace KerbalEngineer.Extensions  
{  
public static class PartResourceExtensions  
{  
#region Methods: public  
 
/// <summary>  
/// Gets the cost of the resource.  
/// </summary>  
public static double GetCost(this PartResource resource)  
{  
return resource.amount * resource.info.unitCost;  
}  
 
/// <summary>  
/// Gets the definition object for the resource.  
/// </summary>  
public static PartResourceDefinition GetDefinition(this PartResource resource)  
{  
return PartResourceLibrary.Instance.GetDefinition(resource.info.id);  
}  
 
/// <summary>  
/// Gets the density of the resource.  
/// </summary>  
public static double GetDensity(this PartResource resource)  
{  
return resource.GetDefinition().density;  
}  
 
/// <summary>  
/// Gets the mass of the resource.  
/// </summary>  
public static double GetMass(this PartResource resource)  
{  
return resource.amount * resource.GetDensity();  
}  
 
#endregion  
}  
}  
//  
// Kerbal Engineer Redux  
//  
// Copyright (C) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
#region Using Directives  
 
using UnityEngine;  
 
#endregion  
 
namespace KerbalEngineer.Extensions  
{  
public static class RectExtensions  
{  
/// <summary>  
/// Clamps the rectangle inside the screen region.  
/// </summary>  
public static Rect ClampInsideScreen(this Rect value)  
{  
value.x = Mathf.Clamp(value.x, 0, Screen.width - value.width);  
value.y = Mathf.Clamp(value.y, 0, Screen.height - value.height);  
 
return value;  
}  
 
/// <summary>  
/// Clamps the rectangle into the screen region by the specified margin.  
/// </summary>  
public static Rect ClampToScreen(this Rect value, float margin = 25.0f)  
{  
value.x = Mathf.Clamp(value.x, -(value.width - margin), Screen.width - margin);  
value.y = Mathf.Clamp(value.y, -(value.height - margin), Screen.height - margin);  
 
return value;  
}  
 
/// <summary>  
/// Returns whether the mouse is within the coordinates of this rectangle.  
/// </summary>  
public static bool MouseIsOver(this Rect value)  
{  
return value.Contains(new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y));  
}  
 
public static Rect Translate(this Rect value, Rect rectangle)  
{  
value.x += rectangle.x;  
value.y += rectangle.y;  
 
return value;  
}  
}  
}  
//  
// 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  
//  
// Copyright (C) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
#region Using Directives  
 
using System;  
 
using UnityEngine;  
 
#endregion  
 
namespace KerbalEngineer.Flight  
{  
using KSP.UI.Screens;  
 
/// <summary>  
/// Graphical controller for section interaction in the form of a menu system.  
/// </summary>  
[KSPAddon(KSPAddon.Startup.Flight, false)]  
public class ActionMenu : MonoBehaviour  
{  
#region Fields  
 
private ActionMenuGui actionMenuGui;  
private ApplicationLauncherButton button;  
 
#endregion  
 
#region Methods: protected  
 
protected void Awake()  
{  
try  
{  
GameEvents.onGUIApplicationLauncherReady.Add(this.OnGuiAppLauncherReady);  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
Logger.Log("ActionMenu was created.");  
}  
 
protected void Start()  
{  
if (button == null)  
{  
OnGuiAppLauncherReady();  
}  
}  
 
protected void OnDestroy()  
{  
try  
{  
GameEvents.onGUIApplicationLauncherReady.Remove(this.OnGuiAppLauncherReady);  
GameEvents.onHideUI.Remove(this.OnHide);  
GameEvents.onShowUI.Remove(this.OnShow);  
if (button != null)  
{  
ApplicationLauncher.Instance.RemoveModApplication(this.button);  
}  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
Logger.Log("ActionMenu was destroyed.");  
}  
 
protected void Update()  
{  
try  
{  
if (this.button == null)  
{  
return;  
}  
if (FlightEngineerCore.IsDisplayable && this.button.toggleButton.Interactable == false)  
{  
this.button.Enable();  
}  
else if (!FlightEngineerCore.IsDisplayable && this.button.toggleButton.Interactable)  
{  
this.button.Disable();  
}  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
#endregion  
 
#region Methods: private  
 
private void OnFalse()  
{  
try  
{  
this.actionMenuGui.enabled = false;  
this.actionMenuGui.StayOpen = false;  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
private void OnGuiAppLauncherReady()  
{  
try  
{  
this.button = ApplicationLauncher.Instance.AddModApplication(  
this.OnTrue,  
this.OnFalse,  
this.OnHover,  
this.OnHoverOut,  
null,  
null,  
ApplicationLauncher.AppScenes.ALWAYS,  
GameDatabase.Instance.GetTexture("KerbalEngineer/Textures/ToolbarIcon", false));  
this.actionMenuGui = this.button.gameObject.AddComponent<ActionMenuGui>();  
this.actionMenuGui.transform.parent = this.button.transform;  
ApplicationLauncher.Instance.EnableMutuallyExclusive(this.button);  
GameEvents.onHideUI.Add(this.OnHide);  
GameEvents.onShowUI.Add(this.OnShow);  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
private void OnHide()  
{  
try  
{  
this.actionMenuGui.Hidden = true;  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
private void OnHover()  
{  
try  
{  
this.actionMenuGui.enabled = true;  
this.actionMenuGui.Hovering = true;  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
private void OnHoverOut()  
{  
try  
{  
this.actionMenuGui.Hovering = false;  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
private void OnShow()  
{  
try  
{  
this.actionMenuGui.Hidden = false;  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
private void OnTrue()  
{  
try  
{  
this.actionMenuGui.enabled = true;  
this.actionMenuGui.StayOpen = true;  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
#endregion  
}  
}  
//  
// Kerbal Engineer Redux  
//  
// Copyright (C) 2014 CYBUTEK  
//  
// This program is free software: you can redistribute it and/or modify  
// it under the terms of the GNU General Public License as published by  
// the Free Software Foundation, either version 3 of the License, or  
// (at your option) any later version.  
//  
// This program is distributed in the hope that it will be useful,  
// but WITHOUT ANY WARRANTY; without even the implied warranty of  
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
// GNU General Public License for more details.  
//  
// You should have received a copy of the GNU General Public License  
// along with this program. If not, see <http://www.gnu.org/licenses/>.  
//  
 
#region Using Directives  
 
using System;  
using System.Collections.Generic;  
 
using KerbalEngineer.Flight.Sections;  
 
using UnityEngine;  
 
#endregion  
 
namespace KerbalEngineer.Flight  
{  
public class ActionMenuGui : MonoBehaviour  
{  
#region Fields  
 
private int numberOfSections;  
private Rect position = new Rect(Screen.width, 38.0f, 300.0f, 0);  
 
#endregion  
 
#region Properties  
 
public bool StayOpen { get; set; }  
 
public bool Hovering { get; set; }  
 
public bool Hidden { get; set; }  
 
#endregion  
 
#region Initialisation  
 
private void Awake()  
{  
try  
{  
this.enabled = false;  
Logger.Log("ActionMenuGui was created.");  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
private void Start()  
{  
try  
{  
this.InitialiseStyles();  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
#endregion  
 
#region GUIStyles  
 
private GUIStyle buttonStyle;  
private GUIStyle windowStyle;  
 
/// <summary>  
/// Initialises all the styles required for this object.  
/// </summary>  
private void InitialiseStyles()  
{  
try  
{  
this.windowStyle = new GUIStyle  
{  
border = new RectOffset(10, 0, 20, 10),  
margin = new RectOffset(0, 0, 3, 0),  
padding = new RectOffset(5, 5, 26, 5),  
normal =  
{  
background = GameDatabase.Instance.GetTexture("KerbalEngineer/Textures/ToolbarBackground", false)  
}  
};  
 
this.buttonStyle = new GUIStyle(HighLogic.Skin.button)  
{  
normal =  
{  
textColor = Color.white,  
},  
margin = new RectOffset(),  
padding = new RectOffset(),  
alignment = TextAnchor.MiddleCenter,  
fontSize = 11,  
fontStyle = FontStyle.Bold,  
fixedHeight = 20.0f,  
};  
}  
catch (Exception ex)  
{  
Logger.Exception(ex, "ActionMenu->InitialiseStyles");  
}  
}  
 
#endregion  
 
#region Drawing  
 
/// <summary>  
/// Called to draw the menu when the UI is enabled.  
/// </summary>  
private void OnGUI()  
{  
try  
{  
if (this.Hidden || !FlightEngineerCore.IsDisplayable)  
{  
return;  
}  
 
if (!this.position.Contains(Event.current.mousePosition) && !this.StayOpen && !this.Hovering)  
{  
this.enabled = false;  
return;  
}  
 
if (this.numberOfSections < SectionLibrary.NumberOfSections)  
{  
this.numberOfSections = SectionLibrary.NumberOfSections;  
}  
else if (this.numberOfSections > SectionLibrary.NumberOfSections)  
{  
this.numberOfSections = SectionLibrary.NumberOfSections;  
this.position.height = 0;  
}  
 
GUI.skin = null;  
this.position.x = Mathf.Clamp(Screen.width * 0.5f + this.transform.parent.position.x - 19.0f, Screen.width * 0.5f, Screen.width - this.position.width);  
this.position = GUILayout.Window(this.GetInstanceID(), this.position, this.Window, string.Empty, this.windowStyle);  
}  
catch (Exception ex)  
{  
Logger.Exception(ex);  
}  
}  
 
/// <summary>  
/// Draws the menu window.  
/// </summary>  
private void Window(int windowId)  
{  
try  
{  
GUILayout.BeginVertical();  
 
this.DrawControlBarButton();  
GUILayout.Space(5.0f);  
this.DrawSections(SectionLibrary.StockSections);  
this.DrawSections(SectionLibrary.CustomSections); &nb