Пример #1
0
        /**
         * Record the vertex, uv, and color information for a single character.
         */
        private bool DrawChar(FontRenderer fr, char letter, float xPos, float yPos, Color letterColor, Script scriptType, Width fontWidth)
        {
            if (fontCharacters.ContainsKey(letter))
            {
                Rect pos = new Rect(screenXOffset + xPos, screenYOffset - ((scriptType == Script.Superscript) ? yPos - fontLetterHalfHeight : yPos),
                                    (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, uv.yMin));
                fr.uvs.Add(new Vector2(uv.xMax, uv.yMin));
                fr.uvs.Add(new Vector2(uv.xMin, uv.yMax));
                fr.uvs.Add(new Vector2(uv.xMax, uv.yMax));

                fr.colors.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);
        }
Пример #2
0
        /// <summary>
        /// Evaluate the variable, returning it in destination.
        /// </summary>
        /// <param name="destination"></param>
        /// <param name="comp"></param>
        /// <returns></returns>
        public bool Get(out double destination, RPMVesselComputer comp)
        {
            if (type == VoNType.ConstantString)
            {
                destination = 0.0;
                return(false);
            }
            else if (type == VoNType.VariableValue)
            {
                numericValue = comp.ProcessVariable(variableName).MassageToDouble();
                if (double.IsNaN(numericValue) || double.IsInfinity(numericValue))
                {
                    if (!warningMade)
                    {
                        JUtil.LogMessage(this, "Warning: {0} can fail to produce a usable number.", variableName);
                        warningMade = true;
                    }
                    destination = numericValue;
                    return(false);
                }
            }

            destination = numericValue;
            return(true);
        }
Пример #3
0
            public GraphLine(ConfigNode node, double xSpan, Vector2 ySpan, double secondsBetweenSamples, RasterPropMonitorComputer compInstance)
            {
                comp = compInstance;

                maxPoints      = (int)(xSpan / secondsBetweenSamples);
                horizontalSpan = xSpan;
                verticalSpan   = ySpan;
                if (!node.HasData)
                {
                    throw new ArgumentException("Graph block with no data?");
                }
                if (node.HasValue("variableName"))
                {
                    variableName = node.GetValue("variableName").Trim();
                    isFlat       = double.TryParse(variableName, out flatValue);
                }
                else
                {
                    throw new ArgumentException("Draw a graph of what?");
                }

                lineColor = Color.white;
                if (node.HasValue("color"))
                {
                    lineColor = ConfigNode.ParseColor32(node.GetValue("color"));
                }

                floatingMax = node.HasValue("floatingMaximum");
                floatingMin = node.HasValue("floatingMinimum");

                JUtil.LogMessage(this, "Graphing {0} in color {1}", variableName, lineColor);
            }
Пример #4
0
 private void CreateCameraObjects(string newCameraName = null)
 {
     if (!string.IsNullOrEmpty(newCameraName))
     {
         isReferenceCamera     = false;
         isReferenceClawCamera = false; clawModule = null;
         // First, we search our own part for this camera transform,
         // only then we search all other parts of the vessel.
         if (!LocateCamera(ourPart, newCameraName))
         {
             foreach (Part thatpart in ourVessel.parts)
             {
                 if (LocateCamera(thatpart, newCameraName))
                 {
                     break;
                 }
             }
         }
     }
     if (cameraTransform != null)
     {
         CameraSetup(0, "Camera ScaledSpace");
         // These two cameras are created by Visual Enhancements mod.
         // I'm still not completely satisfied with the look, but it's definitely an improvement.
         CameraSetup(1, "Camera VE Underlay");
         CameraSetup(2, "Camera VE Overlay");
         CameraSetup(3, "Camera 01");
         CameraSetup(4, "Camera 00");
         enabled = true;
         JUtil.LogMessage(this, "Switched to camera \"{0}\".", cameraTransform.name);
         return;
     }
     JUtil.LogMessage(this, "Tried to switch to camera \"{0}\" but camera was not found.", newCameraName);
 }
Пример #5
0
        public void Start()
        {
            if (!string.IsNullOrEmpty(borderColor))
            {
                borderColorValue = ConfigNode.ParseColor32(borderColor);
            }
            if (!string.IsNullOrEmpty(backgroundColor))
            {
                backgroundColorValue = ConfigNode.ParseColor32(backgroundColor);
            }

            comp            = RasterPropMonitorComputer.Instantiate(internalProp);
            graphSpace      = new Rect();
            graphSpace.xMin = graphRect.x;
            graphSpace.yMin = graphRect.y;
            graphSpace.xMax = graphRect.z;
            graphSpace.yMax = graphRect.w;
            xGraphSpan      = xSpan;
            interval        = secondsBetweenSamples;
            if (GameDatabase.Instance.ExistsTexture(backgroundTextureURL.EnforceSlashes()))
            {
                backgroundTexture = GameDatabase.Instance.GetTexture(backgroundTextureURL.EnforceSlashes(), false);
            }

            var bottomLeft  = new Vector2(graphSpace.xMin, graphSpace.yMin);
            var bottomRight = new Vector2(graphSpace.xMax, graphSpace.yMin);
            var topLeft     = new Vector2(graphSpace.xMin, graphSpace.yMax);
            var topRight    = new Vector2(graphSpace.xMax, graphSpace.yMax);


            switch (borders)
            {
            case 2:
                borderVertices.Add(bottomRight);
                borderVertices.Add(bottomLeft);
                borderVertices.Add(topLeft);
                break;

            case 4:
                borderVertices.Add(bottomLeft);
                borderVertices.Add(topLeft);
                borderVertices.Add(topRight);
                borderVertices.Add(bottomRight);
                borderVertices.Add(bottomLeft);
                break;
            }

            foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("JSIGRAPHSET"))
            {
                if (node.HasValue("name") && node.GetValue("name") == graphSet)
                {
                    foreach (ConfigNode graphNode in node.GetNodes("GRAPH"))
                    {
                        graphs.Add(new GraphLine(graphNode, xGraphSpan, ySpan, interval, comp));
                    }
                }
            }
            JUtil.LogMessage(this, "Graphing {0} values.", graphs.Count);
            startupComplete = true;
        }
        public void Start()
        {
            if (string.IsNullOrEmpty(soundURL))
            {
                JUtil.LogMessage(this, "JSIInternalBackgroundNoise called with no soundURL");
                Destroy(this);
                return;
            }

            if (needsElectricCharge)
            {
                RPMVesselComputer comp = RPMVesselComputer.Instance(vessel);
                comp.UpdateDataRefreshRate(soundCheckRate);
                electricChargeReserve = comp.ProcessVariable(resourceName).MassageToFloat();
            }
            audioOutput            = new FXGroup("RPM" + internalModel.internalName + vessel.id);
            audioOutput.audio      = internalModel.gameObject.AddComponent <AudioSource>();
            audioOutput.audio.clip = GameDatabase.Instance.GetAudioClip(soundURL.EnforceSlashes());
            audioOutput.audio.Stop();
            audioOutput.audio.volume       = GameSettings.SHIP_VOLUME * soundVolume;
            audioOutput.audio.rolloffMode  = AudioRolloffMode.Logarithmic;
            audioOutput.audio.maxDistance  = 10f;
            audioOutput.audio.minDistance  = 8f;
            audioOutput.audio.dopplerLevel = 0f;
            audioOutput.audio.panStereo    = 0f;
            audioOutput.audio.playOnAwake  = false;
            audioOutput.audio.priority     = 255;
            audioOutput.audio.loop         = true;
            audioOutput.audio.pitch        = 1f;
        }
Пример #7
0
        private static Texture2D LoadFont(object caller, InternalProp thisProp, string location)
        {
            Texture2D font = null;

            if (!string.IsNullOrEmpty(location))
            {
                try
                {
                    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).GetComponent <Renderer>().material.mainTexture;
                        JUtil.LogMessage(caller, "Loading font texture from a transform named \"{0}\"", location);
                    }
                }
                catch (Exception)
                {
                    JUtil.LogErrorMessage(caller, "Failed loading font texture \"{0}\" - missing texture?", location);
                }
            }
            return(font);
        }
Пример #8
0
        public void Start()
        {
            if (string.IsNullOrEmpty(hatchTransform))
            {
                JUtil.LogMessage(this, "Where's my transform?");
                return;
            }
            Transform actualTransform;

            if (internalProp == null)
            {
                actualTransform = internalModel.FindModelTransform(hatchTransform);
                if (!string.IsNullOrEmpty(internalAnimation))
                {
                    intAnim = internalModel.FindModelAnimators(internalAnimation)[0];
                }
            }
            else
            {
                actualTransform = internalProp.FindModelTransform(hatchTransform);
                if (!string.IsNullOrEmpty(internalAnimation))
                {
                    intAnim = internalProp.FindModelAnimators(internalAnimation)[0];
                }
            }
            if (!string.IsNullOrEmpty(internalAnimation) && intAnim == null)
            {
                JUtil.LogErrorMessage(this, "Animation name was not found.");
            }
            // Switching to using the stock button class because right now SmarterButton can't correctly handle doubleclick.
            InternalButton.Create(actualTransform.gameObject).OnDoubleTap(new InternalButton.InternalButtonDelegate(EVAClick));
        }
Пример #9
0
        public void EVAClick()
        {
            Kerbal thatKerbal = part.FindCurrentKerbal();

            if (thatKerbal != null && HighLogic.CurrentGame.Parameters.Flight.CanEVA)
            {
                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, "Could not open the internal EVA hatch, not sure why.");
            }
        }
Пример #10
0
        public static string ProcessString(string input, RPMVesselComputer comp, int propID = -1)
        {
            try
            {
                if (input.IndexOf(JUtil.VariableListSeparator[0], StringComparison.Ordinal) >= 0)
                {
                    string[] tokens = input.Split(JUtil.VariableListSeparator, StringSplitOptions.RemoveEmptyEntries);
                    if (tokens.Length != 2)
                    {
                        return("FORMAT ERROR");
                    }
                    else
                    {
                        string[] vars = tokens[1].Split(JUtil.VariableSeparator, StringSplitOptions.RemoveEmptyEntries);

                        var variables = new object[vars.Length];
                        for (int i = 0; i < vars.Length; i++)
                        {
                            variables[i] = comp.ProcessVariable(vars[i], propID);
                        }
                        string output = string.Format(fp, tokens[0], variables);
                        return(output.TrimEnd());
                    }
                }
            }
            catch (Exception e)
            {
                JUtil.LogMessage(comp, "Bad format on string {0}", input);
                throw e;
            }
            return(input.TrimEnd());
        }
Пример #11
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();
            }
        }
Пример #12
0
            public GraphLine(ConfigNode node, RasterPropMonitorComputer rpmComp, double xSpan, Vector2 ySpan, double secondsBetweenSamples)
            {
                maxPoints      = (int)(xSpan / secondsBetweenSamples);
                horizontalSpan = xSpan;
                verticalSpan   = ySpan;
                if (!node.HasData)
                {
                    throw new ArgumentException("Graph block with no data?");
                }
                string variableName = string.Empty;

                if (node.HasValue("variableName"))
                {
                    variableName = node.GetValue("variableName").Trim();
                    variable     = rpmComp.InstantiateVariableOrNumber(variableName);
                }
                else
                {
                    throw new ArgumentException("Draw a graph of what?");
                }

                lineColor = Color.white;
                if (node.HasValue("color"))
                {
                    lineColor = ConfigNode.ParseColor32(node.GetValue("color"));
                }

                floatingMax = node.HasValue("floatingMaximum");
                floatingMin = node.HasValue("floatingMinimum");

                JUtil.LogMessage(this, "Graphing {0} in color {1}", variableName, lineColor);
            }
 private void DrawChar(char letter, float x, float y, Color letterColor, Script scriptType, Width fontWidth)
 {
     if (fontCharacters.ContainsKey(letter))
     {
         // This is complicated.
         // The destination rectangle has coordinates given in pixels, from top left corner of the texture.
         // The source rectangle has coordinates in normalised texture coordinates (!) from bottom left corner of the texture!
         // And without the LoadPixelMatrix, DrawTexture produces nonsense anyway.
         Graphics.DrawTexture(
             new Rect(x, (scriptType == Script.Subscript) ? y + fontLetterHalfHeight : y,
                      (fontWidth == Width.Normal ? fontLetterWidth : (fontWidth == Width.Half ? fontLetterHalfWidth : fontLetterDoubleWidth)),
                      (scriptType != Script.Normal) ? fontLetterHalfHeight : fontLetterHeight),
             fontTexture[fontTextureIndex],
             fontCharacters[letter],
             0, 0, 0, 0,
             letterColor
             );
     }
     else
     {
         if (!characterWarnings[letter])
         {
             JUtil.LogMessage(this, "Warning: Attempted to print a character \"{0}\" (u{1}) not present in the font.",
                              letter.ToString(), letter);
             characterWarnings[letter] = true;
         }
     }
 }
Пример #14
0
 public void Start()
 {
     foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("INTERNAL"))
     {
         if (node.GetValue("name") == internalModel.internalName)
         {
             foreach (ConfigNode moduleConfig in node.GetNodes("MODULE"))
             {
                 // The order we get should in theory match the order of seats, shouldn't it.
                 if (moduleConfig.HasValue("name") && moduleConfig.GetValue("name") == "InternalSeat")
                 {
                     var seatData = new SeatCamera();
                     seatData.fov      = moduleConfig.GetFloat("fov") ?? defaultFov;
                     seatData.maxRot   = moduleConfig.GetFloat("maxRot") ?? defaultMaxRot;
                     seatData.maxPitch = moduleConfig.GetFloat("maxPitch") ?? defaultMaxPitch;
                     seatData.minPitch = moduleConfig.GetFloat("minPitch") ?? defaultMinPitch;
                     seats.Add(seatData);
                     JUtil.LogMessage(this, "Setting per-seat camera parameters for seat {0}: fov {1}, maxRot {2}, maxPitch {3}, minPitch {4}",
                                      seats.Count - 1, seatData.fov, seatData.maxRot, seatData.maxPitch, seatData.minPitch);
                 }
             }
         }
     }
     // Pseudo-seat with default values.
     seats.Add(new SeatCamera {
         fov      = defaultFov,
         maxRot   = defaultMaxRot,
         maxPitch = defaultMaxPitch,
         minPitch = defaultMinPitch
     });
 }
Пример #15
0
        static JSIChatterer()
        {
            try
            {
                var loadedChattererAssy = AssemblyLoader.loadedAssemblies.FirstOrDefault(a => a.name == "Chatterer");

                if (loadedChattererAssy == null)
                {
                    chattererFound = false;

                    return;
                }

                //--- Process all the reflection info
                // MechJebCore
                chatterer_t = loadedChattererAssy.assembly.GetExportedTypes()
                              .SingleOrDefault(t => t.FullName == "Chatterer.chatterer");
                if (chatterer_t == null)
                {
                    JUtil.LogErrorMessage(null, "Did not find Chatterer.chatterer");
                    return;
                }

                MethodInfo txMethod = chatterer_t.GetMethod("VesselIsTransmitting", BindingFlags.Instance | BindingFlags.Public);
                if (txMethod == null)
                {
                    throw new NotImplementedException("txMethod");
                }
                chattererTx = DynamicMethodDelegateFactory.CreateFuncBool(txMethod);

                MethodInfo rxMethod = chatterer_t.GetMethod("VesselIsReceiving", BindingFlags.Instance | BindingFlags.Public);
                if (rxMethod == null)
                {
                    throw new NotImplementedException("rxMethod");
                }
                chattererRx = DynamicMethodDelegateFactory.CreateFuncBool(rxMethod);

                MethodInfo chatterMethod = chatterer_t.GetMethod("InitiateChatter", BindingFlags.Instance | BindingFlags.Public);
                if (chatterMethod == null)
                {
                    throw new NotImplementedException("chatterMethod");
                }
                chattererStartTalking = DynamicMethodDelegateFactory.CreateAction(chatterMethod);
            }
            catch (Exception e)
            {
                chatterer_t = null;
                JUtil.LogMessage(null, "Exception initializing JSIChatterer: {0}", e);
            }

            if (chatterer_t != null && chattererStartTalking != null)
            {
                chattererFound = true;
            }
            else
            {
                chattererFound = false;
            }
        }
 public void SetVar(string persistentVarName, int varvalue)
 {
     try {
         persistenceStorage.SetVar(persistentVarName, varvalue);
     } catch (NullReferenceException e) {
         JUtil.LogMessage(this, errorMessage, e.Message);
     }
 }
 public int?GetVar(string persistentVarName)
 {
     try {
         return(persistenceStorage.GetVar(persistentVarName));
     } catch (NullReferenceException e) {
         JUtil.LogMessage(this, errorMessage, e.Message);
     }
     return(null);
 }
Пример #18
0
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            try
            {
                ConfigNode moduleConfig = null;
                foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP"))
                {
                    if (node.GetValue("name") == internalProp.propName)
                    {
                        if (string.IsNullOrEmpty(variableName))
                        {
                            JUtil.LogErrorMessage(this, "Configuration failed in prop {0} ({1}), no variableName.", internalProp.propID, internalProp.propName);
                            throw new ArgumentNullException();
                        }

                        moduleConfig = node.GetNodes("MODULE")[moduleID];
                        ConfigNode[] variableNodes = moduleConfig.GetNodes("VARIABLESET");

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


                RPMVesselComputer comp = RPMVesselComputer.Instance(vessel);
                del = (Action <RPMVesselComputer, float>)Delegate.CreateDelegate(typeof(Action <RPMVesselComputer, float>), this, "OnCallback");
                float value = comp.ProcessVariable(variableName).MassageToFloat();
                for (int i = 0; i < variableSets.Count; ++i)
                {
                    variableSets[i].Update(comp, value);
                }
                comp.RegisterCallback(variableName, del);
                JUtil.LogMessage(this, "Configuration complete in prop {1} ({2}), supporting {0} callback animators.", variableSets.Count, internalProp.propID, internalProp.propName);
            }
            catch
            {
                JUtil.AnnoyUser(this);
                enabled = false;
                throw;
            }
        }
Пример #19
0
            private static bool InstantiateHandler(ConfigNode node, Part ourPart, 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 ourPart.Modules)
                {
                    if (potentialModule.ClassName == moduleName)
                    {
                        thatModule = potentialModule;
                        break;
                    }
                }
                if (thatModule == null)
                {
                    try
                    {
                        thatModule = ourPart.AddModule(handlerConfiguration);
                    }
                    catch
                    {
                        JUtil.LogErrorMessage(null, "Caught exception when trying to instantiate module '{0}'. Something's fishy here", moduleName);
                    }
                }
                if (thatModule == null)
                {
                    JUtil.LogMessage(null, "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(null, "Error, incorrect variable handler configuration for module {0}", moduleName);
                            return(false);
                        }
                        break;
                    }
                }
                return(true);
            }
Пример #20
0
        public void Start()
        {
            if (!HighLogic.LoadedSceneIsFlight)
            {
                return;
            }

            bool startedOkay = true;

            for (int i = 0; i < part.Modules.Count; ++i)
            {
                if (part.Modules[i] is MultiModeEngine)
                {
                    if (mmeIndex == -1)
                    {
                        mmeIndex = i;
                        JUtil.LogMessage(this, "Start(): mmeIndex = {0}", i);
                    }
                    else
                    {
                        JUtil.LogErrorMessage(this, "Found more than one MultiModeEngine on {0} - I don't know what to do with it.", part.name);
                        startedOkay = false;
                    }
                }
                else if (part.Modules[i] is ModuleEngines)
                {
                    if (engineMode1Index == -1)
                    {
                        engineMode1Index = i;
                        JUtil.LogMessage(this, "Start(): engineMode1Index = {0}", i);
                    }
                    else if (engineMode2Index == -1)
                    {
                        engineMode2Index = i;
                        JUtil.LogMessage(this, "Start(): engineMode2Index = {0}", i);
                    }
                    else
                    {
                        JUtil.LogErrorMessage(this, "Found more than 2 ModuleEngines on {0} - I don't know what to do with them.", part.name);
                        startedOkay = false;
                    }
                }
            }

            if (engineMode1Index == -1 || !startedOkay)
            {
                JUtil.LogErrorMessage(this, "Unable to initialize - no ModuleEngine, or too many engines");
                Destroy(this);
                // No engines!
            }
            else
            {
                UpdateName();
            }
        }
Пример #21
0
        public JSIParachute(Vessel _vessel)
            : base(_vessel)
        {
            try
            {
                rcModuleRealChute = AssemblyLoader.loadedAssemblies.SelectMany(
                    a => a.assembly.GetExportedTypes())
                                    .SingleOrDefault(t => t.FullName == "RealChute.RealChuteModule");
                if (rcModuleRealChute == null)
                {
                    rcFound = false;
                    if (JUtil.debugLoggingEnabled)
                    {
                        JUtil.LogMessage(this, "A supported version of RealChute is {0}", (rcFound) ? "present" : "not available");
                    }
                    return;
                }

                PropertyInfo rcAnyDeployed = rcModuleRealChute.GetProperty("anyDeployed", BindingFlags.Instance | BindingFlags.Public);
                rcGetAnyDeployed = rcAnyDeployed.GetGetMethod();

                rcArmChute    = rcModuleRealChute.GetMethod("GUIArm", BindingFlags.Instance | BindingFlags.Public);
                rcDisarmChute = rcModuleRealChute.GetMethod("GUIDisarm", BindingFlags.Instance | BindingFlags.Public);
                rcDeployChute = rcModuleRealChute.GetMethod("GUIDeploy", BindingFlags.Instance | BindingFlags.Public);
                rcCutChute    = rcModuleRealChute.GetMethod("GUICut", BindingFlags.Instance | BindingFlags.Public);

                rcArmed = rcModuleRealChute.GetField("armed", BindingFlags.Instance | BindingFlags.Public);
            }
            catch (Exception)
            {
                rcModuleRealChute = null;
                rcGetAnyDeployed  = null;
                rcArmChute        = null;
                rcDisarmChute     = null;
                rcDeployChute     = null;
                rcCutChute        = null;
                rcArmed           = null;
            }

            if (rcModuleRealChute != null && rcArmChute != null &&
                rcGetAnyDeployed != null && rcDisarmChute != null && rcDeployChute != null &&
                rcCutChute != null && rcArmed != null)
            {
                rcFound = true;
            }
            else
            {
                rcFound = false;
            }

            if (JUtil.debugLoggingEnabled)
            {
                JUtil.LogMessage(this, "A supported version of RealChute is {0}", (rcFound) ? "present" : "not available");
            }
        }
Пример #22
0
        private bool PointToReferenceCamera()
        {
            isReferenceCamera = true;
            referencePart     = ourVessel.GetReferenceTransformPart();
            ModuleDockingNode thatPort = null;
            ModuleGrappleNode thatClaw = null;

            if (referencePart != null)
            {
                foreach (PartModule thatModule in referencePart.Modules)
                {
                    thatPort = thatModule as ModuleDockingNode;
                    thatClaw = thatModule as ModuleGrappleNode;
                    if (thatPort != null || thatClaw != null)
                    {
                        break;
                    }
                }
            }

            if (thatPort != null)
            {
                if (!LocateCamera(referencePart, "dockingNode"))
                {
                    cameraPart                 = thatPort.part;
                    cameraTransform            = ourVessel.ReferenceTransform.gameObject;
                    isReferenceTransformCamera = true;
                }
                isReferenceClawCamera = false;
                return(CreateCameraObjects());
            }
            else if (thatClaw != null)
            {
                // Mihara: Dirty hack to get around the fact that claws have their reference transform inside the structure.
                if (LocateCamera(referencePart, "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;
                }

                return(CreateCameraObjects());
            }
            else
            {
                return(false);
            }
        }
 public void Start()
 {
     foreach (string seatNumberString in visibleFromSeats.Split(','))
     {
         int result;
         if (int.TryParse(seatNumberString.Trim(), out result) && result >= 0)
         {
             JUtil.LogMessage(this, "Running in prop '{2}' with ID {1}, will be visible from seat {0}", result, internalProp.propID, internalProp.name);
             seatNumbers.Add(result);
         }
         JUtil.HideShowProp(internalProp, false);
     }
 }
Пример #24
0
        public void Start()
        {
            comp             = RasterPropMonitorComputer.Instantiate(internalProp);
            textObjTransform = internalProp.FindModelTransform(labelTransform);
            textObj          = InternalComponents.Instance.CreateText(fontName, fontSize, textObjTransform, string.Empty);
            activeLabel      = 0;

            SmarterButton.CreateButton(internalProp, switchTransform, Click);

            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 {
                            labelsEx.Add(new VariableLabelSet(variableNodes[i]));
                        } 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 (labelsEx.Count < 1 && moduleConfig != null)
            {
                try {
                    labelsEx.Add(new VariableLabelSet(moduleConfig));
                } catch (ArgumentException e) {
                    JUtil.LogMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID);
                }
            }

            colorShiftRenderer = internalProp.FindModelComponent <Renderer>(coloredObject);
            if (labelsEx[activeLabel].hasColor)
            {
                colorShiftRenderer.material.SetColor(colorName, labelsEx[activeLabel].color);
            }
            textObj.text.Text = StringProcessor.ProcessString(labelsEx[activeLabel].labelText, comp);

            audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false);
            JUtil.LogMessage(this, "Configuration complete in prop {1}, supporting {0} variable indicators.", labelsEx.Count, internalProp.propID);
        }
Пример #25
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();
                if (string.IsNullOrEmpty(vesselDescriptionForDisplay))
                {
                    vesselDescriptionForDisplay = " "; // Workaround for issue #466.
                }

                // 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());
                    }
                }
            }
        }
Пример #26
0
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            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;
            }
        }
Пример #27
0
        public static void PatchMaterial()
        {
            if (ranPatch)
            {
                return;
            }
            ranPatch = true;

            try
            {
                var scansatAssembly = AssemblyLoader.loadedAssemblies.FirstOrDefault(assembly => assembly.name == "SCANsat");

                // no scansat, nothing to do
                if (scansatAssembly == null)
                {
                    return;
                }

                var jutil_t = scansatAssembly.assembly.GetExportedTypes().SingleOrDefault(t => t.FullName == "SCANsat.JUtil");

                // can't find the type? weird...
                if (jutil_t == null)
                {
                    JUtil.LogErrorMessage("scansat", "no jutil type found");
                    return;
                }

                var lineMatFieldInfo = jutil_t.GetField("LineMat");

                if (lineMatFieldInfo == null)
                {
                    JUtil.LogErrorMessage("scansat", "unable to find LineMat field info; valid fields are {0}",
                                          string.Join(", ", jutil_t.GetFields().Select(field => field.Name)));
                    return;
                }

                var lineMaterial = new Material(Shader.Find("KSP/Particles/Alpha Blended"));
                lineMaterial.hideFlags        = HideFlags.HideAndDontSave;
                lineMaterial.shader.hideFlags = HideFlags.HideAndDontSave;

                lineMatFieldInfo.SetValue(null, lineMaterial);
                JUtil.LogMessage("scansat", "patched linematerial");
            }
            catch (Exception e)
            {
                JUtil.LogErrorMessage("scansat", e.Message);
            }
        }
Пример #28
0
        public void Start()
        {
            if (!HighLogic.LoadedSceneIsFlight)
            {
                return;
            }

            for (int i = 0; i < part.Modules.Count; ++i)
            {
                if (part.Modules[i] is MultiModeEngine)
                {
                    if (mmeIndex == -1)
                    {
                        mmeIndex = i;
                        JUtil.LogMessage(this, "Start(): mmeIndex = {0}", i);
                    }
                    else
                    {
                        JUtil.LogErrorMessage(this, "Found more than one MultiModeEngine on {0} - I don't know what to do with it.", part.name);
                    }
                }
                else if (part.Modules[i] is ModuleEngines)
                {
                    if (engineMode1Index == -1)
                    {
                        engineMode1Index = i;
                        JUtil.LogMessage(this, "Start(): engineMode1Index = {0}", i);
                    }
                    else if (engineMode2Index == -1)
                    {
                        engineMode2Index = i;
                        JUtil.LogMessage(this, "Start(): engineMode2Index = {0}", i);
                    }
                    else
                    {
                        JUtil.LogErrorMessage(this, "Found more than 2 ModuleEngines on {0} - I don't know what to do with them.", part.name);
                    }
                }
            }

            if (engineMode1Index == -1)
            {
                Destroy(this);
                // No engines!
            }
            UpdateName();
        }
Пример #29
0
        // Oberth phase angle: transfer moon -> another planet
        private static double UpdatePhaseAngleOberth(Vessel vessel, Orbit srcOrbit, Orbit destOrbit)
        {
            if (destOrbit == null)
            {
                JUtil.LogMessage(null, "!!! UpdatePhaseAngleOberth got a NULL orbit !!!");
                return(0.0);
            }

            //double srcAlt = CalcMeanAlt(srcOrbit);
            //double destAlt = CalcMeanAlt(destOrbit);

            double phase = CurrentPhase(srcOrbit, destOrbit) - OberthDesiredPhase(vessel, destOrbit);

            phase = (phase + 360.0) % 360.0;

            return(phase);
        }
Пример #30
0
        // Adjacent phase angle: transfer planet -> planet or moon -> moon
        private static double UpdatePhaseAngleAdjacent(Vessel vessel, Orbit srcOrbit, Orbit destOrbit)
        {
            if (destOrbit == null)
            {
                JUtil.LogMessage(null, "!!! UpdatePhaseAngleAdjacent got a NULL orbit !!!");
                return(0.0);
            }

            double srcAlt  = CalcMeanAlt(srcOrbit);
            double destAlt = CalcMeanAlt(destOrbit);

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

            phase = (phase + 360.0) % 360.0;

            return(phase);
        }