Пример #1
0
        public void SetThrottleSpeed(double rate)
        {
            if (!paFound)
            {
                return;
            }
            try
            {
                object pilotAssistant = GetPilotAssistant();

                SetThrottle(pilotAssistant, new object[] { true, true, ThrottleMode.Speed, rate });
            }
            catch (Exception e)
            {
                JUtil.LogMessage(this, "SetThrottleSpeed: {0}", e);
            }
        }
Пример #2
0
        public void Start()
        {
            JUtil.LogMessage(this, "Setting RasterPropMonitor debugging to {0}", debugLogging);
            JUtil.debugLoggingEnabled = debugLogging;

            if (!HighLogic.LoadedSceneIsEditor)
            {
                RPMVesselComputer comp = RPMVesselComputer.Instance(vessel);
                comp.SetVesselDescription(vesselDescription);

                // Make sure we have the description strings parsed.
                string[] descriptionStrings = vesselDescription.UnMangleConfigText().Split(JUtil.LineSeparator, StringSplitOptions.None);
                for (int i = 0; i < descriptionStrings.Length; i++)
                {
                    if (descriptionStrings[i].StartsWith("AG", StringComparison.Ordinal) && descriptionStrings[i][3] == '=')
                    {
                        uint groupID;
                        if (uint.TryParse(descriptionStrings[i][2].ToString(), out groupID))
                        {
                            descriptionStrings[i] = string.Empty;
                        }
                    }
                }
                vesselDescriptionForDisplay = string.Join(Environment.NewLine, descriptionStrings).MangleConfigText();

                // Now let's parse our stored strings...
                if (!string.IsNullOrEmpty(storedStrings))
                {
                    storedStringsArray = storedStrings.Split('|');
                }

                ParseData();

                // TODO: If there are triggered events, register for an undock
                // callback so we can void and rebuild the callbacks after undocking.
                // Although it didn't work when I tried it...
                if (!string.IsNullOrEmpty(triggeredEvents))
                {
                    string[] varstring = triggeredEvents.Split('|');
                    for (int i = 0; i < varstring.Length; ++i)
                    {
                        comp.AddTriggeredEvent(varstring[i].Trim());
                    }
                }
            }
        }
Пример #3
0
        public void SetHorzHeading(double rate)
        {
            if (!paFound)
            {
                return;
            }
            try
            {
                object pilotAssistant = GetPilotAssistant();

                SetHorz(pilotAssistant, new object[] { true, true, HrztMode.HeadingNum, rate });
            }
            catch (Exception e)
            {
                JUtil.LogMessage(this, "SetHorzHeading: {0}", e);
            }
        }
Пример #4
0
        /// <summary>
        /// Add a variable to the variableCache
        /// </summary>
        /// <param name="variableName"></param>
        private void AddVariable(string variableName)
        {
            VariableCache vc = new VariableCache();
            bool          cacheable;

            vc.evaluator = GetEvaluator(variableName, out cacheable);
            vc.value     = new VariableOrNumber(variableName, cacheable, this);
            vc.cacheable = cacheable;

            if (vc.value.variableType == VariableOrNumber.VoNType.VariableValue)
            {
                RPMVesselComputer comp  = RPMVesselComputer.Instance(vessel);
                object            value = vc.evaluator(variableName, comp);
                if (value is string)
                {
                    vc.value.stringValue  = value as string;
                    vc.value.isNumeric    = false;
                    vc.value.numericValue = 0.0;

                    // If the evaluator returns the variableName, then we
                    // have an unknown variable.  Change the VoN type to
                    // ConstantString so we don't waste cycles on update to
                    // reevaluate it.
                    if (vc.value.stringValue == variableName && !unrecognizedVariables.Contains(variableName))
                    {
                        vc.value.variableType = VariableOrNumber.VoNType.ConstantString;
                        unrecognizedVariables.Add(variableName);
                        JUtil.LogInfo(this, "Unrecognized variable {0}", variableName);
                    }
                }
                else
                {
                    vc.value.numericValue = value.MassageToDouble();
                    vc.value.isNumeric    = true;
                }
            }

            variableCache.Add(variableName, vc);

            if (vc.value.variableType == VariableOrNumber.VoNType.VariableValue)
            {
                // Only variables that are really variable need to be checked
                // during FixedUpdate.
                updatableVariables.Add(vc);
            }
        }
Пример #5
0
        public void SetVertAltitude(double rate)
        {
            if (!paFound)
            {
                return;
            }
            try
            {
                object pilotAssistant = GetPilotAssistant();

                SetVert(pilotAssistant, new object[] { true, true, VertMode.Altitude, rate });
            }
            catch (Exception e)
            {
                JUtil.LogMessage(this, "SetVertAltitude: {0}", e);
            }
        }
Пример #6
0
        public void Start()
        {
            try
            {
                rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true);

                Transform textObjTransform = internalProp.FindModelTransform(transformName);
                textObj = InternalComponents.Instance.CreateText("Arial", fontSize * 15.5f, textObjTransform, string.Empty);
                // Force oneshot if there's no variables:
                oneshot |= !labelText.Contains("$&$");
                string sourceString = labelText.UnMangleConfigText();

                if (!string.IsNullOrEmpty(sourceString) && sourceString.Length > 1)
                {
                    // Alow a " character to escape leading whitespace
                    if (sourceString[0] == '"')
                    {
                        sourceString = sourceString.Substring(1);
                    }
                }
                spf = new StringProcessorFormatter(sourceString, rpmComp);

                if (!oneshot)
                {
                    rpmComp.UpdateDataRefreshRate(refreshRate);
                }

                if (!(string.IsNullOrEmpty(variableName) || string.IsNullOrEmpty(positiveColor) || string.IsNullOrEmpty(negativeColor) || string.IsNullOrEmpty(zeroColor)))
                {
                    positiveColorValue = JUtil.ParseColor32(positiveColor, part, ref rpmComp);
                    negativeColorValue = JUtil.ParseColor32(negativeColor, part, ref rpmComp);
                    zeroColorValue     = JUtil.ParseColor32(zeroColor, part, ref rpmComp);
                    del = (Action <float>)Delegate.CreateDelegate(typeof(Action <float>), this, "OnCallback");
                    rpmComp.RegisterVariableCallback(variableName, del);
                    registeredVessel = vessel.id;

                    // Initialize the text color. Actually, callback registration took care of that
                }
            }
            catch (Exception e)
            {
                JUtil.LogErrorMessage(this, "Start failed with exception {0}", e);
                spf = new StringProcessorFormatter("x", rpmComp);
            }
        }
Пример #7
0
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true);

            if (string.IsNullOrEmpty(definitionIn) && definitions != null)
            {
                for (int i = 0; i < definitions.Length; ++i)
                {
                    string[] varrange = definitions[i].range.Split(',');
                    range.Add(new VariableOrNumberRange(rpmComp, definitions[i].variableName, varrange[0], varrange[1]));
                    text.Add(JUtil.LoadPageDefinition(definitions[i].page));
                }
                definitions = null;
                initialized = true;
            }
            else
            {
                string[] tokens = scale.Split(',');

                if (tokens.Length == 2)
                {
                    legacyRange = new VariableOrNumberRange(rpmComp, variableName, tokens[0], tokens[1]);

                    float min = Mathf.Min(threshold.x, threshold.y);
                    float max = Mathf.Max(threshold.x, threshold.y);
                    threshold.x = min;
                    threshold.y = max;

                    text.Add(JUtil.LoadPageDefinition(definitionIn));

                    initialized = true;
                }
                else
                {
                    JUtil.LogErrorMessage(this, "Could not parse the 'scale' parameter: {0}", scale);
                }
            }

            text.Add(JUtil.LoadPageDefinition(definitionOut));
        }
            private static bool InstantiateHandler(ConfigNode node, PartModule ourComp, out Func <string, object> handlerFunction)
            {
                handlerFunction = null;
                var handlerConfiguration = new ConfigNode("MODULE");

                node.CopyTo(handlerConfiguration);
                string moduleName = node.GetValue("name");
                string methodName = node.GetValue("method");

                // Since we're working with part modules here, and starting in a pod config,
                // we'll keep one instance per pod, which will let them instantiate with their own config if needed.
                MonoBehaviour thatModule = null;

                foreach (PartModule potentialModule in ourComp.part.Modules)
                {
                    if (potentialModule.ClassName == moduleName)
                    {
                        thatModule = potentialModule;
                        break;
                    }
                }
                if (thatModule == null)
                {
                    thatModule = ourComp.part.AddModule(handlerConfiguration);
                }
                if (thatModule == null)
                {
                    JUtil.LogMessage(ourComp, "Warning, variable handler module \"{0}\" could not be loaded. This could be perfectly normal.", moduleName);
                    return(false);
                }
                foreach (MethodInfo m in thatModule.GetType().GetMethods())
                {
                    if (m.Name == node.GetValue("method"))
                    {
                        try {
                            handlerFunction = (Func <string, object>)Delegate.CreateDelegate(typeof(Func <string, object>), thatModule, m);
                        } catch {
                            JUtil.LogErrorMessage(ourComp, "Error, incorrect variable handler configuration for module {0}", moduleName);
                            return(false);
                        }
                        break;
                    }
                }
                return(true);
            }
Пример #9
0
        private void ResetIVA()
        {
            if (HighLogic.LoadedSceneIsFlight)
            {
                JUtil.LogMessage(this, "Need to reset IVA in part ", part.partName);

                // Now the cruical bit.
                // If the root part changed, we actually need to recreate the IVA forcibly even if it still exists.
                if (vessel.rootPart != knownRootPart)
                {
                    // In this case we also need to kick the user out of IVA if they're currently in our pod,
                    // otherwise lots of things screw up in a bizarre fashion.
                    if (JUtil.UserIsInPod(part))
                    {
                        JUtil.LogMessage(this, "The user is in pod {0} and I need to kick them out.", part.partName);
                        CameraManager.Instance.SetCameraFlight();
                    }
                    // This call not just reinitialises the IVA, but also destroys the existing one, if any,
                    // and reloads all the props and modules.
                    JUtil.LogMessage(this, "Need to actually respawn the IVA model in part {0}", part.partName);
                    part.CreateInternalModel();
                }
                // But otherwise the existing one will serve.

                // If the internal model doesn't yet exist, this call will implicitly create it anyway.
                // It will also initialise it, which in this case implies moving it into the correct location in internal space
                // and populate it with crew, which is what we want.
                part.SpawnIVA(); //?
                //part.SpawnCrew();

                // Once that happens, the internal will have the correct location for viewing from IVA relative to the
                // current active vessel. (Yeah, internal space is bizarre like that.) So we make note of it.
                originalParent   = part.internalModel.transform.parent;
                originalPosition = part.internalModel.transform.localPosition;
                originalRotation = part.internalModel.transform.localRotation;
                originalScale    = part.internalModel.transform.localScale;

                // And then we remember the root part and the active vessel these coordinates refer to.
                knownRootPart    = vessel.rootPart;
                lastActiveVessel = FlightGlobals.ActiveVessel;

                //Finally we check for Stowaways on the PortraitCams
                CheckStowaways();
            }
        }
Пример #10
0
        public void PointCamera(string newCameraName, float initialFOV)
        {
            CleanupCameraObjects();
            if (!string.IsNullOrEmpty(newCameraName))
            {
                FOV = initialFOV;

                if (newCameraName == referenceCamera)
                {
                    PointToReferenceCamera();
                    JUtil.LogMessage(this, "Tracking reference point docking port camera.");
                }
                else
                {
                    CreateCameraObjects(newCameraName);
                }
            }
        }
Пример #11
0
 public ExternalVariableHandlers(RasterPropMonitorComputer ourComp)
 {
     foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("RPMCVARIABLEHANDLER"))
     {
         if (!node.HasValue("name") || !node.HasValue("method"))
         {
             JUtil.LogMessage(ourComp, "A variable handler configuration block is missing key items and was ignored.");
         }
         else
         {
             handlers.Add(new VariableHandler(node, ourComp));
         }
     }
     foreach (VariableHandler thatHandler in handlers)
     {
         JUtil.LogMessage(ourComp, "Variable handler {0} is known and {1:;;\"not\"} loaded.", thatHandler.handlerName, thatHandler.active.GetHashCode());
     }
 }
Пример #12
0
        public double GetThrottleSetting()
        {
            if (!paFound)
            {
                return(0.0);
            }
            try
            {
                object pilotAssistant = GetPilotAssistant();

                return(GetCurrentThrottle(pilotAssistant));
            }
            catch (Exception e)
            {
                JUtil.LogMessage(this, "GetThrottleSetting: {0}", e);
            }
            return(0.0);
        }
Пример #13
0
        // Simple phase angle: transfer from sun -> planet or planet -> moon
        private static double UpdatePhaseAngleSimple(Vessel vessel, double altitudeASL, Orbit srcOrbit, Orbit destOrbit)
        {
            if (destOrbit == null)
            {
                JUtil.LogMessage(null, "!!! UpdatePhaseAngleSimple got a NULL orbit !!!");
                return(0.0);
            }

            // MOARdV TODO: Can this be made more accurate using the orbit
            // altitude at the point of intercept?
            double destAlt = CalcMeanAlt(destOrbit);

            double phase = CurrentPhase(srcOrbit, destOrbit) - DesiredPhase(altitudeASL + vessel.mainBody.Radius, destAlt, vessel.mainBody.gravParameter);

            phase = (phase + 360.0) % 360.0;

            return(phase);
        }
Пример #14
0
        public void Start()
        {
            try {
                ConfigNode moduleConfig = null;
                foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP"))
                {
                    if (node.GetValue("name") == internalProp.propName)
                    {
                        moduleConfig = node.GetNodes("MODULE")[moduleID];
                        ConfigNode[] variableNodes = moduleConfig.GetNodes("VARIABLESET");

                        for (int i = 0; i < variableNodes.Length; i++)
                        {
                            try {
                                variableSets.Add(new VariableAnimationSet(variableNodes[i], internalProp));
                            } catch (ArgumentException e) {
                                JUtil.LogMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID);
                            }
                        }
                        break;
                    }
                }

                // Fallback: If there are no VARIABLESET blocks, we treat the module configuration itself as a variableset block.
                if (variableSets.Count < 1 && moduleConfig != null)
                {
                    try {
                        variableSets.Add(new VariableAnimationSet(moduleConfig, internalProp));
                    } catch (ArgumentException e) {
                        JUtil.LogMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID);
                    }
                }
                JUtil.LogMessage(this, "Configuration complete in prop {1}, supporting {0} variable indicators.", variableSets.Count, internalProp.propID);
                foreach (VariableAnimationSet thatSet in variableSets)
                {
                    alwaysActive |= thatSet.alwaysActive;
                }
                startupComplete = true;
            } catch {
                JUtil.AnnoyUser(this);
                enabled = false;
                throw;
            }
        }
Пример #15
0
        private static GameObject BuildMarker(int iconX, int iconY, float markerSize, Texture gizmoTexture, Color nativeColor, int drawingLayer, int propID, Shader shader)
        {
            GameObject marker = JUtil.CreateSimplePlane("RPMPFDMarker" + iconX + iconY + propID, markerSize, drawingLayer);

            Material material = new Material(shader);

            material.mainTexture       = gizmoTexture;
            material.mainTextureScale  = Vector2.one / 3f;
            material.mainTextureOffset = new Vector2(iconX * (1f / 3f), iconY * (1f / 3f));
            material.color             = Color.white;
            material.SetVector("_Color", nativeColor);
            marker.renderer.material = material;

            marker.transform.position = Vector3.zero;

            JUtil.ShowHide(false, marker);

            return(marker);
        }
Пример #16
0
        // MOARdV TODO: Convert persistence values to floats to support new input options
        private void ParseData()
        {
            persistentVars.Clear();
            if (!string.IsNullOrEmpty(data))
            {
                string[] varstring = data.Split('|');
                for (int i = 0; i < varstring.Length; ++i)
                {
                    string[] tokens = varstring[i].Split('$');
                    int      value;
                    if (tokens.Length == 2 && int.TryParse(tokens[1], out value))
                    {
                        persistentVars.Add(tokens[0], value);
                    }
                }

                JUtil.LogMessage(this, "Parsed persistence string 'data' into {0} entries", persistentVars.Count);
            }
        }
Пример #17
0
        public void SetVertMode(double dmode)
        {
            if (!paFound)
            {
                return;
            }

            VertMode vertMode;

            switch ((int)dmode)
            {
            case 0:
                vertMode = VertMode.Pitch;
                break;

            case 1:
                vertMode = VertMode.VSpeed;
                break;

            case 2:
                vertMode = VertMode.Altitude;
                break;

            case 3:
                vertMode = VertMode.RadarAltitude;
                break;

            default:
                return;
            }

            try
            {
                object pilotAssistant = GetPilotAssistant();
                object vertActive     = vertActive_t.GetValue(pilotAssistant);

                SetVert(pilotAssistant, new object[] { vertActive, false, vertMode, 0.0 });
            }
            catch (Exception e)
            {
                JUtil.LogMessage(this, "SetVertMode: {0}", e);
            }
        }
        public void EVAClick()
        {
            Kerbal thatKerbal = part.FindCurrentKerbal();

            float acLevel     = ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex);
            bool  evaUnlocked = GameVariables.Instance.UnlockedEVA(acLevel);
            bool  evaPossible = GameVariables.Instance.EVAIsPossible(evaUnlocked, vessel);

            if (evaPossible && thatKerbal != null && HighLogic.CurrentGame.Parameters.Flight.CanEVA)
            {
                if (thatKerbal.protoCrewMember.type != ProtoCrewMember.KerbalType.Tourist)
                {
                    activeKerbal = thatKerbal;
                    if (intAnim != null)
                    {
                        intAnim.enabled = true;
                        intAnim[internalAnimation].speed = 1;
                        intAnim.Play();
                        intAnimStarted = true;
                    }
                    else
                    {
                        GoEva();
                    }
                    JUtil.LogMessage(this, "{0} has opened the internal EVA hatch.", thatKerbal.name);
                }
                else
                {
                    JUtil.LogMessage(this, "{0}, a tourist, tried to open the EVA hatch.", thatKerbal.name);
                }
            }
            else
            {
                if (evaPossible)
                {
                    JUtil.LogMessage(this, "Could not open the internal EVA hatch, not sure why.");
                }
                else
                {
                    JUtil.LogMessage(this, "EVA hatches can not be opened - is the astronaut complex upgraded yet?");
                }
            }
        }
Пример #19
0
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }
            try
            {
                backgroundColorValue = ConfigNode.ParseColor32(backgroundColor);

                cameraBody                 = new GameObject();
                cameraBody.name            = "RPMPFD" + cameraBody.GetInstanceID();
                cameraBody.layer           = drawingLayer;
                hudCamera                  = cameraBody.AddComponent <Camera>();
                hudCamera.enabled          = false;
                hudCamera.orthographic     = true;
                hudCamera.eventMask        = 0;
                hudCamera.farClipPlane     = 3f;
                hudCamera.orthographicSize = 1.0f;
                hudCamera.cullingMask      = 1 << drawingLayer;
                // does this actually work?
                hudCamera.backgroundColor      = backgroundColorValue;
                hudCamera.clearFlags           = CameraClearFlags.Depth | CameraClearFlags.Color;
                hudCamera.transparencySortMode = TransparencySortMode.Orthographic;
                hudCamera.transform.position   = Vector3.zero;
                hudCamera.transform.LookAt(new Vector3(0.0f, 0.0f, 1.5f), Vector3.up);

                if (!string.IsNullOrEmpty(progradeColor))
                {
                    progradeColorValue = ConfigNode.ParseColor32(progradeColor);
                }

                persistence = new PersistenceAccessor(internalProp);
            }
            catch (Exception e)
            {
                JUtil.LogErrorMessage(this, "Start() failed with an exception: {0}", e);
                JUtil.AnnoyUser(this);
                throw;
            }

            startupComplete = true;
        }
Пример #20
0
        private static Texture2D LoadFont(object caller, InternalProp thisProp, string location)
        {
            Texture2D font = null;

            if (!string.IsNullOrEmpty(location))
            {
                if (GameDatabase.Instance.ExistsTexture(location.EnforceSlashes()))
                {
                    font = GameDatabase.Instance.GetTexture(location.EnforceSlashes(), false);
                    JUtil.LogMessage(caller, "Loading font texture from URL \"{0}\"", location);
                }
                else
                {
                    font = (Texture2D)thisProp.FindModelTransform(location).renderer.material.mainTexture;
                    JUtil.LogMessage(caller, "Loading font texture from a transform named \"{0}\"", location);
                }
            }
            return(font);
        }
Пример #21
0
 /// <summary>
 /// Callback RasterPropMonitorComputer calls when the variable of interest
 /// changes.
 /// </summary>
 /// <param name="value"></param>
 void OnCallback(float value)
 {
     // Sanity checks:
     if (vessel == null)
     {
         // Stop getting callbacks if for some reason a different
         // computer is talking to us.
         //JUtil.LogMessage(this, "OnCallback - unregistering del {0}, vessel null is {1}, comp.id = {2}", del.GetHashCode(), (vessel == null), comp.id);
         rpmComp.UnregisterVariableCallback(variableName, del);
         JUtil.LogErrorMessage(this, "Received an unexpected OnCallback()");
     }
     else
     {
         for (int i = 0; i < variableSets.Count; ++i)
         {
             variableSets[i].Update(value);
         }
     }
 }
Пример #22
0
        private void CameraSetup(int index, string sourceName)
        {
            Camera sourceCam = JUtil.GetCameraByName(sourceName);

            if (sourceCam != null)
            {
                var cameraBody = new GameObject();
                cameraBody.name     = typeof(RasterPropMonitor).Name + index + cameraBody.GetInstanceID();
                cameraObject[index] = cameraBody.AddComponent <Camera>();

                // Just in case to support JSITransparentPod.
                cameraObject[index].cullingMask &= ~(1 << 16 | 1 << 20);

                cameraObject[index].CopyFrom(sourceCam);
                cameraObject[index].enabled       = false;
                cameraObject[index].targetTexture = screenTexture;
                cameraObject[index].aspect        = cameraAspect;
            }
        }
Пример #23
0
 /// <summary>
 /// Set the named persistent variable to the value provided.
 /// </summary>
 /// <param name="name"></param>
 /// <param name="value"></param>
 internal void SetPersistentVariable(string name, object value)
 {
     try
     {
         if (name.Trim().Length == 0)
         {
             JUtil.LogErrorMessage(this, "Trying to set an empty variable name!");
             return;
         }
         persistentVars[name] = value;
         //JUtil.LogMessage(this, "Setting persistent var {0} to {1}", name, value);
     }
     catch
     {
         // Not needed?  Looks like the assignment will add the value.
         persistentVars.Add(name, value);
         //JUtil.LogMessage(this, "Adding persistent var {0} as {1}", name, value);
     }
 }
Пример #24
0
        /**
         * Record the vertex, uv, and color information for a single character.
         */
        private bool DrawChar(FontRenderer fr, char letter, float xPos, float yPos, Color32 letterColor, Script scriptType, Width fontWidth)
        {
            if (fontCharacters.ContainsKey(letter))
            {
                // This code was written for a much older flavor of Unity, and the Unity 2017.1 update broke
                // some assumptions about who managed the y-inversion issue between OpenGL and DX9.
                float yPosition;
                if (manuallyInvertY)
                {
                    yPosition = screenYOffset + ((scriptType == Script.Superscript) ? yPos + fontLetterHalfHeight : yPos);
                }
                else
                {
                    yPosition = screenYOffset - ((scriptType == Script.Superscript) ? yPos - fontLetterHalfHeight : yPos);
                }
                Rect pos = new Rect(screenXOffset + xPos,
                                    yPosition,
                                    (fontWidth == Width.Normal ? fontLetterWidth : (fontWidth == Width.Half ? fontLetterHalfWidth : fontLetterDoubleWidth)),
                                    (scriptType != Script.Normal) ? fontLetterHalfHeight : fontLetterHeight);
                fr.vertices.Add(new Vector3(pos.xMin, pos.yMin, 0.0f));
                fr.vertices.Add(new Vector3(pos.xMax, pos.yMin, 0.0f));
                fr.vertices.Add(new Vector3(pos.xMin, pos.yMax, 0.0f));
                fr.vertices.Add(new Vector3(pos.xMax, pos.yMax, 0.0f));

                Rect uv = fontCharacters[letter];
                fr.uvs.Add(new Vector2(uv.xMin, (manuallyInvertY) ? uv.yMax : uv.yMin));
                fr.uvs.Add(new Vector2(uv.xMax, (manuallyInvertY) ? uv.yMax : uv.yMin));
                fr.uvs.Add(new Vector2(uv.xMin, (manuallyInvertY) ? uv.yMin : uv.yMax));
                fr.uvs.Add(new Vector2(uv.xMax, (manuallyInvertY) ? uv.yMin : uv.yMax));

                fr.colors32.Add(letterColor);
            }
            else if (!characterWarnings.Contains(letter))
            {
                JUtil.LogMessage(this, "Warning: Attempted to print a character \"{0}\" (u{1}) not present in the font.", letter.ToString(), letter);

                characterWarnings.Add(letter);
                return(false);
            }

            return(true);
        }
Пример #25
0
        //--- Throttle control modes -----------------------------------------
        public void ChangeSpeedRef(double mode)
        {
            if (!paFound)
            {
                return;
            }

            SpeedRef speedRef;

            switch ((int)mode)
            {
            case 0:
                speedRef = SpeedRef.True;
                break;

            case 1:
                speedRef = SpeedRef.Indicated;
                break;

            case 2:
                speedRef = SpeedRef.Equivalent;
                break;

            case 3:
                speedRef = SpeedRef.Mach;
                break;

            default:
                return;
            }

            try
            {
                object pilotAssistant = GetPilotAssistant();

                SetSpeedRef(pilotAssistant, new object[] { speedRef });
            }
            catch (Exception e)
            {
                JUtil.LogMessage(this, "ChangeSpeedRef: {0}", e);
            }
        }
Пример #26
0
        private void PointToReferenceCamera()
        {
            isReferenceCamera = true;
            referencePart     = ourVessel.GetReferenceTransformPart();
            ModuleDockingNode thatPort = null;
            ModuleGrappleNode thatClaw = null;

            foreach (PartModule thatModule in ourVessel.GetReferenceTransformPart().Modules)
            {
                thatPort = thatModule as ModuleDockingNode;
                thatClaw = thatModule as ModuleGrappleNode;
                if (thatPort != null || thatClaw != null)
                {
                    break;
                }
            }
            if (thatPort != null || thatClaw != null)
            {
                if (thatPort != null)
                {
                    cameraPart            = thatPort.part;
                    cameraTransform       = ourVessel.ReferenceTransform.gameObject;
                    isReferenceClawCamera = false;
                }
                else if (thatClaw != null)
                {
                    // Mihara: Dirty hack to get around the fact that claws have their reference transform inside the structure.
                    if (LocateCamera(ourVessel.GetReferenceTransformPart(), "ArticulatedCap"))
                    {
                        isReferenceClawCamera = true;
                        clawModule            = thatClaw;
                    }
                    else
                    {
                        JUtil.LogMessage(this, "Claw was not a stock part. Falling back to reference transform position...");
                        cameraPart      = thatClaw.part;
                        cameraTransform = ourVessel.ReferenceTransform.gameObject;
                    }
                }
                CreateCameraObjects();
            }
        }
Пример #27
0
        public void Add(PartResource resource)
        {
            try
            {
                ResourceData res = nameResources[resource.info.name];
                res.current += (float)resource.amount;
                res.max     += (float)resource.maxAmount;

                var flowmode = resource.info.resourceFlowMode;
                if (IsFreeFlow(flowmode))
                {
                    res.stage    += (float)resource.amount;
                    res.stagemax += (float)resource.maxAmount;
                }
            }
            catch (Exception e)
            {
                JUtil.LogErrorMessage(this, "Error adding {0}: {1}", resource.info.name, e);
            }
        }
        /// <summary>
        /// Evaluate the variable, returning it in destination.
        /// </summary>
        /// <param name="destination"></param>
        /// <param name="comp"></param>
        /// <returns></returns>
        public bool Get(out float destination, RPMVesselComputer comp)
        {
            if (!string.IsNullOrEmpty(variableName))
            {
                value = comp.ProcessVariable(variableName).MassageToFloat();
                if (float.IsNaN(value) || float.IsInfinity(value))
                {
                    if (!warningMade)
                    {
                        JUtil.LogMessage(this, "Warning: {0} can fail to produce a usable number.", variableName);
                        warningMade = true;
                    }
                    destination = value;
                    return(false);
                }
            }

            destination = value;
            return(true);
        }
        // I don't like this mess of copypaste, but how can I improve it away?...
        public override void OnUpdate()
        {
            if (!pageActiveState || !JUtil.VesselIsInIVA(vessel) || !UpdateCheck())
            {
                return;
            }

            for (int i = 0; i < 3; i++)
            {
                if (!scaleEnds[i].Get(out scaleResults[i]))
                {
                    return;
                }
            }


            float scaledValue = Mathf.InverseLerp(scaleResults[0], scaleResults[1], scaleResults[2]);

            isInThreshold = (scaledValue >= threshold.x && scaledValue <= threshold.y);
        }
Пример #30
0
        public static void SetCameraCullingMaskForIVA(string cameraName, bool flag)
        {
            Camera thatCamera = JUtil.GetCameraByName(cameraName);

            if (thatCamera != null)
            {
                if (flag)
                {
                    thatCamera.cullingMask |= 1 << 16 | 1 << 20;
                }
                else
                {
                    thatCamera.cullingMask &= ~(1 << 16 | 1 << 20);
                }
            }
            else
            {
                Debug.Log("Could not find camera \"" + cameraName + "\" to change it's culling mask, check your code.");
            }
        }