Example #1
0
 public override void OnStart(PartModule.StartState state)
 {
     base.OnStart(state);
     FARActive = AssemblyLoader.loadedAssemblies.Any(a => a.assembly.GetName().Name.Equals("FerramAerospaceResearch", StringComparison.InvariantCultureIgnoreCase));
     // This line breaks the plugin :(
     if (FARActive)
     {
         foreach (BaseField f in Fields)
         {
             f.guiActive = false;
         }
         foreach (BaseEvent e in Events)
         {
             e.active          = false;
             e.guiActive       = false;
             e.guiActiveEditor = false;
         }
         foreach (BaseAction a in Actions)
         {
             a.active = false;
         }
         this.enabled = false;
     }
     else
     {
         //winglet = part.Modules.OfType<ControlSurface>().FirstOrDefault();
         winglet      = part as ControlSurface;
         defaultRange = winglet.ctrlSurfaceRange;
         if (!currentControlRangeSet)
         {
             currentControlRange    = defaultRange;
             currentControlRangeSet = true;
         }
     }
 }
 // Use this for initialization
 void Start()
 {
     LocalWing = GetComponent<Wing>();
     LocalControlSurface = GetComponent<ControlSurface>();
     LocalPropWash = GetComponent<PropWash>();
     LocalGroundEffect = GetComponent<GroundEffect>();
 }
    private void OnEnable()
    {
        targetControlSurface = target as ControlSurface;

        // Instantiate undoManager
        UndoManager = new HOEditorUndoManager(targetControlSurface, "ControlSurface");
    }
Example #4
0
 private void addChildItemToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (TreeViewHierarchy.SelectedNode != null)
     {
         ControlSurface surface  = TreeViewHierarchy.SelectedNode.Tag as ControlSurface;
         AirplaneModel  airplane = TreeViewHierarchy.Nodes[0].Tag as AirplaneModel;
         if (surface != null)
         {
             RCSim.DataClasses.AircraftParameters.ControlSurface surfaceDef = new RCSim.DataClasses.AircraftParameters.ControlSurface();
             if (surface.SurfaceDefinition.ChildControlSurfaces == null)
             {
                 surface.SurfaceDefinition.ChildControlSurfaces = new List <RCSim.DataClasses.AircraftParameters.ControlSurface>();
             }
             surface.SurfaceDefinition.ChildControlSurfaces.Add(surfaceDef);
             ControlSurface newSurface = new ControlSurface(surfaceDef, surface.AirplaneControl);
             surface.AddChild(newSurface);
         }
         else if (airplane != null)
         {
             RCSim.DataClasses.AircraftParameters.ControlSurface surfaceDef = new RCSim.DataClasses.AircraftParameters.ControlSurface();
             ModelControl.AirplaneModel.AirplaneControl.AircraftParameters.ControlSurfaces.Add(surfaceDef);
             ControlSurface newSurface = new ControlSurface(surfaceDef, airplane.AirplaneControl);
             airplane.AddChild(newSurface);
         }
         BuildTreeView(airplane);
     }
 }
Example #5
0
 // Use this for initialization
 void Start()
 {
     LocalWing           = GetComponent <Wing>();
     LocalControlSurface = GetComponent <ControlSurface>();
     LocalPropWash       = GetComponent <PropWash>();
     LocalGroundEffect   = GetComponent <GroundEffect>();
 }
        private void RotateSurface(ControlSurface surface, Quaternion rotation)
        {
            // Create a target which is the surface's original rotation, rotated by the input.
            Quaternion target = surface.originalLocalRotation * rotation;

            // Slerp the surface's rotation towards the target rotation.
            //surface.transform.localRotation = Quaternion.Slerp(surface.transform.localRotation, target, m_Smoothing*Time.deltaTime);
        }
    void RotateSurface(ControlSurface surface, Quaternion rotation)
    {
        // Create a target which is the surface's original rotation, rotated by the input.
        Quaternion target = surface.originalLocalRotation * rotation;

        // Slerp the surface's rotation towards the target rotation.
        surface.transform.localRotation = Quaternion.Slerp(surface.transform.localRotation, target, smoothing * Time.deltaTime);
    }
Example #8
0
 // Use this for initialization
 public void Start()
 {
     WingBoxCollider        = (BoxCollider)gameObject.collider;
     Parent                 = transform.root.gameObject.GetComponent <Rigidbody>();
     ParentAircraft         = transform.root.gameObject.GetComponent <Aircraft>();
     AttachedControlSurface = gameObject.GetComponent <ControlSurface>();
     AttachedPropWash       = gameObject.GetComponent <PropWash>();
     AttachedGroundEffect   = gameObject.GetComponent <GroundEffect>();
 }
    private void TryMoveAllControlSurfaces()
    {
        for (int i = 0; i < _vehicle.Parts.Count; i++)
        {
            if (_vehicle.Parts[i] is ControlSurface)
            {
                ControlSurface controlSurface = (ControlSurface)_vehicle.Parts[i];

                controlSurface.SurfaceControls.TryMove(controlSurface.SurfaceControls.GetMoveInput(), _SASEnabled, _SASStrength);
            }
        }
    }
Example #10
0
 private void surfacePropertiesControl_FileChanged(object sender, EventArgs e)
 {
     if (TreeViewHierarchy.SelectedNode != null)
     {
         ControlSurface surface  = TreeViewHierarchy.SelectedNode.Tag as ControlSurface;
         AirplaneModel  airplane = TreeViewHierarchy.Nodes[0].Tag as AirplaneModel;
         if (surface != null)
         {
             TreeViewHierarchy.SelectedNode.Text = GetNodeName(surface.MeshFileName);
         }
         else if (airplane != null)
         {
             TreeViewHierarchy.SelectedNode.Text = GetNodeName(airplane.MeshFileName);
         }
     }
 }
Example #11
0
 private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (TreeViewHierarchy.SelectedNode != null)
     {
         ControlSurface surface  = TreeViewHierarchy.SelectedNode.Tag as ControlSurface;
         AirplaneModel  airplane = TreeViewHierarchy.Nodes[0].Tag as AirplaneModel;
         if ((surface != null) && (airplane != null))
         {
             ControlSurface parentSurface = surface.Parent as ControlSurface;
             if (parentSurface != null)
             {
                 foreach (RCSim.DataClasses.AircraftParameters.ControlSurface child in parentSurface.SurfaceDefinition.ChildControlSurfaces)
                 {
                     if (child == surface.SurfaceDefinition)
                     {
                         parentSurface.SurfaceDefinition.ChildControlSurfaces.Remove(child);
                         if (parentSurface.SurfaceDefinition.ChildControlSurfaces.Count == 0)
                         {
                             parentSurface.SurfaceDefinition.ChildControlSurfaces = null;
                         }
                         break;
                     }
                 }
             }
             else if (surface.Parent == airplane)
             {
                 foreach (RCSim.DataClasses.AircraftParameters.ControlSurface child in airplane.AirplaneControl.AircraftParameters.ControlSurfaces)
                 {
                     if (child == surface.SurfaceDefinition)
                     {
                         airplane.AirplaneControl.AircraftParameters.ControlSurfaces.Remove(child);
                         break;
                     }
                 }
             }
             surface.Parent.RemoveChild(surface);
             surface.Dispose();
             BuildTreeView(airplane);
         }
     }
 }
Example #12
0
 protected void AddChildren(GameObject gameObject, TreeNode treeNode)
 {
     foreach (GameObject child in gameObject.Children)
     {
         ControlSurface surface = child as ControlSurface;
         if (surface != null)
         {
             TreeNode node;
             if (surface.Name != null)
             {
                 node = new TreeNode(GetNodeName(surface.Name));
             }
             else
             {
                 node = new TreeNode("empty");
             }
             node.Tag = surface;
             AddChildren(surface, node);
             treeNode.Nodes.Add(node);
         }
     }
 }
        private void RotateSurface(ControlSurface surface, Quaternion rotation)
        {
            Quaternion target = surface.originalLocalRotation * rotation;

            surface.transform.localRotation = Quaternion.Slerp(surface.transform.localRotation, target, m_Smoothing * Time.deltaTime);
        }
Example #14
0
    // Update is called once per frame
    void Update()
    {
        //Make sure we have a parent wing before we try and do anything and also make sure they are similarly parented.
        if ((null != ParentWing) && (transform.root.gameObject == ParentWing.transform.root.gameObject))
        {
            //Do not try and copy self.
            if (this == ParentWing)
            {
                return;
            }

            //Copy name ( only if changed )
            string newName = ParentWing.name + "(Mirror)";
            if (gameObject.name != newName)
            {
                gameObject.name = newName;
            }

            //First copy transforms..
            transform.localScale    = new Vector3(-ParentWing.transform.localScale.x, ParentWing.transform.localScale.y, ParentWing.transform.localScale.z);
            transform.localPosition = ParentWing.transform.localPosition;
            transform.localPosition = new Vector3(-transform.localPosition.x, transform.localPosition.y, transform.localPosition.z);

            transform.localRotation = new Quaternion(-ParentWing.transform.localRotation.x,
                                                     ParentWing.transform.localRotation.y,
                                                     ParentWing.transform.localRotation.z,
                                                     ParentWing.transform.localRotation.w * -1.0f);

            //Copy wing
            if (!LocalWing && ParentWing)
            {
                LocalWing = gameObject.AddComponent <Wing>();
            }
            if (LocalWing && ParentWing)
            {
                LocalWing.SectionCount          = ParentWing.SectionCount;
                LocalWing.WingTipWidthZeroToOne = ParentWing.WingTipWidthZeroToOne;
                LocalWing.WingTipSweep          = ParentWing.WingTipSweep;
                LocalWing.WingTipAngle          = ParentWing.WingTipAngle;
                LocalWing.Aerofoil   = ParentWing.Aerofoil;
                LocalWing.CDOverride = ParentWing.CDOverride;
            }
            else if (LocalWing && !ParentWing)
            {
                //deleted on parent since copying.
                DestroyImmediate(LocalWing);
            }

            //Copy control surface
            ControlSurface parentControlSurface = ParentWing.GetComponent <ControlSurface>();
            if (!LocalControlSurface && parentControlSurface)
            {
                LocalControlSurface = gameObject.AddComponent <ControlSurface>();
            }
            if (LocalControlSurface && parentControlSurface)
            {
                //string previousLocalAxisName = LocalControlSurface.AxisName;
                GameObject previousModel        = LocalControlSurface.Model;
                Vector3    previousRotationAxis = LocalControlSurface.ModelRotationAxis;

                LocalControlSurface.MaxDeflectionDegrees = parentControlSurface.MaxDeflectionDegrees;
                LocalControlSurface.RootHingeDistanceFromTrailingEdge = parentControlSurface.RootHingeDistanceFromTrailingEdge;
                LocalControlSurface.TipHingeDistanceFromTrailingEdge  = parentControlSurface.TipHingeDistanceFromTrailingEdge;
                LocalControlSurface.AffectedSections  = parentControlSurface.AffectedSections;
                LocalControlSurface.Model             = parentControlSurface.Model;
                LocalControlSurface.ModelRotationAxis = parentControlSurface.ModelRotationAxis;

                //Keep the following unique.
                LocalControlSurface.Model             = previousModel;
                LocalControlSurface.ModelRotationAxis = previousRotationAxis;
            }
            else if (LocalControlSurface && !parentControlSurface)
            {
                //deleted on parent since copying.
                DestroyImmediate(LocalControlSurface);
            }

            //Copy propwash
            PropWash parentPropWash = ParentWing.GetComponent <PropWash>();
            if (!LocalPropWash && parentPropWash)
            {
                LocalPropWash = gameObject.AddComponent <PropWash>();
            }
            if (LocalPropWash && parentPropWash)
            {
                Engine previousPropwashSource = LocalPropWash.PropWashSource;

                //Copy everything except propwash source..
                LocalPropWash.AffectedSections = parentPropWash.AffectedSections;
                LocalPropWash.PropWashSource   = parentPropWash.PropWashSource;
                LocalPropWash.PropWashStrength = parentPropWash.PropWashStrength;

                //Keep unique
                LocalPropWash.PropWashSource = previousPropwashSource;
            }
            else if (LocalPropWash && !parentPropWash)
            {
                //deleted on parent since copying.
                DestroyImmediate(LocalPropWash);
            }

            //Copy groundeffect.
            GroundEffect parentGroundEffect = ParentWing.GetComponent <GroundEffect>();
            if (!LocalGroundEffect && parentGroundEffect)
            {
                LocalGroundEffect = gameObject.AddComponent <GroundEffect>();
            }
            if (LocalGroundEffect && parentGroundEffect)
            {
                //Copy everything..
                LocalGroundEffect.CLHeightVsChord = parentGroundEffect.CLHeightVsChord;
                LocalGroundEffect.CDHeightVsSpan  = parentGroundEffect.CDHeightVsSpan;
                LocalGroundEffect.RayCastAxis     = parentGroundEffect.RayCastAxis;
                LocalGroundEffect.RayCastLayers   = parentGroundEffect.RayCastLayers;
                LocalGroundEffect.Wingspan        = parentGroundEffect.Wingspan;
            }
            else if (LocalGroundEffect && !parentGroundEffect)
            {
                //deleted on parent since copying.
                DestroyImmediate(LocalGroundEffect);
            }
        }
    }
 public override void OnStart(PartModule.StartState state)
 {
     base.OnStart(state);
     FARActive = AssemblyLoader.loadedAssemblies.Any(a => a.assembly.GetName().Name.Equals("FerramAerospaceResearch", StringComparison.InvariantCultureIgnoreCase));
     // This line breaks the plugin :(
     if (FARActive)
     {
         foreach (BaseField f in Fields)
         {
             f.guiActive = false;
         }
         foreach (BaseEvent e in Events)
         {
             e.active = false;
             e.guiActive = false;
             e.guiActiveEditor = false;
         }
         foreach (BaseAction a in Actions)
         {
             a.active = false;
         }
         this.enabled = false;
     }
     else
     {
         //winglet = part.Modules.OfType<ControlSurface>().FirstOrDefault();
         winglet = part as ControlSurface;
         defaultRange = winglet.ctrlSurfaceRange;
         if (!currentControlRangeSet)
         {
             currentControlRange = defaultRange;
             currentControlRangeSet = true;
         }
     }
 }
    private void OnEnable()
    {
        targetControlSurface = target as ControlSurface;

        // Instantiate undoManager
        UndoManager = new HOEditorUndoManager( targetControlSurface, "ControlSurface" );
    }
Example #17
0
    public override void OnStart(PartModule.StartState state)
    {
        debug.debugMode = debugMode;

        FARActive = AssemblyLoader.loadedAssemblies.Any(a => a.assembly.GetName().Name.Equals("FerramAerospaceResearch", StringComparison.InvariantCultureIgnoreCase));
        // This line breaks the plugin :(
        if (FARActive)
        {
            foreach (BaseField f in Fields)
            {
                f.guiActive = false;
            }
            foreach (BaseEvent e in Events)
            {
                e.active = false;
                e.guiActive = false;
                e.guiActiveEditor = false;
            }
            foreach (BaseAction a in Actions)
            {
                a.active = false;
            }
            this.enabled = false;
            return;
        }

        //debug.debugMessage("FSwing OnStart: " + part.name);

        #region fligth mode

        if (HighLogic.LoadedSceneIsFlight)
        {

            findTransforms(true);

            // Check if a stock wing module is present, if not, manipulate FSliftSurface stuff instead.
            if (affectStockWingModule)
            {
                //Debug.Log("FSwing: getting stock wing module");
                stockWingModule = part as ControlSurface;
                if (stockWingModule != null)
                {
                    //Debug.Log("FSwing: success");
                }
                else
                {
                    debug.debugMessage("FSwing: did not Find stock wing module");
                    affectStockWingModule = false;
                }
            }

            // get the main lift surface for the leading edge to manipulate
            if (affectStockWingModule)
            {
                useCtrlSrf = false;
            }
            else
            {
                FSliftSurface[] surfaces = part.GetComponents<FSliftSurface>();
                foreach (FSliftSurface surface in surfaces)
                {
                    if (surface.liftTransformName == leadingEdgeLiftSurface)
                    {
                        mainLift = surface;
                        mainLiftAreaDefault = surface.wingArea;
                        //Debug.Log("FSwing: Slat assigned main lift to: " + surface.liftTransformName);
                        break;
                    }
                }
                if (mainLift == null) debug.debugMessage("FSwing: leading edge missing main FSliftSurface: " + leadingEdgeLiftSurface);
            }
        }
        #endregion

        #region help popup

        helpPopup = new Firespitter.gui.HelpPopup("Wing setup help", helpTextInternal);

        /*helpSection = new PopupSection();
        PopupElement helpText = new PopupElement(helpTextnternal, true);
        helpSection.AddElement(helpText, 300f);
        if (windowID == 0)
            windowID = FSGUIwindowID.getNextID();
        helpPopup = new FSGUIPopup(part, "FSwing", 0, windowID, windowRect, "Wing setup help");
        helpPopup.sections.Add(helpSection);
        helpPopup.useInEditor = true;
        helpPopup.useInFlight = true;*/

        #endregion

        originalCtrlSurfaceRange = ctrlSurfaceRange;

        if (affectStockWingModule || !showTweakables)
        {
            Fields["pitchResponse"].guiActive = false;
            Fields["pitchResponse"].guiActiveEditor = false;
            Fields["rollResponse"].guiActive = false;
            Fields["rollResponse"].guiActiveEditor = false;
            Fields["yawResponse"].guiActive = false;
            Fields["yawResponse"].guiActiveEditor = false;
            Fields["flapResponse"].guiActive = false;
            Fields["flapResponse"].guiActiveEditor = false;
        }

        ApplyDamage(partHealth);
    }
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
        VehiclePart       part   = (VehiclePart)target;
        VehiclePartConfig config = part.PartConfig;
        Type desiredConfig       = _partConfigDict[part.GetType()];

        if (config == null || config.GetType() != desiredConfig)
        {
            EditorGUILayout.HelpBox("Wrong config type! Use " + desiredConfig, MessageType.Error);
        }

        if (GUILayout.Button("Mirror (" + part.Mirrored + ")"))
        {
            part.Mirrored = !part.Mirrored;
            EditorUtility.SetDirty(part);
            SceneView.RepaintAll(); // !! GOD COMMAND
        }

        if (part is Wheel)
        {
            Wheel wheel = part as Wheel;
            if (GUILayout.Button("Generate Wheel Collider"))
            {
                WheelCollider wheelCollider = wheel.WheelCollider;
                if (wheelCollider == null)
                {
                    GameObject wheelColliderObject = new GameObject();
                    wheelColliderObject.transform.SetParent(wheel.Vehicle.transform);
                    wheelColliderObject.transform.localPosition = Vector3.zero;
                    wheelColliderObject.name = "[" + wheel.name + " collider]";
                    wheelCollider            = wheelColliderObject.AddComponent <WheelCollider>();
                }
                Wheel.ImplementConfigValues(ref wheelCollider, wheel.WheelConfig);
                Vector3 offset = wheel.GetUpDirection() * wheel.WheelConfig.suspensionDistance * 0.5f;
                wheelCollider.transform.position = wheel.transform.position + wheel.Vehicle.transform.TransformDirection(offset);
                wheel.WheelCollider = wheelCollider;
                EditorUtility.SetDirty(wheel);
            }
        }

        if (part is ControlSurface)
        {
            ControlSurface moveableStructure = part as ControlSurface;
            if (GUILayout.Button("Save default rotation"))
            {
                moveableStructure.SurfaceControls.SetDefaultLocalRotation(moveableStructure.transform.localEulerAngles);
                EditorUtility.SetDirty(part);
            }
        }

        /*if (part is AerodynamicPart)
         * {
         *  if((part as AerodynamicPart).Aerodynamics == null)
         *  {
         *      EditorGUILayout.HelpBox("No aerodynamic data assigned! Click button below.", MessageType.Error);
         *  }
         *  if (GUILayout.Button("Input aerodynamic data"))
         *  {
         *      if (config != null)
         *      {
         *          (part as AerodynamicPart).Aerodynamics = new Aerodynamics(config.aerodynamicsData);
         *      }
         *  }
         * }*/
    }
    public void OnDrawGizmos()
    {
        //Draw icon.
        Gizmos.DrawIcon (transform.position, "wing.png", true);

        WingBoxCollider = (BoxCollider)gameObject.collider;
        if ( null != WingBoxCollider )
        {
            //Clamp box collider scales.
            WingBoxCollider.size = new Vector3( 1.0f, 0.1f, 1.0f );

            UpdateWingGeometry();

            //Wing geometry.
            Gizmos.color = Color.blue;
            Gizmos.DrawLine( WingRootLeadingEdge, WingTipLeadingEdge );

            Gizmos.color = Color.red;
            Gizmos.DrawLine( WingTipTrailingEdge, WingRootTrailingEdge );

            Gizmos.color = Color.blue;
            Gizmos.DrawLine( WingRootTrailingEdge, WingRootLeadingEdge );
            Gizmos.DrawLine( WingTipLeadingEdge, WingTipTrailingEdge );

            //Sections.
            Gizmos.color = Color.blue;
            for ( int i=0; i<SectionCount; i++ )
            {
                Vector3 sectionStart = WingRootTrailingEdge + ( (WingTipTrailingEdge - WingRootTrailingEdge) * (float)i/(float)SectionCount );
                Vector3 sectionEnd = WingRootLeadingEdge + ( (WingTipLeadingEdge - WingRootLeadingEdge) * (float)i/(float)SectionCount );
                Gizmos.DrawLine( sectionStart, sectionEnd );
            }

            //Lift line.
            Gizmos.color = Color.green;
            Gizmos.DrawLine( RootLiftPosition, TipLiftPosition );

            //Aileron hinge
            AttachedControlSurface = gameObject.GetComponent<ControlSurface>();
            if ( null != AttachedControlSurface )
            {
                float rootHingeOffset = AttachedControlSurface.RootHingeDistanceFromTrailingEdge;
                float tipHingeOffset = AttachedControlSurface.TipHingeDistanceFromTrailingEdge;

                Vector3 wingRootAileronHingePos = WingRootTrailingEdge + ( ( WingRootLeadingEdge - WingRootTrailingEdge ) * rootHingeOffset );
                Vector3 wingTipAileronHingePos = WingTipTrailingEdge + ( ( WingTipLeadingEdge - WingTipTrailingEdge ) * tipHingeOffset );

                Gizmos.color = Color.magenta;
                Gizmos.DrawLine( wingRootAileronHingePos, wingTipAileronHingePos );

                //Control surface - Draw crosses over each control surface section which is affected.
                if ( null != AttachedControlSurface.AffectedSections )
                {
                    for ( int i=0; i<AttachedControlSurface.AffectedSections.Length; i++ )
                    {
                        if ( AttachedControlSurface.AffectedSections[i] == true )
                        {
                            Vector3 hingeLeft = wingRootAileronHingePos + ( (wingTipAileronHingePos - wingRootAileronHingePos ) * ((float)i / (float)AttachedControlSurface.AffectedSections.Length) );
                            Vector3 hingeRight = wingRootAileronHingePos + ( (wingTipAileronHingePos - wingRootAileronHingePos ) * ((float)(i+1) / (float)AttachedControlSurface.AffectedSections.Length) );

                            Vector3 backLeft = WingRootTrailingEdge + ( (WingTipTrailingEdge - WingRootTrailingEdge ) * ((float)i / (float)AttachedControlSurface.AffectedSections.Length) );
                            Vector3 backRight = WingRootTrailingEdge + ( (WingTipTrailingEdge - WingRootTrailingEdge ) * ((float)(i+1) / (float)AttachedControlSurface.AffectedSections.Length) );

                            Gizmos.DrawLine( hingeLeft, backRight );
                            Gizmos.DrawLine( hingeRight, backLeft );
                        }
                    }
                }
            }

            //Prop wash - Draw crosses over each control surface section which is affected.
            AttachedPropWash = gameObject.GetComponent<PropWash>();
            if ( null != AttachedPropWash )
            {
                Gizmos.color = Color.cyan;
                if ( null != AttachedPropWash.AffectedSections )
                {
                    for ( int i=0; i<AttachedPropWash.AffectedSections.Length; i++ )
                    {
                        if ( AttachedPropWash.AffectedSections[i] == true )
                        {
                            Vector3 frontLeft = WingRootLeadingEdge + ( (WingTipLeadingEdge - WingRootLeadingEdge ) * ((float)i / (float)AttachedPropWash.AffectedSections.Length) );
                            Vector3 frontRight = WingRootLeadingEdge + ( (WingTipLeadingEdge - WingRootLeadingEdge ) * ((float)(i+1) / (float)AttachedPropWash.AffectedSections.Length) );

                            Vector3 backLeft = WingRootTrailingEdge + ( (WingTipTrailingEdge - WingRootTrailingEdge ) * ((float)i / (float)AttachedPropWash.AffectedSections.Length) );
                            Vector3 backRight = WingRootTrailingEdge + ( (WingTipTrailingEdge - WingRootTrailingEdge ) * ((float)(i+1) / (float)AttachedPropWash.AffectedSections.Length) );

                            //Vector3 topCenter = hingeLeft + ( (hingeRight-hingeLeft) * 0.5f );
                            //Vector3 bottomCenter = backLeft + ( (backRight-backLeft) * 0.5f );
                            ///Vector3 leftCenter = backLeft + ( (hingeLeft-backLeft) * 0.5f );
                            //Vector3 rightCenter = backRight + ( (hingeRight-backRight) * 0.5f );

                            Gizmos.DrawLine( frontLeft, backRight );
                            Gizmos.DrawLine( frontRight, backLeft );
                        }
                    }
                }
            }

        }
    }
Example #20
0
    public override void OnStart(PartModule.StartState state)
    {
        debug.debugMode = debugMode;

        FARActive = AssemblyLoader.loadedAssemblies.Any(a => a.assembly.GetName().Name.Equals("FerramAerospaceResearch", StringComparison.InvariantCultureIgnoreCase));
        // This line breaks the plugin :(
        if (FARActive)
        {
            foreach (BaseField f in Fields)
            {
                f.guiActive = false;
            }
            foreach (BaseEvent e in Events)
            {
                e.active          = false;
                e.guiActive       = false;
                e.guiActiveEditor = false;
            }
            foreach (BaseAction a in Actions)
            {
                a.active = false;
            }
            this.enabled = false;
            return;
        }

        //debug.debugMessage("FSwing OnStart: " + part.name);

        #region fligth mode

        if (HighLogic.LoadedSceneIsFlight)
        {
            findTransforms(true);

            // Check if a stock wing module is present, if not, manipulate FSliftSurface stuff instead.
            if (affectStockWingModule)
            {
                //Debug.Log("FSwing: getting stock wing module");
                stockWingModule = part as ControlSurface;
                if (stockWingModule != null)
                {
                    //Debug.Log("FSwing: success");
                }
                else
                {
                    debug.debugMessage("FSwing: did not Find stock wing module");
                    affectStockWingModule = false;
                }
            }

            // get the main lift surface for the leading edge to manipulate
            if (affectStockWingModule)
            {
                useCtrlSrf = false;
            }
            else
            {
                FSliftSurface[] surfaces = part.GetComponents <FSliftSurface>();
                foreach (FSliftSurface surface in surfaces)
                {
                    if (surface.liftTransformName == leadingEdgeLiftSurface)
                    {
                        mainLift            = surface;
                        mainLiftAreaDefault = surface.wingArea;
                        //Debug.Log("FSwing: Slat assigned main lift to: " + surface.liftTransformName);
                        break;
                    }
                }
                if (mainLift == null)
                {
                    debug.debugMessage("FSwing: leading edge missing main FSliftSurface: " + leadingEdgeLiftSurface);
                }
            }
        }
        #endregion

        #region help popup

        helpPopup = new Firespitter.info.HelpPopup("Wing setup help", helpTextInternal);

        /*helpSection = new PopupSection();
         * PopupElement helpText = new PopupElement(helpTextnternal, true);
         * helpSection.AddElement(helpText, 300f);
         * if (windowID == 0)
         *  windowID = FSGUIwindowID.getNextID();
         * helpPopup = new FSGUIPopup(part, "FSwing", 0, windowID, windowRect, "Wing setup help");
         * helpPopup.sections.Add(helpSection);
         * helpPopup.useInEditor = true;
         * helpPopup.useInFlight = true;*/

        #endregion

        originalCtrlSurfaceRange = ctrlSurfaceRange;

        if (affectStockWingModule || !showTweakables)
        {
            Fields["pitchResponse"].guiActive       = false;
            Fields["pitchResponse"].guiActiveEditor = false;
            Fields["rollResponse"].guiActive        = false;
            Fields["rollResponse"].guiActiveEditor  = false;
            Fields["yawResponse"].guiActive         = false;
            Fields["yawResponse"].guiActiveEditor   = false;
            Fields["flapResponse"].guiActive        = false;
            Fields["flapResponse"].guiActiveEditor  = false;
        }

        ApplyDamage(partHealth);
    }
Example #21
0
    // Update is called once per frame
    void Update()
    {
        //Make sure we have a parent wing before we try and do anything and also make sure they are similarly parented.
        if ( (null != ParentWing) && (transform.root.gameObject == ParentWing.transform.root.gameObject) )
        {
            //Do not try and copy self.
            if ( this == ParentWing )
            {
                return;
            }

            //Copy name..
            gameObject.name = ParentWing.name + "(Mirror)";

            //First copy transforms..
            transform.localScale = new Vector3( -ParentWing.transform.localScale.x, ParentWing.transform.localScale.y, ParentWing.transform.localScale.z );
            transform.localPosition = ParentWing.transform.localPosition;
            transform.localPosition = new Vector3( -transform.localPosition.x, transform.localPosition.y, transform.localPosition.z );

            transform.localRotation = new Quaternion( -ParentWing.transform.localRotation.x,
                                                        ParentWing.transform.localRotation.y,
                                                        ParentWing.transform.localRotation.z,
                                                        ParentWing.transform.localRotation.w * -1.0f);

            //Copy wing
            if ( !LocalWing && ParentWing )
            {
                LocalWing = gameObject.AddComponent<Wing>();
            }

            if ( LocalWing )
            {
                //EditorUtility.CopySerialized( ParentWing, LocalWing ); //**CRASHES ON 3.5

                LocalWing.SectionCount = ParentWing.SectionCount;
                LocalWing.WingTipWidthZeroToOne = ParentWing.WingTipWidthZeroToOne;
                LocalWing.WingTipSweep = ParentWing.WingTipSweep;
                LocalWing.WingTipAngle = ParentWing.WingTipAngle;
                LocalWing.Aerofoil = ParentWing.Aerofoil;
                LocalWing.CDOverride = ParentWing.CDOverride;
            }

            //Copy control surface
            ControlSurface parentControlSurface = ParentWing.GetComponent<ControlSurface>();
            if (!LocalControlSurface && parentControlSurface )
            {
                LocalControlSurface = gameObject.AddComponent<ControlSurface>();
            }
            if ( LocalControlSurface )
            {
                //string previousLocalAxisName = LocalControlSurface.AxisName;
                bool previousLocalInvert = LocalControlSurface.Invert;
                GameObject previousModel = LocalControlSurface.Model;
                Vector3 previousRotationAxis = LocalControlSurface.ModelRotationAxis;

                //EditorUtility.CopySerialized( parentControlSurface, LocalControlSurface ); //**CRASHES ON 3.5

                LocalControlSurface.AxisName = parentControlSurface.AxisName;
                LocalControlSurface.Invert = parentControlSurface.Invert;
                LocalControlSurface.MaxDeflectionDegrees = parentControlSurface.MaxDeflectionDegrees;
                LocalControlSurface.RootHingeDistanceFromTrailingEdge = parentControlSurface.RootHingeDistanceFromTrailingEdge;
                LocalControlSurface.TipHingeDistanceFromTrailingEdge = parentControlSurface.TipHingeDistanceFromTrailingEdge;
                LocalControlSurface.AffectedSections = parentControlSurface.AffectedSections;
                LocalControlSurface.Model = parentControlSurface.Model;
                LocalControlSurface.ModelRotationAxis = parentControlSurface.ModelRotationAxis;

                //Keep the following unique.
                //LocalControlSurface.AxisName = previousLocalAxisName;
                LocalControlSurface.Invert = previousLocalInvert;
                LocalControlSurface.Model = previousModel;
                LocalControlSurface.ModelRotationAxis = previousRotationAxis;
            }

            //Copy propwash
            PropWash parentPropWash = ParentWing.GetComponent<PropWash>();
            if (!LocalPropWash && parentPropWash )
            {
                LocalPropWash = gameObject.AddComponent<PropWash>();
            }
            if ( LocalPropWash )
            {
                Engine previousPropwashSource = LocalPropWash.PropWashSource;

                //Copy everything except propwash source..
                LocalPropWash.AffectedSections = parentPropWash.AffectedSections;
                LocalPropWash.PropWashSource = parentPropWash.PropWashSource;
                LocalPropWash.PropWashStrength = parentPropWash.PropWashStrength;

                //Keep unique
                LocalPropWash.PropWashSource = previousPropwashSource;
            }
        }
    }
Example #22
0
    public void OnDrawGizmos()
    {
        //Draw icon.
        Gizmos.DrawIcon(transform.position, "wing.png", true);

        WingBoxCollider = (BoxCollider)gameObject.collider;
        if (null != WingBoxCollider)
        {
            //Clamp box collider scales.
            WingBoxCollider.size = new Vector3(1.0f, 0.1f, 1.0f);

            UpdateWingGeometry();

            //Wing geometry.
            Gizmos.color = Color.blue;
            Gizmos.DrawLine(WingRootLeadingEdge, WingTipLeadingEdge);

            Gizmos.color = Color.red;
            Gizmos.DrawLine(WingTipTrailingEdge, WingRootTrailingEdge);

            Gizmos.color = Color.blue;
            Gizmos.DrawLine(WingRootTrailingEdge, WingRootLeadingEdge);
            Gizmos.DrawLine(WingTipLeadingEdge, WingTipTrailingEdge);


            //Sections.
            Gizmos.color = Color.blue;
            for (int i = 0; i < SectionCount; i++)
            {
                Vector3 sectionStart = WingRootTrailingEdge + ((WingTipTrailingEdge - WingRootTrailingEdge) * (float)i / (float)SectionCount);
                Vector3 sectionEnd   = WingRootLeadingEdge + ((WingTipLeadingEdge - WingRootLeadingEdge) * (float)i / (float)SectionCount);
                Gizmos.DrawLine(sectionStart, sectionEnd);
            }

            //Lift line.
            Gizmos.color = Color.green;
            Gizmos.DrawLine(RootLiftPosition, TipLiftPosition);

            //Aileron hinge
            AttachedControlSurface = gameObject.GetComponent <ControlSurface>();
            if (null != AttachedControlSurface)
            {
                float rootHingeOffset = AttachedControlSurface.RootHingeDistanceFromTrailingEdge;
                float tipHingeOffset  = AttachedControlSurface.TipHingeDistanceFromTrailingEdge;

                Vector3 wingRootAileronHingePos = WingRootTrailingEdge + ((WingRootLeadingEdge - WingRootTrailingEdge) * rootHingeOffset);
                Vector3 wingTipAileronHingePos  = WingTipTrailingEdge + ((WingTipLeadingEdge - WingTipTrailingEdge) * tipHingeOffset);

                Gizmos.color = Color.magenta;
                Gizmos.DrawLine(wingRootAileronHingePos, wingTipAileronHingePos);

                //Control surface - Draw crosses over each control surface section which is affected.
                if (null != AttachedControlSurface.AffectedSections)
                {
                    for (int i = 0; i < AttachedControlSurface.AffectedSections.Length; i++)
                    {
                        if (AttachedControlSurface.AffectedSections[i] == true)
                        {
                            Vector3 hingeLeft  = wingRootAileronHingePos + ((wingTipAileronHingePos - wingRootAileronHingePos) * ((float)i / (float)AttachedControlSurface.AffectedSections.Length));
                            Vector3 hingeRight = wingRootAileronHingePos + ((wingTipAileronHingePos - wingRootAileronHingePos) * ((float)(i + 1) / (float)AttachedControlSurface.AffectedSections.Length));

                            Vector3 backLeft  = WingRootTrailingEdge + ((WingTipTrailingEdge - WingRootTrailingEdge) * ((float)i / (float)AttachedControlSurface.AffectedSections.Length));
                            Vector3 backRight = WingRootTrailingEdge + ((WingTipTrailingEdge - WingRootTrailingEdge) * ((float)(i + 1) / (float)AttachedControlSurface.AffectedSections.Length));

                            Gizmos.DrawLine(hingeLeft, backRight);
                            Gizmos.DrawLine(hingeRight, backLeft);
                        }
                    }
                }
            }

            //Prop wash - Draw crosses over each control surface section which is affected.
            AttachedPropWash = gameObject.GetComponent <PropWash>();
            if (null != AttachedPropWash)
            {
                Gizmos.color = Color.cyan;
                if (null != AttachedPropWash.AffectedSections)
                {
                    for (int i = 0; i < AttachedPropWash.AffectedSections.Length; i++)
                    {
                        if (AttachedPropWash.AffectedSections[i] == true)
                        {
                            Vector3 frontLeft  = WingRootLeadingEdge + ((WingTipLeadingEdge - WingRootLeadingEdge) * ((float)i / (float)AttachedPropWash.AffectedSections.Length));
                            Vector3 frontRight = WingRootLeadingEdge + ((WingTipLeadingEdge - WingRootLeadingEdge) * ((float)(i + 1) / (float)AttachedPropWash.AffectedSections.Length));

                            Vector3 backLeft  = WingRootTrailingEdge + ((WingTipTrailingEdge - WingRootTrailingEdge) * ((float)i / (float)AttachedPropWash.AffectedSections.Length));
                            Vector3 backRight = WingRootTrailingEdge + ((WingTipTrailingEdge - WingRootTrailingEdge) * ((float)(i + 1) / (float)AttachedPropWash.AffectedSections.Length));

                            //Vector3 topCenter = hingeLeft + ( (hingeRight-hingeLeft) * 0.5f );
                            //Vector3 bottomCenter = backLeft + ( (backRight-backLeft) * 0.5f );
                            ///Vector3 leftCenter = backLeft + ( (hingeLeft-backLeft) * 0.5f );
                            //Vector3 rightCenter = backRight + ( (hingeRight-backRight) * 0.5f );

                            Gizmos.DrawLine(frontLeft, backRight);
                            Gizmos.DrawLine(frontRight, backLeft);
                        }
                    }
                }
            }
        }
    }
    // Update is called once per frame
    void Update()
    {
        //Make sure we have a parent wing before we try and do anything and also make sure they are similarly parented.
        if ( (null != ParentWing) && (transform.root.gameObject == ParentWing.transform.root.gameObject) )
        {
            //Do not try and copy self.
            if ( this == ParentWing )
            {
                return;
            }

            //Copy name ( only if changed )
            string newName = ParentWing.name + "(Mirror)";
            if ( gameObject.name != newName )
            {
                gameObject.name = newName;
            }

            //First copy transforms..
            transform.localScale = new Vector3( -ParentWing.transform.localScale.x, ParentWing.transform.localScale.y, ParentWing.transform.localScale.z );
            transform.localPosition = ParentWing.transform.localPosition;
            transform.localPosition = new Vector3( -transform.localPosition.x, transform.localPosition.y, transform.localPosition.z );

            transform.localRotation = new Quaternion( -ParentWing.transform.localRotation.x,
                                                        ParentWing.transform.localRotation.y,
                                                        ParentWing.transform.localRotation.z,
                                                        ParentWing.transform.localRotation.w * -1.0f);

            //Copy wing
            if ( !LocalWing && ParentWing )
            {
                LocalWing = gameObject.AddComponent<Wing>();
            }
            if ( LocalWing && ParentWing )
            {
                LocalWing.SectionCount = ParentWing.SectionCount;
                LocalWing.WingTipWidthZeroToOne = ParentWing.WingTipWidthZeroToOne;
                LocalWing.WingTipSweep = ParentWing.WingTipSweep;
                LocalWing.WingTipAngle = ParentWing.WingTipAngle;
                LocalWing.Aerofoil = ParentWing.Aerofoil;
                LocalWing.CDOverride = ParentWing.CDOverride;
            }
            else if ( LocalWing && !ParentWing )
            {
                //deleted on parent since copying.
                DestroyImmediate( LocalWing );
            }

            //Copy control surface
            ControlSurface parentControlSurface = ParentWing.GetComponent<ControlSurface>();
            if (!LocalControlSurface && parentControlSurface )
            {
                LocalControlSurface = gameObject.AddComponent<ControlSurface>();
            }
            if ( LocalControlSurface && parentControlSurface )
            {
                //string previousLocalAxisName = LocalControlSurface.AxisName;
                GameObject previousModel = LocalControlSurface.Model;
                Vector3 previousRotationAxis = LocalControlSurface.ModelRotationAxis;

                LocalControlSurface.MaxDeflectionDegrees = parentControlSurface.MaxDeflectionDegrees;
                LocalControlSurface.RootHingeDistanceFromTrailingEdge = parentControlSurface.RootHingeDistanceFromTrailingEdge;
                LocalControlSurface.TipHingeDistanceFromTrailingEdge = parentControlSurface.TipHingeDistanceFromTrailingEdge;
                LocalControlSurface.AffectedSections = parentControlSurface.AffectedSections;
                LocalControlSurface.Model = parentControlSurface.Model;
                LocalControlSurface.ModelRotationAxis = parentControlSurface.ModelRotationAxis;

                //Keep the following unique.
                LocalControlSurface.Model = previousModel;
                LocalControlSurface.ModelRotationAxis = previousRotationAxis;
            }
            else if ( LocalControlSurface && !parentControlSurface )
            {
                //deleted on parent since copying.
                DestroyImmediate( LocalControlSurface );
            }

            //Copy propwash
            PropWash parentPropWash = ParentWing.GetComponent<PropWash>();
            if (!LocalPropWash && parentPropWash )
            {
                LocalPropWash = gameObject.AddComponent<PropWash>();
            }
            if ( LocalPropWash && parentPropWash )
            {
                Engine previousPropwashSource = LocalPropWash.PropWashSource;

                //Copy everything except propwash source..
                LocalPropWash.AffectedSections = parentPropWash.AffectedSections;
                LocalPropWash.PropWashSource = parentPropWash.PropWashSource;
                LocalPropWash.PropWashStrength = parentPropWash.PropWashStrength;

                //Keep unique
                LocalPropWash.PropWashSource = previousPropwashSource;
            }
            else if ( LocalPropWash && !parentPropWash )
            {
                //deleted on parent since copying.
                DestroyImmediate( LocalPropWash );
            }

            //Copy groundeffect.
            GroundEffect parentGroundEffect = ParentWing.GetComponent<GroundEffect>();
            if (!LocalGroundEffect && parentGroundEffect )
            {
                LocalGroundEffect = gameObject.AddComponent<GroundEffect>();
            }
            if ( LocalGroundEffect && parentGroundEffect )
            {
                //Copy everything..
                LocalGroundEffect.CLHeightVsChord = parentGroundEffect.CLHeightVsChord;
                LocalGroundEffect.CDHeightVsSpan = parentGroundEffect.CDHeightVsSpan;
                LocalGroundEffect.RayCastAxis = parentGroundEffect.RayCastAxis;
                LocalGroundEffect.RayCastLayers = parentGroundEffect.RayCastLayers;
                LocalGroundEffect.Wingspan = parentGroundEffect.Wingspan;
            }
            else if ( LocalGroundEffect && !parentGroundEffect )
            {
                //deleted on parent since copying.
                DestroyImmediate( LocalGroundEffect );
            }
        }
    }
Example #24
0
        public void Update(Vessel vessel)
        {
            if (vessel.rigidbody == null)
            {
                return;                           //if we try to update before rigidbodies exist we spam the console with NullPointerExceptions.
            }
            //if (vessel.packed) return;

            // To investigate some strange error
            if ((vessel.mainBody == null || (object)(vessel.mainBody) == null) && counter == 0)
            {
                if ((object)(vessel.mainBody) == null)
                {
                    MechJebCore.print("vessel.mainBody is proper null");
                }
                else
                {
                    MechJebCore.print("vessel.mainBody is Unity null");
                }

                counter = counter++ % 100;
            }


            time   = Planetarium.GetUniversalTime();
            deltaT = TimeWarp.fixedDeltaTime;

            CoM = vessel.findWorldCenterOfMass();
            up  = (CoM - vessel.mainBody.position).normalized;

            Rigidbody rigidBody = vessel.rootPart.rigidbody;

            if (rigidBody != null)
            {
                rootPartPos = rigidBody.position;
            }

            north                 = Vector3d.Exclude(up, (vessel.mainBody.position + vessel.mainBody.transform.up * (float)vessel.mainBody.Radius) - CoM).normalized;
            east                  = vessel.mainBody.getRFrmVel(CoM).normalized;
            forward               = vessel.GetTransform().up;
            rotationSurface       = Quaternion.LookRotation(north, up);
            rotationVesselSurface = Quaternion.Inverse(Quaternion.Euler(90, 0, 0) * Quaternion.Inverse(vessel.GetTransform().rotation) * rotationSurface);

//            velocityVesselOrbit = vessel.orbit.GetVel();
//            velocityVesselOrbitUnit = velocityVesselOrbit.normalized;
//            velocityVesselSurface = velocityVesselOrbit - vessel.mainBody.getRFrmVel(CoM);
//            velocityVesselSurfaceUnit = velocityVesselSurface.normalized;
            velocityMainBodySurface = rotationSurface * vessel.srf_velocity;

            horizontalOrbit   = Vector3d.Exclude(up, vessel.obt_velocity).normalized;
            horizontalSurface = Vector3d.Exclude(up, vessel.srf_velocity).normalized;

            angularVelocity = Quaternion.Inverse(vessel.GetTransform().rotation) * vessel.rigidbody.angularVelocity;

            radialPlusSurface = Vector3d.Exclude(vessel.srf_velocity, up).normalized;
            radialPlus        = Vector3d.Exclude(vessel.obt_velocity, up).normalized;
            normalPlusSurface = -Vector3d.Cross(radialPlusSurface, vessel.srf_velocity.normalized);
            normalPlus        = -Vector3d.Cross(radialPlus, vessel.obt_velocity.normalized);

            gravityForce = FlightGlobals.getGeeForceAtPosition(CoM);
            localg       = gravityForce.magnitude;

            speedOrbital.value           = vessel.obt_velocity.magnitude;
            speedSurface.value           = vessel.srf_velocity.magnitude;
            speedVertical.value          = Vector3d.Dot(vessel.srf_velocity, up);
            speedSurfaceHorizontal.value = Vector3d.Exclude(up, vessel.srf_velocity).magnitude; //(velocityVesselSurface - (speedVertical * up)).magnitude;
            speedOrbitHorizontal         = (vessel.obt_velocity - (speedVertical * up)).magnitude;

            vesselHeading.value = rotationVesselSurface.eulerAngles.y;
            vesselPitch.value   = (rotationVesselSurface.eulerAngles.x > 180) ? (360.0 - rotationVesselSurface.eulerAngles.x) : -rotationVesselSurface.eulerAngles.x;
            vesselRoll.value    = (rotationVesselSurface.eulerAngles.z > 180) ? (rotationVesselSurface.eulerAngles.z - 360.0) : rotationVesselSurface.eulerAngles.z;

            altitudeASL.value = vessel.mainBody.GetAltitude(CoM);
            //RaycastHit sfc;
            //if (Physics.Raycast(CoM, -up, out sfc, (float)altitudeASL + 10000.0F, 1 << 15))
            //{
            //    altitudeTrue.value = sfc.distance;
            //}
            //else if (vessel.mainBody.pqsController != null)
            //{
            //    // from here: http://kerbalspaceprogram.com/forum/index.php?topic=10324.msg161923#msg161923
            //    altitudeTrue.value = vessel.mainBody.GetAltitude(CoM) - (vessel.mainBody.pqsController.GetSurfaceHeight(QuaternionD.AngleAxis(vessel.mainBody.GetLongitude(CoM), Vector3d.down) * QuaternionD.AngleAxis(vessel.mainBody.GetLatitude(CoM), Vector3d.forward) * Vector3d.right) - vessel.mainBody.pqsController.radius);
            //}
            //else
            //{
            //    altitudeTrue.value = vessel.mainBody.GetAltitude(CoM);
            //}

            //double surfaceAltitudeASL = altitudeASL - altitudeTrue;

            double surfaceAltitudeASL = vessel.mainBody.pqsController != null ? vessel.pqsAltitude : 0d;

            altitudeTrue.value = altitudeASL - surfaceAltitudeASL;

            altitudeBottom = altitudeTrue;
            foreach (Part p in vessel.parts)
            {
                if (p.collider != null)
                {
                    Vector3d bottomPoint   = p.collider.ClosestPointOnBounds(vessel.mainBody.position);
                    double   partBottomAlt = vessel.mainBody.GetAltitude(bottomPoint) - surfaceAltitudeASL;
                    altitudeBottom = Math.Max(0, Math.Min(altitudeBottom, partBottomAlt));
                }
            }

            double atmosphericPressure = FlightGlobals.getStaticPressure(altitudeASL, vessel.mainBody);

            if (atmosphericPressure < vessel.mainBody.atmosphereMultiplier * 1e-6)
            {
                atmosphericPressure = 0;
            }
            atmosphericDensity      = FlightGlobals.getAtmDensity(atmosphericPressure);
            atmosphericDensityGrams = atmosphericDensity * 1000;

            orbitApA.value      = vessel.orbit.ApA;
            orbitPeA.value      = vessel.orbit.PeA;
            orbitPeriod.value   = vessel.orbit.period;
            orbitTimeToAp.value = vessel.orbit.timeToAp;
            if (vessel.orbit.eccentricity < 1)
            {
                orbitTimeToPe.value = vessel.orbit.timeToPe;
            }
            else
            {
                orbitTimeToPe.value = -vessel.orbit.meanAnomaly / (2 * Math.PI / vessel.orbit.period);
            }
            orbitLAN.value = vessel.orbit.LAN;
            orbitArgumentOfPeriapsis.value = vessel.orbit.argumentOfPeriapsis;
            orbitInclination.value         = vessel.orbit.inclination;
            orbitEccentricity.value        = vessel.orbit.eccentricity;
            orbitSemiMajorAxis.value       = vessel.orbit.semiMajorAxis;
            latitude.value  = vessel.mainBody.GetLatitude(CoM);
            longitude.value = MuUtils.ClampDegrees180(vessel.mainBody.GetLongitude(CoM));

            if (vessel.mainBody != Planetarium.fetch.Sun)
            {
                Vector3d delta = vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime() + 1) - vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime() - 1);
                Vector3d plUp  = Vector3d.Cross(vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime()) - vessel.mainBody.referenceBody.getPositionAtUT(Planetarium.GetUniversalTime()), vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime() + vessel.mainBody.orbit.period / 4) - vessel.mainBody.referenceBody.getPositionAtUT(Planetarium.GetUniversalTime() + vessel.mainBody.orbit.period / 4)).normalized;
                angleToPrograde = MuUtils.ClampDegrees360((((vessel.orbit.inclination > 90) || (vessel.orbit.inclination < -90)) ? 1 : -1) * ((Vector3)up).AngleInPlane(plUp, delta));
            }
            else
            {
                angleToPrograde = 0;
            }

            mainBody = vessel.mainBody;

            radius = (CoM - vessel.mainBody.position).magnitude;

            mass = massDrag = torqueThrustPYAvailable = 0;
            thrustVectorLastFrame   = new Vector3d();
            thrustVectorMaxThrottle = new Vector3d();
            thrustVectorMinThrottle = new Vector3d();
            torqueAvailable         = new Vector3d();
            rcsThrustAvailable      = new Vector6();
            rcsTorqueAvailable      = new Vector6();
            ctrlTorqueAvailable     = new Vector6();

            EngineInfo einfo = new EngineInfo(CoM);
            IntakeInfo iinfo = new IntakeInfo();

            parachutes = new List <ModuleParachute>();

            var rcsbal = vessel.GetMasterMechJeb().rcsbal;

            if (vessel.ActionGroups[KSPActionGroup.RCS] && rcsbal.enabled)
            {
                Vector3d rot = Vector3d.zero;
                foreach (Vector6.Direction dir6 in Enum.GetValues(typeof(Vector6.Direction)))
                {
                    Vector3d dir = Vector6.directions[dir6];
                    double[] throttles;
                    List <RCSSolver.Thruster> thrusters;
                    rcsbal.GetThrottles(dir, out throttles, out thrusters);
                    if (throttles != null)
                    {
                        for (int i = 0; i < throttles.Length; i++)
                        {
                            if (throttles[i] > 0)
                            {
                                Vector3d force = thrusters[i].GetThrust(dir, rot);
                                rcsThrustAvailable.Add(vessel.GetTransform().InverseTransformDirection(dir * Vector3d.Dot(force * throttles[i], dir)));
                            }
                        }
                    }
                }
            }

            hasMFE = false;

            foreach (Part p in vessel.parts)
            {
                if (p.IsPhysicallySignificant())
                {
                    double partMass = p.TotalMass();
                    mass     += partMass;
                    massDrag += partMass * p.maximum_drag;
                }

                if (vessel.ActionGroups[KSPActionGroup.RCS] && !rcsbal.enabled)
                {
                    foreach (ModuleRCS pm in p.Modules.OfType <ModuleRCS>())
                    {
                        double   maxT         = pm.thrusterPower;
                        Vector3d partPosition = p.Rigidbody.worldCenterOfMass - CoM;

                        if ((pm.isEnabled) && (!pm.isJustForShow))
                        {
                            foreach (Transform t in pm.thrusterTransforms)
                            {
                                Vector3d thrusterThrust = vessel.GetTransform().InverseTransformDirection(-t.up.normalized) * pm.thrusterPower;
                                rcsThrustAvailable.Add(thrusterThrust);
                                Vector3d thrusterTorque = Vector3.Cross(vessel.GetTransform().InverseTransformDirection(partPosition), thrusterThrust);
                                rcsTorqueAvailable.Add(thrusterTorque);
                            }
                        }
                    }
                }

                if (p is ControlSurface)
                {
                    Vector3d       partPosition = p.Rigidbody.worldCenterOfMass - CoM;
                    ControlSurface cs           = (p as ControlSurface);
                    Vector3d       airSpeed     = vessel.srf_velocity + Vector3.Cross(cs.Rigidbody.angularVelocity, cs.transform.position - cs.Rigidbody.position);
                    // Air Speed is velocityVesselSurface
                    // AddForceAtPosition seems to need the airspeed vector rotated with the flap rotation x its surface
                    Quaternion airSpeedRot   = Quaternion.AngleAxis(cs.ctrlSurfaceRange * cs.ctrlSurfaceArea, cs.transform.rotation * cs.pivotAxis);
                    Vector3    ctrlTroquePos = vessel.GetTransform().InverseTransformDirection(Vector3.Cross(partPosition, cs.getLiftVector(airSpeedRot * airSpeed)));
                    Vector3    ctrlTroqueNeg = vessel.GetTransform().InverseTransformDirection(Vector3.Cross(partPosition, cs.getLiftVector(Quaternion.Inverse(airSpeedRot) * airSpeed)));
                    ctrlTorqueAvailable.Add(ctrlTroquePos);
                    ctrlTorqueAvailable.Add(ctrlTroqueNeg);
                }

                if (p is CommandPod)
                {
                    torqueAvailable += Vector3d.one * Math.Abs(((CommandPod)p).rotPower);
                }

                foreach (VesselStatePartExtension vspe in vesselStatePartExtensions)
                {
                    vspe(p);
                }

                foreach (PartModule pm in p.Modules)
                {
                    if (!pm.isEnabled)
                    {
                        continue;
                    }

                    if (pm is ModuleReactionWheel)
                    {
                        ModuleReactionWheel rw = (ModuleReactionWheel)pm;
                        // I had to remove the test for active in .23 since the new ressource system reply to the RW that
                        // there is no energy available when the RW do tiny adjustement.
                        // I replaceed it with a test that check if there is electricity anywhere on the ship.
                        // Let's hope we don't get reaction wheel that use something else
                        //if (rw.wheelState == ModuleReactionWheel.WheelState.Active && !rw.stateString.Contains("Not enough"))
                        if (rw.wheelState == ModuleReactionWheel.WheelState.Active && vessel.HasElectricCharge())
                        {
                            torqueAvailable += new Vector3d(rw.PitchTorque, rw.RollTorque, rw.YawTorque);
                        }
                    }
                    else if (pm is ModuleEngines)
                    {
                        einfo.AddNewEngine(pm as ModuleEngines);
                    }
                    else if (pm is ModuleEnginesFX)
                    {
                        einfo.AddNewEngine(pm as ModuleEnginesFX);
                    }
                    else if (pm is ModuleResourceIntake)
                    {
                        iinfo.addIntake(pm as ModuleResourceIntake);
                    }
                    else if (pm is ModuleParachute)
                    {
                        parachutes.Add(pm as ModuleParachute);
                    }
                    else if (pm is ModuleControlSurface)
                    {
                        // TODO : Tweakable for ignorePitch / ignoreYaw  / ignoreRoll
                        ModuleControlSurface cs           = (pm as ModuleControlSurface);
                        Vector3d             partPosition = p.Rigidbody.worldCenterOfMass - CoM;

                        Vector3d airSpeed = vessel.srf_velocity + Vector3.Cross(cs.part.Rigidbody.angularVelocity, cs.transform.position - cs.part.Rigidbody.position);

                        Quaternion airSpeedRot = Quaternion.AngleAxis(cs.ctrlSurfaceRange * cs.ctrlSurfaceArea, cs.transform.rotation * Vector3.right);

                        Vector3 ctrlTroquePos = vessel.GetTransform().InverseTransformDirection(Vector3.Cross(partPosition, cs.getLiftVector(airSpeedRot * airSpeed)));
                        Vector3 ctrlTroqueNeg = vessel.GetTransform().InverseTransformDirection(Vector3.Cross(partPosition, cs.getLiftVector(Quaternion.Inverse(airSpeedRot) * airSpeed)));
                        ctrlTorqueAvailable.Add(ctrlTroquePos);
                        ctrlTorqueAvailable.Add(ctrlTroqueNeg);
                    }

                    if (pm.ClassName == "ModuleEngineConfigs" || pm.ClassName == "ModuleHybridEngine" || pm.ClassName == "ModuleHybridEngines")
                    {
                        hasMFE = true;
                    }

                    foreach (VesselStatePartModuleExtension vspme in vesselStatePartModuleExtensions)
                    {
                        vspme(pm);
                    }
                }
            }

            // Consider all the parachutes
            {
                bool tempParachuteDeployed = false;
                foreach (ModuleParachute p in parachutes)
                {
                    if (p.deploymentState == ModuleParachute.deploymentStates.DEPLOYED || p.deploymentState == ModuleParachute.deploymentStates.SEMIDEPLOYED)
                    {
                        tempParachuteDeployed = true;
                        break;
                    }
                }
                this.parachuteDeployed = tempParachuteDeployed;
            }

            torqueAvailable += Vector3d.Max(rcsTorqueAvailable.positive, rcsTorqueAvailable.negative);   // Should we use Max or Min ?
            torqueAvailable += Vector3d.Max(ctrlTorqueAvailable.positive, ctrlTorqueAvailable.negative); // Should we use Max or Min ?

            thrustVectorMaxThrottle += einfo.thrustMax;
            thrustVectorMinThrottle += einfo.thrustMin;
            thrustVectorLastFrame   += einfo.thrustCurrent;
            torqueThrustPYAvailable += einfo.torqueThrustPYAvailable;

            if (thrustVectorMaxThrottle.magnitude == 0 && vessel.ActionGroups[KSPActionGroup.RCS])
            {
                rcsThrust = true;
                thrustVectorMaxThrottle += (Vector3d)(vessel.transform.up) * rcsThrustAvailable.down;
            }
            else
            {
                rcsThrust = false;
            }

            // Convert the resource information from the einfo and iinfo format
            // to the more useful ResourceInfo format.
            resources = new Dictionary <int, ResourceInfo>();
            foreach (var info in einfo.resourceRequired)
            {
                int id  = info.Key;
                var req = info.Value;
                resources[id] = new ResourceInfo(
                    PartResourceLibrary.Instance.GetDefinition(id),
                    req.requiredLastFrame,
                    req.requiredAtMaxThrottle,
                    iinfo.getIntakes(id));
            }

            int intakeAirId = PartResourceLibrary.Instance.GetDefinition("IntakeAir").id;

            intakeAir           = 0;
            intakeAirNeeded     = 0;
            intakeAirAtMax      = 0;
            intakeAirAllIntakes = 0;
            if (resources.ContainsKey(intakeAirId))
            {
                intakeAir           = resources[intakeAirId].intakeProvided;
                intakeAirAllIntakes = resources[intakeAirId].intakeAvailable;
                intakeAirNeeded     = resources[intakeAirId].required;
                intakeAirAtMax      = resources[intakeAirId].requiredAtMaxThrottle;
            }

            angularMomentum = new Vector3d(angularVelocity.x * MoI.x, angularVelocity.y * MoI.y, angularVelocity.z * MoI.z);

            inertiaTensor = new Matrix3x3();
            foreach (Part p in vessel.parts)
            {
                if (p.Rigidbody == null)
                {
                    continue;
                }

                //Compute the contributions to the vessel inertia tensor due to the part inertia tensor
                Vector3d   principalMoments = p.Rigidbody.inertiaTensor;
                Quaternion princAxesRot     = Quaternion.Inverse(vessel.GetTransform().rotation) * p.transform.rotation * p.Rigidbody.inertiaTensorRotation;
                Quaternion invPrincAxesRot  = Quaternion.Inverse(princAxesRot);

                for (int i = 0; i < 3; i++)
                {
                    Vector3d iHat = Vector3d.zero;
                    iHat[i] = 1;
                    for (int j = 0; j < 3; j++)
                    {
                        Vector3d jHat = Vector3d.zero;
                        jHat[j]              = 1;
                        inertiaTensor[i, j] += Vector3d.Dot(iHat, princAxesRot * Vector3d.Scale(principalMoments, invPrincAxesRot * jHat));
                    }
                }

                //Compute the contributions to the vessel inertia tensor due to the part mass and position
                double  partMass     = p.TotalMass();
                Vector3 partPosition = vessel.GetTransform().InverseTransformDirection(p.Rigidbody.worldCenterOfMass - CoM);

                for (int i = 0; i < 3; i++)
                {
                    inertiaTensor[i, i] += partMass * partPosition.sqrMagnitude;

                    for (int j = 0; j < 3; j++)
                    {
                        inertiaTensor[i, j] += -partMass * partPosition[i] * partPosition[j];
                    }
                }
            }

            MoI             = new Vector3d(inertiaTensor[0, 0], inertiaTensor[1, 1], inertiaTensor[2, 2]);
            angularMomentum = inertiaTensor * angularVelocity;
        }
Example #25
0
    public override void OnUpdate()
    {
        base.OnUpdate();

        if (FlightGlobals.fetch.vesselTargetMode != VesselTargetModes.None)
        {
            Vessel target = (Vessel)FlightGlobals.fetch.VesselTarget;
            //target.ctrlState.mainThrottle = 1f;

            foreach (Part part in target.Parts)
            {
                ControlSurface ctrlsurf = part.Modules.OfType <ControlSurface>().FirstOrDefault();
                if (ctrlsurf != null)
                {
                    ctrlsurf.ActivatesEvenIfDisconnected = true;
                    ctrlsurf.inputVector = new Vector3(vessel.ctrlState.X, vessel.ctrlState.Y, vessel.ctrlState.Z);
                }
            }

            target.ctrlState.mainThrottle = vessel.ctrlState.Z;
            target.ctrlState.pitch        = vessel.ctrlState.X;
            target.ctrlState.roll         = vessel.ctrlState.Z;
            //Vessel targetVessel = (Vessel)target;
            //Debug.Log(target);
            BaseFieldList test = this.part.Fields;
            foreach (BaseField field in test)
            {
                field.guiActive = false;
            }

            fogDensity -= 0.0001f;
            if (fogDensity <= 0f)
            {
                fogDensity = 0.01f;
            }

            RenderSettings.fog              = true;
            RenderSettings.fogColor         = Color.white;
            RenderSettings.fogDensity       = fogDensity;
            RenderSettings.fogStartDistance = -50f;
            RenderSettings.fogMode          = FogMode.ExponentialSquared;
            //Camera.main.clearFlags = CameraClearFlags.SolidColor;
            //Camera.main.backgroundColor = new Color(1f,1f,1f,0.1f);
        }
        else
        {
            RenderSettings.fog          = false;
            RenderSettings.fogColor     = new Color(0.439f, 0.859f, 1.000f, 0.0f);;
            RenderSettings.fogDensity   = 1.5E-05f;
            RenderSettings.fogMode      = FogMode.ExponentialSquared;
            Camera.main.clearFlags      = CameraClearFlags.Depth;
            Camera.main.backgroundColor = new Color(0f, 0f, 0f, 0.02f);

            /*Debug.Log("fs: rsFog " + RenderSettings.fog);
             * Debug.Log("fs: fogC " + RenderSettings.fogColor);
             * Debug.Log("fs: fDens " + RenderSettings.fogDensity);
             * Debug.Log("fs: fMode" + RenderSettings.fogMode);
             * Debug.Log("fs: camCF" + Camera.main.clearFlags);
             * Debug.Log("fs: camBGc" + Camera.main.backgroundColor);*/
        }
    }
 // Use this for initialization
 public void Start()
 {
     WingBoxCollider = (BoxCollider)gameObject.collider;
     Parent = transform.root.gameObject.GetComponent<Rigidbody>();
     ParentAircraft = transform.root.gameObject.GetComponent<Aircraft>();
     AttachedControlSurface = gameObject.GetComponent<ControlSurface>();
     AttachedPropWash = gameObject.GetComponent<PropWash>();
     AttachedGroundEffect = gameObject.GetComponent<GroundEffect>();
 }
 public void SetControlSurface(object obj)
 {
     surface  = null;
     airplane = null;
     surface  = obj as ControlSurface;
     if (surface != null)
     {
         comboBoxChannel.Enabled          = true;
         comboBoxType.Enabled             = true;
         checkBoxReversed.Enabled         = true;
         comboBoxChannel.SelectedIndex    = (int)surface.Channel;
         comboBoxType.SelectedIndex       = (int)surface.ControlSurfaceType;
         checkBoxReversed.Visible         = true;
         checkBoxReversed.Checked         = surface.Reversed;
         vectorControlPosition.Vector     = surface.Position;
         vectorControlRotationAxis.Vector = surface.RotationAxis;
         labelFileName.Text = surface.MeshFileName;
         numericUpDownDefaultAngle.Value = Convert.ToDecimal(surface.ZeroAngle * 180 / Math.PI);
         numericUpDownMinAngle.Value     = Convert.ToDecimal(surface.MinimumAngle * 180 / Math.PI);
         numericUpDownMaxAngle.Value     = Convert.ToDecimal(surface.MaximumAngle * 180 / Math.PI);
         numericUpDownScale.Value        = Convert.ToDecimal(surface.Scale.X);
         comboBoxChannel.Visible         = true;
         labelChannel.Visible            = true;
         comboBoxType.Visible            = true;
         labelType.Visible                 = true;
         vectorControlPosition.Visible     = true;
         labelPosition.Visible             = true;
         vectorControlRotationAxis.Visible = true;
         labelRotation.Visible             = true;
         numericUpDownDefaultAngle.Visible = true;
         labelDefaultAngle.Visible         = true;
         numericUpDownMaxAngle.Visible     = true;
         labelMaxAngle.Visible             = true;
         numericUpDownMinAngle.Visible     = true;
         labelMinAngle.Visible             = true;
         labelSpanLength.Visible           = false;
     }
     else
     {
         airplane = obj as AirplaneModel;
         if (airplane != null)
         {
             numericUpDownScale.Value = Convert.ToDecimal(airplane.Scale.X);
             labelFileName.Text       = airplane.MeshFileName;
             labelSpanLength.Visible  = true;
             UpdateSizeLabel();
             comboBoxChannel.Visible           = false;
             labelChannel.Visible              = false;
             comboBoxType.Visible              = false;
             labelType.Visible                 = false;
             vectorControlPosition.Visible     = false;
             labelPosition.Visible             = false;
             vectorControlRotationAxis.Visible = false;
             labelRotation.Visible             = false;
             numericUpDownDefaultAngle.Visible = false;
             labelDefaultAngle.Visible         = false;
             numericUpDownMaxAngle.Visible     = false;
             labelMaxAngle.Visible             = false;
             numericUpDownMinAngle.Visible     = false;
             labelMinAngle.Visible             = false;
             checkBoxReversed.Visible          = false;
         }
         else
         {
             comboBoxType.SelectedIndex    = -1;
             comboBoxChannel.SelectedIndex = -1;
             checkBoxReversed.Checked      = false;
             comboBoxChannel.Enabled       = false;
             comboBoxType.Enabled          = false;
             checkBoxReversed.Enabled      = false;
         }
     }
 }