Beispiel #1
0
        public void Start()
        {
            string[] tokens = scale.Split(',');

            if (tokens.Length == 2)
            {
                //comp = RasterPropMonitorComputer.Instantiate(internalProp);
                scaleEnds[0] = new VariableOrNumber(tokens[0], this);
                scaleEnds[1] = new VariableOrNumber(tokens[1], this);
                scaleEnds[2] = new VariableOrNumber(variableName, this);

                textIn  = JUtil.LoadPageDefinition(definitionIn);
                textOut = JUtil.LoadPageDefinition(definitionOut);

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

                persistence = new PersistenceAccessor(internalProp);
            }
            else
            {
                JUtil.LogErrorMessage(this, "Could not parse the 'scale' parameter: {0}", scale);
            }
        }
        internal SelectVariable(ConfigNode node)
        {
            name = node.GetValue("name");

            foreach (ConfigNode sourceVarNode in node.GetNodes("VARIABLE_DEFINITION"))
            {
                bool reverseVal;
                VariableOrNumberRange vonr = ProcessSourceNode(sourceVarNode, out reverseVal);

                sourceVariables.Add(vonr);
                reverse.Add(reverseVal);

                VariableOrNumber val = VariableOrNumber.Instantiate(sourceVarNode.GetValue("value"));
                result.Add(val);
            }

            if (node.HasValue("defaultValue"))
            {
                VariableOrNumber val = VariableOrNumber.Instantiate(node.GetValue("defaultValue"));
                result.Add(val);
            }
            else
            {
                throw new Exception(string.Format("Select variable {0} is missing its defaultValue", name));
            }

            if (sourceVariables.Count == 0)
            {
                throw new ArgumentException("Did not find any VARIABLE_DEFINITION nodes in RPM_SELECT_VARIABLE", name);
            }
        }
Beispiel #3
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);
            }
        /// <summary>
        /// Create a new VariableOrNumber, or return an existing one that
        /// tracks the same value.
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static VariableOrNumber Instantiate(string input)
        {
            string varName = input.Trim();
            float  floatval;

            if (float.TryParse(varName, out floatval))
            {
                // If it's a numeric value, let's canonicalize it using
                // ToString, so we don't have duplicates that evaluate to the
                // same value (eg, 1.0, 1, 1.00, etc).
                varName = floatval.ToString();
            }

            if (varName == "MetersToFeet")
            {
                varName = RPMVesselComputer.MetersToFeet.ToString();
            }
            else if (varName == "MetersPerSecondToKnots")
            {
                varName = RPMVesselComputer.MetersPerSecondToKnots.ToString();
            }

            if (!vars.ContainsKey(varName))
            {
                VariableOrNumber VoN = new VariableOrNumber(varName);
                vars.Add(varName, VoN);
                //JUtil.LogMessage(null, "Adding VoN {0}", varName);
            }
            return(vars[varName]);
        }
        public void Start()
        {
            string[] tokens = scale.Split(',');

            if (tokens.Length == 2)
            {

                //comp = RasterPropMonitorComputer.Instantiate(internalProp);
                scaleEnds[0] = new VariableOrNumber(tokens[0], this);
                scaleEnds[1] = new VariableOrNumber(tokens[1], this);
                scaleEnds[2] = new VariableOrNumber(variableName, this);

                textIn = JUtil.LoadPageDefinition(definitionIn);
                textOut = JUtil.LoadPageDefinition(definitionOut);

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

                persistence = new PersistenceAccessor(internalProp);
            }
            else
            {
                JUtil.LogErrorMessage(this, "Could not parse the 'scale' parameter: {0}", scale);
            }
        }
Beispiel #6
0
        public MappedVariable(ConfigNode node, RasterPropMonitorComputer rpmComp)
        {
            if (!node.HasValue("mappedVariable") || !node.HasValue("mappedRange") || !node.HasValue("sourceVariable") || !node.HasValue("sourceRange"))
            {
                throw new ArgumentException("MappedVariable missing required values");
            }

            string sourceVariableStr = node.GetValue("sourceVariable");
            string sourceRange       = node.GetValue("sourceRange");

            string[] sources = sourceRange.Split(',');
            if (sources.Length != 2)
            {
                throw new ArgumentException("MappedVariable sourceRange does not have exactly two values");
            }

            sourceVariable = new VariableOrNumberRange(rpmComp, sourceVariableStr, sources[0], sources[1]);

            mappedVariable = node.GetValue("mappedVariable");
            string[] destinations = node.GetValue("mappedRange").Split(',');
            if (destinations.Length != 2)
            {
                throw new ArgumentException("MappedVariable mappedRange does not have exactly two values");
            }
            mappedExtent1 = rpmComp.InstantiateVariableOrNumber(destinations[0]);
            mappedExtent2 = rpmComp.InstantiateVariableOrNumber(destinations[1]);
        }
        public MappedVariable(ConfigNode node, RasterPropMonitorComputer rpmComp)
        {
            if (!node.HasValue("mappedVariable") || !node.HasValue("mappedRange") || !node.HasValue("sourceVariable") || !node.HasValue("sourceRange"))
            {
                throw new ArgumentException("MappedVariable missing required values");
            }

            string sourceVariableStr = node.GetValue("sourceVariable");
            string sourceRange = node.GetValue("sourceRange");
            string[] sources = sourceRange.Split(',');
            if (sources.Length != 2)
            {
                throw new ArgumentException("MappedVariable sourceRange does not have exactly two values");
            }

            sourceVariable = new VariableOrNumberRange(rpmComp, sourceVariableStr, sources[0], sources[1]);

            mappedVariable = node.GetValue("mappedVariable");
            string[] destinations = node.GetValue("mappedRange").Split(',');
            if (destinations.Length != 2)
            {
                throw new ArgumentException("MappedVariable mappedRange does not have exactly two values");
            }
            mappedExtent1 = rpmComp.InstantiateVariableOrNumber(destinations[0]);
            mappedExtent2 = rpmComp.InstantiateVariableOrNumber(destinations[1]);
        }
 public VariableOrNumberRange(RasterPropMonitorComputer rpmComp, string sourceVariable, string range1, string range2, string moduloVariable = null)
 {
     sourceValue = rpmComp.InstantiateVariableOrNumber(sourceVariable);
     lowerBound  = rpmComp.InstantiateVariableOrNumber(range1);
     upperBound  = rpmComp.InstantiateVariableOrNumber(range2);
     if (!string.IsNullOrEmpty(moduloVariable))
     {
         modulo = rpmComp.InstantiateVariableOrNumber(moduloVariable);
     }
 }
        internal MathVariable(ConfigNode node)
        {
            name = node.GetValue("name");

            string[] sources = node.GetValues("sourceVariable");
            for (int i = 0; i < sources.Length; ++i)
            {
                VariableOrNumber sv = VariableOrNumber.Instantiate(sources[i]);
                sourceVariables.Add(sv);
            }

            if (sourceVariables.Count == 0)
            {
                throw new ArgumentException("Did not find any SOURCE_VARIABLE nodes in RPM_CUSTOM_VARIABLE", name);
            }

            string oper = node.GetValue("operator");

            if (oper == Operator.NONE.ToString())
            {
                op = Operator.NONE;
            }
            else if (oper == Operator.ADD.ToString())
            {
                op = Operator.ADD;
            }
            else if (oper == Operator.SUBTRACT.ToString())
            {
                op = Operator.SUBTRACT;
            }
            else if (oper == Operator.MULTIPLY.ToString())
            {
                op = Operator.MULTIPLY;
            }
            else if (oper == Operator.DIVIDE.ToString())
            {
                op = Operator.DIVIDE;
            }
            else if (oper == Operator.MAX.ToString())
            {
                op = Operator.MAX;
            }
            else if (oper == Operator.MIN.ToString())
            {
                op = Operator.MIN;
            }
            else
            {
                throw new ArgumentException("Found an invalid operator type in RPM_CUSTOM_VARIABLE", oper);
            }
        }
Beispiel #10
0
        public void OnDestroy()
        {
            //JUtil.LogMessage(this, "OnDestroy()");
            if (colorShiftMaterial != null)
            {
                UnityEngine.Object.Destroy(colorShiftMaterial);
                colorShiftMaterial = null;
            }
            actionHandler  = null;
            transferGetter = null;
            transferSetter = null;
            audioOutput    = null;
            loopingOutput  = null;

            if (del != null)
            {
                rpmComp.UnregisterResourceCallback(resourceName, del);
            }
        }
        public VariableAnimationSet(ConfigNode node, InternalProp thisProp)
        {
            part = thisProp.part;

            if (!node.HasData)
            {
                throw new ArgumentException("No data?!");
            }

            string[] tokens = { };

            if (node.HasValue("scale"))
            {
                tokens = node.GetValue("scale").Split(',');
            }

            if (tokens.Length != 2)
            {
                throw new ArgumentException("Could not parse 'scale' parameter.");
            }

            if (node.HasValue("variableName"))
            {
                string variableName;
                variableName = node.GetValue("variableName").Trim();
                scaleEnds[2] = new VariableOrNumber(variableName, this);
            }
            else if (node.HasValue("stateMethod"))
            {
                RPMVesselComputer comp          = RPMVesselComputer.Instance(part.vessel);
                Func <bool>       stateFunction = (Func <bool>)comp.GetMethod(node.GetValue("stateMethod").Trim(), thisProp, typeof(Func <bool>));
                if (stateFunction != null)
                {
                    scaleEnds[2] = new VariableOrNumber(stateFunction, this);
                }
                else
                {
                    throw new ArgumentException("Unrecognized stateMethod");
                }
            }
            else
            {
                throw new ArgumentException("Missing variable name.");
            }

            scaleEnds[0] = new VariableOrNumber(tokens[0], this);
            scaleEnds[1] = new VariableOrNumber(tokens[1], this);

            // That takes care of the scale, now what to do about that scale:

            if (node.HasValue("reverse"))
            {
                if (!bool.TryParse(node.GetValue("reverse"), out reverse))
                {
                    throw new ArgumentException("So is 'reverse' true or false?");
                }
            }

            if (node.HasValue("animationName"))
            {
                animationName = node.GetValue("animationName");
                if (node.HasValue("animationSpeed"))
                {
                    animationSpeed = float.Parse(node.GetValue("animationSpeed"));

                    if (reverse)
                    {
                        animationSpeed = -animationSpeed;
                    }
                }
                else
                {
                    animationSpeed = 0.0f;
                }
                Animation[] anims = node.HasValue("animateExterior") ? thisProp.part.FindModelAnimators(animationName) : thisProp.FindModelAnimators(animationName);
                if (anims.Length > 0)
                {
                    onAnim         = anims[0];
                    onAnim.enabled = true;
                    onAnim[animationName].speed          = 0;
                    onAnim[animationName].normalizedTime = reverse ? 1f : 0f;
                    looping = node.HasValue("loopingAnimation");
                    if (looping)
                    {
                        onAnim[animationName].wrapMode = WrapMode.Loop;
                        onAnim.wrapMode             = WrapMode.Loop;
                        onAnim[animationName].speed = animationSpeed;
                        mode = Mode.LoopingAnimation;
                    }
                    else
                    {
                        onAnim[animationName].wrapMode = WrapMode.Once;
                        mode = Mode.Animation;
                    }
                    onAnim.Play();
                    alwaysActive = node.HasValue("animateExterior");
                }
                else
                {
                    throw new ArgumentException("Animation could not be found.");
                }

                if (node.HasValue("stopAnimationName"))
                {
                    stopAnimationName = node.GetValue("stopAnimationName");
                    anims             = node.HasValue("animateExterior") ? thisProp.part.FindModelAnimators(stopAnimationName) : thisProp.FindModelAnimators(stopAnimationName);
                    if (anims.Length > 0)
                    {
                        offAnim         = anims[0];
                        offAnim.enabled = true;
                        offAnim[stopAnimationName].speed          = 0;
                        offAnim[stopAnimationName].normalizedTime = reverse ? 1f : 0f;
                        if (looping)
                        {
                            offAnim[stopAnimationName].wrapMode = WrapMode.Loop;
                            offAnim.wrapMode = WrapMode.Loop;
                            offAnim[stopAnimationName].speed = animationSpeed;
                            mode = Mode.LoopingAnimation;
                        }
                        else
                        {
                            offAnim[stopAnimationName].wrapMode = WrapMode.Once;
                            mode = Mode.Animation;
                        }
                    }
                }
            }
            else if (node.HasValue("activeColor") && node.HasValue("passiveColor") && node.HasValue("coloredObject"))
            {
                if (node.HasValue("colorName"))
                {
                    colorName = node.GetValue("colorName");
                }
                passiveColor       = ConfigNode.ParseColor32(node.GetValue("passiveColor"));
                activeColor        = ConfigNode.ParseColor32(node.GetValue("activeColor"));
                colorShiftRenderer = thisProp.FindModelComponent <Renderer>(node.GetValue("coloredObject"));
                colorShiftRenderer.material.SetColor(colorName, reverse ? activeColor : passiveColor);
                mode = Mode.Color;
            }
            else if (node.HasValue("controlledTransform") && node.HasValue("localRotationStart") && node.HasValue("localRotationEnd"))
            {
                controlledTransform = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim());
                initialRotation     = controlledTransform.localRotation;
                if (node.HasValue("longPath"))
                {
                    longPath    = true;
                    vectorStart = ConfigNode.ParseVector3(node.GetValue("localRotationStart"));
                    vectorEnd   = ConfigNode.ParseVector3(node.GetValue("localRotationEnd"));
                }
                else
                {
                    rotationStart = Quaternion.Euler(ConfigNode.ParseVector3(node.GetValue("localRotationStart")));
                    rotationEnd   = Quaternion.Euler(ConfigNode.ParseVector3(node.GetValue("localRotationEnd")));
                }
                mode = Mode.Rotation;
            }
            else if (node.HasValue("controlledTransform") && node.HasValue("localTranslationStart") && node.HasValue("localTranslationEnd"))
            {
                controlledTransform = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim());
                initialPosition     = controlledTransform.localPosition;
                vectorStart         = ConfigNode.ParseVector3(node.GetValue("localTranslationStart"));
                vectorEnd           = ConfigNode.ParseVector3(node.GetValue("localTranslationEnd"));
                mode = Mode.Translation;
            }
            else if (node.HasValue("controlledTransform") && node.HasValue("localScaleStart") && node.HasValue("localScaleEnd"))
            {
                controlledTransform = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim());
                initialScale        = controlledTransform.localScale;
                vectorStart         = ConfigNode.ParseVector3(node.GetValue("localScaleStart"));
                vectorEnd           = ConfigNode.ParseVector3(node.GetValue("localScaleEnd"));
                mode = Mode.Scale;
            }
            else if (node.HasValue("controlledTransform") && node.HasValue("textureLayers") && node.HasValue("textureShiftStart") && node.HasValue("textureShiftEnd"))
            {
                affectedMaterial  = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim()).renderer.material;
                textureLayer      = node.GetValue("textureLayers");
                textureShiftStart = ConfigNode.ParseVector2(node.GetValue("textureShiftStart"));
                textureShiftEnd   = ConfigNode.ParseVector2(node.GetValue("textureShiftEnd"));
                mode = Mode.TextureShift;
            }
            else if (node.HasValue("controlledTransform") && node.HasValue("textureLayers") && node.HasValue("textureScaleStart") && node.HasValue("textureScaleEnd"))
            {
                affectedMaterial  = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim()).renderer.material;
                textureLayer      = node.GetValue("textureLayers");
                textureScaleStart = ConfigNode.ParseVector2(node.GetValue("textureScaleStart"));
                textureScaleEnd   = ConfigNode.ParseVector2(node.GetValue("textureScaleEnd"));
                mode = Mode.TextureScale;
            }
            else
            {
                throw new ArgumentException("Cannot initiate any of the possible action modes.");
            }

            if (node.HasValue("threshold"))
            {
                threshold = ConfigNode.ParseVector2(node.GetValue("threshold"));
            }

            resourceAmount = 0.0f;
            if (threshold != Vector2.zero)
            {
                thresholdMode = true;

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

                if (node.HasValue("flashingDelay"))
                {
                    flashingDelay = double.Parse(node.GetValue("flashingDelay"));
                }

                if (node.HasValue("alarmSound"))
                {
                    alarmSoundVolume = 0.5f;
                    if (node.HasValue("alarmSoundVolume"))
                    {
                        alarmSoundVolume = float.Parse(node.GetValue("alarmSoundVolume"));
                    }
                    audioOutput = JUtil.SetupIVASound(thisProp, node.GetValue("alarmSound"), alarmSoundVolume, false);
                    if (node.HasValue("alarmMustPlayOnce"))
                    {
                        if (!bool.TryParse(node.GetValue("alarmMustPlayOnce"), out alarmMustPlayOnce))
                        {
                            throw new ArgumentException("So is 'alarmMustPlayOnce' true or false?");
                        }
                    }
                    if (node.HasValue("alarmShutdownButton"))
                    {
                        SmarterButton.CreateButton(thisProp, node.GetValue("alarmShutdownButton"), AlarmShutdown);
                    }
                    if (node.HasValue("alarmSoundLooping"))
                    {
                        if (!bool.TryParse(node.GetValue("alarmSoundLooping"), out alarmSoundLooping))
                        {
                            throw new ArgumentException("So is 'alarmSoundLooping' true or false?");
                        }
                        audioOutput.audio.loop = alarmSoundLooping;
                    }
                }

                if (node.HasValue("resourceAmount"))
                {
                    resourceAmount = float.Parse(node.GetValue("resourceAmount"));
                }

                TurnOff();
            }
        }
Beispiel #12
0
        internal HorizontalBar(ConfigNode node, float screenWidth, float screenHeight, int drawingLayer, Shader displayShader, GameObject cameraBody)
        {
            JUtil.LogMessage(this, "Configuring for {0}", node.GetValue("name"));
            if (!node.HasValue("variableName"))
            {
                throw new Exception("HorizontalBar " + node.GetValue("name") + " missing variableName");
            }
            variable = VariableOrNumber.Instantiate(node.GetValue("variableName"));

            if (!node.HasValue("texture"))
            {
                throw new Exception("HorizontalBar " + node.GetValue("name") + " missing texture");
            }

            Texture2D tex = GameDatabase.Instance.GetTexture(node.GetValue("texture"), false);

            if (tex == null)
            {
                throw new Exception("HorizontalBar " + node.GetValue("name") + " texture " + node.GetValue("texture") + " can't be loaded.");
            }
            tex.wrapMode = TextureWrapMode.Clamp;

            if (node.HasValue("useLog10") && bool.TryParse(node.GetValue("useLog10"), out useLog10) == false)
            {
                // I think this is redundant
                useLog10 = false;
            }

            if (!node.HasValue("scale"))
            {
                throw new Exception("HorizontalBar " + node.GetValue("name") + " missing scale");
            }

            scale = ConfigNode.ParseVector2(node.GetValue("scale"));
            if (useLog10)
            {
                scale.x = JUtil.PseudoLog10(scale.x);
                scale.y = JUtil.PseudoLog10(scale.y);
            }

            if (!node.HasValue("textureSize"))
            {
                throw new Exception("HorizontalBar " + node.GetValue("name") + " missing textureSize");
            }

            if (!float.TryParse(node.GetValue("textureSize"), out textureSize))
            {
                throw new Exception("HorizontalBar " + node.GetValue("name") + " failed parsing textureSize");
            }

            textureSize = 0.5f * textureSize / (float)tex.width;

            if (!node.HasValue("textureLimit"))
            {
                throw new Exception("HorizontalBar " + node.GetValue("name") + " missing textureLimit");
            }

            textureLimit   = ConfigNode.ParseVector2(node.GetValue("textureLimit"));
            textureLimit.x = 1.0f - textureLimit.x / (float)tex.width;
            textureLimit.y = 1.0f - textureLimit.y / (float)tex.width;

            if (!node.HasValue("position"))
            {
                throw new Exception("HorizontalBar " + node.GetValue("name") + " missing position");
            }

            Vector4 position = ConfigNode.ParseVector4(node.GetValue("position"));

            if (node.HasValue("enablingVariable") && node.HasValue("enablingVariableRange"))
            {
                string[] range = node.GetValue("enablingVariableRange").Split(',');
                if (range.Length != 2)
                {
                    throw new Exception("HorizontalBar " + node.GetValue("name") + " has an invalid enablingVariableRange");
                }

                enablingVariable = new VariableOrNumberRange(node.GetValue("enablingVariable").Trim(), range[0].Trim(), range[1].Trim());
            }

            barObject = JUtil.CreateSimplePlane("HorizontalBar" + node.GetValue("name"), new Vector2(0.5f * position.z, 0.5f * position.w), new Rect(0.0f, 0.0f, 1.0f, 1.0f), drawingLayer);

            Material barMaterial = new Material(displayShader);

            barMaterial.color       = Color.white;
            barMaterial.mainTexture = tex;

            // Position in camera space has (0, 0) in the center, so we need to
            // translate everything appropriately.  Y is odd since the coordinates
            // supplied are Left-Handed (0Y on top, growing down), not RH.
            barObject.transform.position = new Vector3(position.x + 0.5f * (position.z - screenWidth), 0.5f * (screenHeight - position.w) - position.y, 1.4f);
            barObject.GetComponent <Renderer>().material = barMaterial;
            barObject.transform.parent = cameraBody.transform;

            JUtil.ShowHide(true, barObject);
        }
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
                return;

            try
            {

                if (!groupList.ContainsKey(actionName) && !customGroupList.ContainsKey(actionName))
                {
                    JUtil.LogErrorMessage(this, "Action \"{0}\" is not supported.", actionName);
                    return;
                }

                // Parse the needs-electric-charge here.
                if (!string.IsNullOrEmpty(needsElectricCharge))
                {
                    switch (needsElectricCharge.ToLowerInvariant().Trim())
                    {
                        case "true":
                        case "yes":
                        case "1":
                            needsElectricChargeValue = true;
                            break;
                        case "false":
                        case "no":
                        case "0":
                            needsElectricChargeValue = false;
                            break;
                    }
                }

                // Now parse consumeOnToggle and consumeWhileActive...
                if (!string.IsNullOrEmpty(consumeOnToggle))
                {
                    string[] tokens = consumeOnToggle.Split(',');
                    if (tokens.Length == 3)
                    {
                        consumeOnToggleName = tokens[0].Trim();
                        if (!(PartResourceLibrary.Instance.GetDefinition(consumeOnToggleName) != null &&
                           float.TryParse(tokens[1].Trim(), NumberStyles.Any, CultureInfo.InvariantCulture,
                               out consumeOnToggleAmount)))
                        {
                            JUtil.LogErrorMessage(this, "Could not parse \"{0}\"", consumeOnToggle);
                        }
                        switch (tokens[2].Trim().ToLower())
                        {
                            case "on":
                                consumingOnToggleUp = true;
                                break;
                            case "off":
                                consumingOnToggleDown = true;
                                break;
                            case "both":
                                consumingOnToggleUp = true;
                                consumingOnToggleDown = true;
                                break;
                            default:
                                JUtil.LogErrorMessage(this, "So should I consume resources when turning on, turning off, or both in \"{0}\"?", consumeOnToggle);
                                break;
                        }
                    }
                }

                if (!string.IsNullOrEmpty(consumeWhileActive))
                {
                    string[] tokens = consumeWhileActive.Split(',');
                    if (tokens.Length == 2)
                    {
                        consumeWhileActiveName = tokens[0].Trim();
                        if (!(PartResourceLibrary.Instance.GetDefinition(consumeWhileActiveName) != null &&
                           float.TryParse(tokens[1].Trim(),
                               NumberStyles.Any, CultureInfo.InvariantCulture,
                               out consumeWhileActiveAmount)))
                        {
                            JUtil.LogErrorMessage(this, "Could not parse \"{0}\"", consumeWhileActive);
                        }
                        else
                        {
                            consumingWhileActive = true;
                            JUtil.LogMessage(this, "Switch in prop {0} prop id {1} will consume {2} while active at a rate of {3}", internalProp.propName,
                                internalProp.propID, consumeWhileActiveName, consumeWhileActiveAmount);
                        }
                    }
                }

                if (groupList.ContainsKey(actionName))
                {
                    currentState = vessel.ActionGroups[groupList[actionName]];
                    // action group switches may not belong to a radio group
                    switchGroupIdentifier = -1;
                }
                else
                {
                    isCustomAction = true;
                    switch (actionName)
                    {
                        case "intlight":
                            persistentVarName = internalLightName;
                            lightObjects = internalModel.FindModelComponents<Light>();
                            needsElectricChargeValue |= string.IsNullOrEmpty(needsElectricCharge) || needsElectricChargeValue;
                            break;
                        case "plugin":
                            persistentVarName = string.Empty;
                            comp = RasterPropMonitorComputer.Instantiate(internalProp);
                            comp.UpdateRefreshRates(lightCheckRate, lightCheckRate);

                            foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP"))
                            {
                                if (node.GetValue("name") == internalProp.propName)
                                {
                                    foreach (ConfigNode pluginConfig in node.GetNodes("MODULE")[moduleID].GetNodes("PLUGINACTION"))
                                    {
                                        if (pluginConfig.HasValue("name") && pluginConfig.HasValue("actionMethod"))
                                        {
                                            string action = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("actionMethod").Trim();
                                            actionHandler = (Action<bool>)comp.GetMethod(action, internalProp, typeof(Action<bool>));

                                            if (actionHandler == null)
                                            {
                                                JUtil.LogErrorMessage(this, "Failed to instantiate action handler {0}", pluginConfig.GetValue("name"));
                                            }
                                            else
                                            {
                                                if (pluginConfig.HasValue("stateMethod"))
                                                {
                                                    string state = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("stateMethod").Trim();
                                                    stateHandler = (Func<bool>)comp.GetMethod(state, internalProp, typeof(Func<bool>));
                                                }
                                                isPluginAction = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            if (actionHandler == null)
                            {
                                actionName = "dummy";
                                JUtil.LogMessage(this, "Plugin handlers did not start, reverting to dummy mode.");
                            }
                            break;
                        default:
                            persistentVarName = "switch" + internalProp.propID + "_" + moduleID;
                            break;
                    }
                    if (!string.IsNullOrEmpty(perPodPersistenceName))
                    {
                        persistentVarName = perPodPersistenceName;
                    }
                    else
                    {
                        // If there's no persistence name, there's no valid group id for this switch
                        switchGroupIdentifier = -1;
                    }
                }

                if (needsElectricChargeValue || !string.IsNullOrEmpty(persistentVarName) || !string.IsNullOrEmpty(perPodMasterSwitchName) || !string.IsNullOrEmpty(masterVariableName))
                {
                    if (comp == null)
                    {
                        comp = RasterPropMonitorComputer.Instantiate(internalProp);
                        comp.UpdateRefreshRates(lightCheckRate, lightCheckRate);
                    }

                    if (!string.IsNullOrEmpty(masterVariableName))
                    {
                        masterVariable = new VariableOrNumber(masterVariableName, this);
                        string[] range = masterVariableRange.Split(',');
                        if(range.Length == 2)
                        {
                            masterRange[0] = new VariableOrNumber(range[0], this);
                            masterRange[1] = new VariableOrNumber(range[1], this);
                        }
                        else
                        {
                            masterVariable = null;
                        }
                    }
                }

                // set up the toggle switch
                if (!string.IsNullOrEmpty(switchTransform))
                {
                    SmarterButton.CreateButton(internalProp, switchTransform, Click);
                }

                if (isCustomAction)
                {
                    if (isPluginAction && stateHandler != null)
                    {
                        currentState = stateHandler();
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(persistentVarName))
                        {
                            if (switchGroupIdentifier >= 0)
                            {
                                int activeSwitch = comp.Persistence.GetVar(persistentVarName, 0);

                                currentState = customGroupList[actionName] = (switchGroupIdentifier == activeSwitch);
                            }
                            else
                            {
                                currentState = customGroupList[actionName] = comp.Persistence.GetBool(persistentVarName, initialState);
                            }

                            if (actionName == "intlight")
                            {
                                // We have to restore lighting after reading the
                                // persistent variable.
                                SetInternalLights(customGroupList[actionName]);
                            }
                        }
                    }
                }

                if (!string.IsNullOrEmpty(persistentVarName) && !comp.Persistence.HasVar(persistentVarName))
                {
                    if (switchGroupIdentifier >= 0)
                    {
                        if (currentState)
                        {
                            comp.Persistence.SetVar(persistentVarName, switchGroupIdentifier);
                        }
                    }
                    else
                    {
                        comp.Persistence.SetVar(persistentVarName, currentState);
                    }
                }

                if (!string.IsNullOrEmpty(animationName))
                {
                    // Set up the animation
                    Animation[] animators = animateExterior ? part.FindModelAnimators(animationName) : internalProp.FindModelAnimators(animationName);
                    if (animators.Length > 0)
                    {
                        anim = animators[0];
                    }
                    else
                    {
                        JUtil.LogErrorMessage(this, "Could not find animation \"{0}\" on {2} \"{1}\"",
                            animationName, animateExterior ? part.name : internalProp.name, animateExterior ? "part" : "prop");
                        return;
                    }
                    anim[animationName].wrapMode = WrapMode.Once;

                    if (currentState ^ reverse)
                    {
                        anim[animationName].speed = float.MaxValue;
                        anim[animationName].normalizedTime = 0;

                    }
                    else
                    {
                        anim[animationName].speed = float.MinValue;
                        anim[animationName].normalizedTime = 1;
                    }
                    anim.Play(animationName);
                }
                else if (!string.IsNullOrEmpty(coloredObject))
                {
                    // Set up the color shift.
                    colorShiftRenderer = internalProp.FindModelComponent<Renderer>(coloredObject);
                    disabledColorValue = ConfigNode.ParseColor32(disabledColor);
                    enabledColorValue = ConfigNode.ParseColor32(enabledColor);
                    colorShiftRenderer.material.SetColor(colorName, (currentState ^ reverse ? enabledColorValue : disabledColorValue));
                }
                else
                {
                    JUtil.LogMessage(this, "Warning, neither color nor animation are defined.");
                }

                audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false);

                startupComplete = true;
            }
            catch
            {
                JUtil.AnnoyUser(this);
                enabled = false;
                throw;
            }
        }
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            try
            {
                if (string.IsNullOrEmpty(perPodPersistenceName))
                {
                    JUtil.LogErrorMessage(this, "perPodPersistenceName must be defined");
                    return;
                }
                if (string.IsNullOrEmpty(defaultValue))
                {
                    JUtil.LogErrorMessage(this, "defaultValue must be defined");
                    return;
                }

                if (stepSize < 0.0f)
                {
                    stepSize = 0.0f;
                }

                //JUtil.LogMessage(this, "Start(): {0}, {1}, {2}, {3}, {4}", perPodPersistenceName, defaultValue, minValue, maxValue, stepSize);

                if (!string.IsNullOrEmpty(minValue))
                {
                    minRange = VariableOrNumber.Instantiate(minValue);
                    //JUtil.LogMessage(this, "Created lower bound variable");
                }
                if (!string.IsNullOrEmpty(maxValue))
                {
                    maxRange = VariableOrNumber.Instantiate(maxValue);
                    //JUtil.LogMessage(this, "Created upper bound variable");
                }
                if ((minRange == null || maxRange == null) && loopInput == true)
                {
                    JUtil.LogErrorMessage(this, "Overriding loopInput - minValue or maxValue is missing");
                    loopInput = false;
                }

                rpmComp = RasterPropMonitorComputer.Instantiate(internalProp);
                if (!rpmComp.HasVar(perPodPersistenceName))
                {
                    //JUtil.LogMessage(this, "Initializing per pod persistence value {0}", perPodPersistenceName);

                    RPMVesselComputer comp = RPMVesselComputer.Instance(vessel);
                    VariableOrNumber von = VariableOrNumber.Instantiate(defaultValue);
                    float value;
                    if (von.Get(out value, comp))
                    {
                        if (stepSize > 0.0f)
                        {
                            float remainder = value % stepSize;
                            value -= remainder;
                        }
                        //JUtil.LogMessage(this, " ... Initialized to {0}", (int)value);
                        rpmComp.SetVar(perPodPersistenceName, (int)value);
                    }
                    else
                    {
                        JUtil.LogErrorMessage(this, "Failed to evaluate default value of {0} for {1}", defaultValue, perPodPersistenceName);
                        return;
                    }
                }

                ConfigNode moduleConfig = null;
                foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP"))
                {
                    if (node.GetValue("name") == internalProp.propName)
                    {

                        moduleConfig = node.GetNodes("MODULE")[moduleID];
                        ConfigNode[] inputNodes = moduleConfig.GetNodes("USERINPUTSET");

                        for (int i = 0; i < inputNodes.Length; i++)
                        {
                            try
                            {
                                numericInputs.Add(new NumericInput(inputNodes[i], internalProp));
                                //JUtil.LogMessage(this, "Added USERINPUTSET {0}", inputNodes[i].GetValue("switchTransform"));
                            }
                            catch (ArgumentException e)
                            {
                                JUtil.LogErrorMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID);
                            }
                        }
                        break;
                    }
                }

                enabled = true;
            }
            catch
            {
                JUtil.AnnoyUser(this);
                enabled = false;
                throw;
            }
        }
        public DataSet(ConfigNode node)
        {
            Vector4 packedPosition = ConfigNode.ParseVector4(node.GetValue("borderPosition"));

            position.x = packedPosition.x;
            position.y = packedPosition.y;
            size.x     = packedPosition.z;
            size.y     = packedPosition.w;

            if (node.HasValue("borderColor"))
            {
                color = ConfigNode.ParseColor32(node.GetValue("borderColor"));
            }

            if (node.HasValue("borderWidth"))
            {
                lineWidth = int.Parse(node.GetValue("borderWidth"));
            }

            string graphTypeStr = node.GetValue("graphType").Trim();

            if (graphTypeStr == GraphType.VerticalUp.ToString())
            {
                graphType = GraphType.VerticalUp;
            }
            else if (graphTypeStr == GraphType.VerticalDown.ToString())
            {
                graphType = GraphType.VerticalDown;
            }
            else if (graphTypeStr == GraphType.VerticalSplit.ToString())
            {
                graphType = GraphType.VerticalSplit;
            }
            else if (graphTypeStr == GraphType.HorizontalRight.ToString())
            {
                graphType = GraphType.HorizontalRight;
            }
            else if (graphTypeStr == GraphType.HorizontalLeft.ToString())
            {
                graphType = GraphType.HorizontalLeft;
            }
            else if (graphTypeStr == GraphType.HorizontalSplit.ToString())
            {
                graphType = GraphType.HorizontalSplit;
            }
            else if (graphTypeStr == GraphType.Lamp.ToString())
            {
                graphType = GraphType.Lamp;
            }
            else
            {
                throw new ArgumentException("Unknown 'graphType' in DATA_SET");
            }

            if (node.HasValue("passiveColor"))
            {
                passiveColor = ConfigNode.ParseColor32(node.GetValue("passiveColor"));
            }
            if (node.HasValue("activeColor"))
            {
                activeColor = ConfigNode.ParseColor32(node.GetValue("activeColor"));
            }
            string[] token = node.GetValue("scale").Split(',');
            scale[0]     = VariableOrNumber.Instantiate(token[0]);
            scale[1]     = VariableOrNumber.Instantiate(token[1]);
            variableName = node.GetValue("variableName").Trim();

            if (node.HasValue("reverse"))
            {
                if (!bool.TryParse(node.GetValue("reverse"), out reverse))
                {
                    throw new ArgumentException("So is 'reverse' true or false?");
                }
            }

            if (node.HasValue("threshold"))
            {
                threshold = ConfigNode.ParseVector2(node.GetValue("threshold"));
            }
            if (threshold != Vector2.zero)
            {
                thresholdMode = true;

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

                if (node.HasValue("flashingDelay"))
                {
                    flashingDelay = float.Parse(node.GetValue("flashingDelay"));
                    flashingDelay = Mathf.Max(flashingDelay, 0.0f);
                }
            }

            fillTopLeftCorner = position + new Vector2((float)lineWidth, (float)lineWidth);
            fillSize          = (size - new Vector2((float)(2 * lineWidth), (float)(2 * lineWidth)));
        }
        public VariableAnimationSet(ConfigNode node, InternalProp thisProp)
        {
            part = thisProp.part;

            if (!node.HasData)
            {
                throw new ArgumentException("No data?!");
            }

            comp = RasterPropMonitorComputer.Instantiate(thisProp);

            string[] tokens = { };

            if (node.HasValue("scale"))
            {
                tokens = node.GetValue("scale").Split(',');
            }

            if (tokens.Length != 2)
            {
                throw new ArgumentException("Could not parse 'scale' parameter.");
            }

            if (node.HasValue("variableName"))
            {
                string variableName;
                variableName = node.GetValue("variableName").Trim();
                scaleEnds[2] = new VariableOrNumber(variableName, this);
            }
            else if (node.HasValue("stateMethod"))
            {
                Func<bool> stateFunction = (Func<bool>)comp.GetMethod(node.GetValue("stateMethod").Trim(), thisProp, typeof(Func<bool>));
                if (stateFunction != null)
                {
                    scaleEnds[2] = new VariableOrNumber(stateFunction, this);
                }
                else
                {
                    throw new ArgumentException("Unrecognized stateMethod");
                }
            }
            else
            {
                throw new ArgumentException("Missing variable name.");
            }

            scaleEnds[0] = new VariableOrNumber(tokens[0], this);
            scaleEnds[1] = new VariableOrNumber(tokens[1], this);

            // That takes care of the scale, now what to do about that scale:

            if (node.HasValue("reverse"))
            {
                if (!bool.TryParse(node.GetValue("reverse"), out reverse))
                {
                    throw new ArgumentException("So is 'reverse' true or false?");
                }
            }

            if (node.HasValue("animationName"))
            {
                animationName = node.GetValue("animationName");
                if (node.HasValue("animationSpeed"))
                {
                    animationSpeed = float.Parse(node.GetValue("animationSpeed"));

                    if (reverse)
                    {
                        animationSpeed = -animationSpeed;
                    }
                }
                else
                {
                    animationSpeed = 0.0f;
                }
                Animation[] anims = node.HasValue("animateExterior") ? thisProp.part.FindModelAnimators(animationName) : thisProp.FindModelAnimators(animationName);
                if (anims.Length > 0)
                {
                    onAnim = anims[0];
                    onAnim.enabled = true;
                    onAnim[animationName].speed = 0;
                    onAnim[animationName].normalizedTime = reverse ? 1f : 0f;
                    looping = node.HasValue("loopingAnimation");
                    if (looping)
                    {
                        onAnim[animationName].wrapMode = WrapMode.Loop;
                        onAnim.wrapMode = WrapMode.Loop;
                        onAnim[animationName].speed = animationSpeed;
                        mode = Mode.LoopingAnimation;
                    }
                    else
                    {
                        onAnim[animationName].wrapMode = WrapMode.Once;
                        mode = Mode.Animation;
                    }
                    onAnim.Play();
                    alwaysActive = node.HasValue("animateExterior");
                }
                else
                {
                    throw new ArgumentException("Animation could not be found.");
                }

                if (node.HasValue("stopAnimationName"))
                {
                    stopAnimationName = node.GetValue("stopAnimationName");
                    anims = node.HasValue("animateExterior") ? thisProp.part.FindModelAnimators(stopAnimationName) : thisProp.FindModelAnimators(stopAnimationName);
                    if (anims.Length > 0)
                    {
                        offAnim = anims[0];
                        offAnim.enabled = true;
                        offAnim[stopAnimationName].speed = 0;
                        offAnim[stopAnimationName].normalizedTime = reverse ? 1f : 0f;
                        if (looping)
                        {
                            offAnim[stopAnimationName].wrapMode = WrapMode.Loop;
                            offAnim.wrapMode = WrapMode.Loop;
                            offAnim[stopAnimationName].speed = animationSpeed;
                            mode = Mode.LoopingAnimation;
                        }
                        else
                        {
                            offAnim[stopAnimationName].wrapMode = WrapMode.Once;
                            mode = Mode.Animation;
                        }
                    }
                }
            }
            else if (node.HasValue("activeColor") && node.HasValue("passiveColor") && node.HasValue("coloredObject"))
            {
                if (node.HasValue("colorName"))
                    colorName = node.GetValue("colorName");
                passiveColor = ConfigNode.ParseColor32(node.GetValue("passiveColor"));
                activeColor = ConfigNode.ParseColor32(node.GetValue("activeColor"));
                colorShiftRenderer = thisProp.FindModelComponent<Renderer>(node.GetValue("coloredObject"));
                colorShiftRenderer.material.SetColor(colorName, reverse ? activeColor : passiveColor);
                mode = Mode.Color;
            }
            else if (node.HasValue("controlledTransform") && node.HasValue("localRotationStart") && node.HasValue("localRotationEnd"))
            {
                controlledTransform = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim());
                initialRotation = controlledTransform.localRotation;
                if (node.HasValue("longPath"))
                {
                    longPath = true;
                    vectorStart = ConfigNode.ParseVector3(node.GetValue("localRotationStart"));
                    vectorEnd = ConfigNode.ParseVector3(node.GetValue("localRotationEnd"));
                }
                else
                {
                    rotationStart = Quaternion.Euler(ConfigNode.ParseVector3(node.GetValue("localRotationStart")));
                    rotationEnd = Quaternion.Euler(ConfigNode.ParseVector3(node.GetValue("localRotationEnd")));
                }
                mode = Mode.Rotation;
            }
            else if (node.HasValue("controlledTransform") && node.HasValue("localTranslationStart") && node.HasValue("localTranslationEnd"))
            {
                controlledTransform = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim());
                initialPosition = controlledTransform.localPosition;
                vectorStart = ConfigNode.ParseVector3(node.GetValue("localTranslationStart"));
                vectorEnd = ConfigNode.ParseVector3(node.GetValue("localTranslationEnd"));
                mode = Mode.Translation;
            }
            else if (node.HasValue("controlledTransform") && node.HasValue("localScaleStart") && node.HasValue("localScaleEnd"))
            {
                controlledTransform = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim());
                initialScale = controlledTransform.localScale;
                vectorStart = ConfigNode.ParseVector3(node.GetValue("localScaleStart"));
                vectorEnd = ConfigNode.ParseVector3(node.GetValue("localScaleEnd"));
                mode = Mode.Scale;
            }
            else if (node.HasValue("controlledTransform") && node.HasValue("textureLayers") && node.HasValue("textureShiftStart") && node.HasValue("textureShiftEnd"))
            {
                affectedMaterial = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim()).renderer.material;
                textureLayer = node.GetValue("textureLayers");
                textureShiftStart = ConfigNode.ParseVector2(node.GetValue("textureShiftStart"));
                textureShiftEnd = ConfigNode.ParseVector2(node.GetValue("textureShiftEnd"));
                mode = Mode.TextureShift;
            }
            else if (node.HasValue("controlledTransform") && node.HasValue("textureLayers") && node.HasValue("textureScaleStart") && node.HasValue("textureScaleEnd"))
            {
                affectedMaterial = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim()).renderer.material;
                textureLayer = node.GetValue("textureLayers");
                textureScaleStart = ConfigNode.ParseVector2(node.GetValue("textureScaleStart"));
                textureScaleEnd = ConfigNode.ParseVector2(node.GetValue("textureScaleEnd"));
                mode = Mode.TextureScale;
            }
            else
            {
                throw new ArgumentException("Cannot initiate any of the possible action modes.");
            }

            if (node.HasValue("threshold"))
            {
                threshold = ConfigNode.ParseVector2(node.GetValue("threshold"));
            }

            resourceAmount = 0.0f;
            if (threshold != Vector2.zero)
            {
                thresholdMode = true;

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

                if (node.HasValue("flashingDelay"))
                {
                    flashingDelay = double.Parse(node.GetValue("flashingDelay"));
                }

                if (node.HasValue("alarmSound"))
                {
                    alarmSoundVolume = 0.5f;
                    if (node.HasValue("alarmSoundVolume"))
                        alarmSoundVolume = float.Parse(node.GetValue("alarmSoundVolume"));
                    audioOutput = JUtil.SetupIVASound(thisProp, node.GetValue("alarmSound"), alarmSoundVolume, false);
                    if (node.HasValue("alarmMustPlayOnce"))
                    {
                        if (!bool.TryParse(node.GetValue("alarmMustPlayOnce"), out alarmMustPlayOnce))
                            throw new ArgumentException("So is 'alarmMustPlayOnce' true or false?");
                    }
                    if (node.HasValue("alarmShutdownButton"))
                        SmarterButton.CreateButton(thisProp, node.GetValue("alarmShutdownButton"), AlarmShutdown);
                    if (node.HasValue("alarmSoundLooping"))
                    {
                        if (!bool.TryParse(node.GetValue("alarmSoundLooping"), out alarmSoundLooping))
                            throw new ArgumentException("So is 'alarmSoundLooping' true or false?");
                        audioOutput.audio.loop = alarmSoundLooping;
                    }
                }

                if (node.HasValue("resourceAmount"))
                {
                    resourceAmount = float.Parse(node.GetValue("resourceAmount"));
                }

                TurnOff();
            }
        }
            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);
            }
        public DataSet(ConfigNode node)
        {
            Vector4 packedPosition = ConfigNode.ParseVector4(node.GetValue("borderPosition"));
            position.x = packedPosition.x;
            position.y = packedPosition.y;
            size.x = packedPosition.z;
            size.y = packedPosition.w;

            if (node.HasValue("borderColor"))
            {
                color = ConfigNode.ParseColor32(node.GetValue("borderColor"));
            }

            if (node.HasValue("borderWidth"))
            {
                lineWidth = int.Parse(node.GetValue("borderWidth"));
            }

            string graphTypeStr = node.GetValue("graphType").Trim();
            if (graphTypeStr == GraphType.VerticalUp.ToString())
            {
                graphType = GraphType.VerticalUp;
            }
            else if (graphTypeStr == GraphType.VerticalDown.ToString())
            {
                graphType = GraphType.VerticalDown;
            }
            else if (graphTypeStr == GraphType.VerticalSplit.ToString())
            {
                graphType = GraphType.VerticalSplit;
            }
            else if (graphTypeStr == GraphType.HorizontalRight.ToString())
            {
                graphType = GraphType.HorizontalRight;
            }
            else if (graphTypeStr == GraphType.HorizontalLeft.ToString())
            {
                graphType = GraphType.HorizontalLeft;
            }
            else if (graphTypeStr == GraphType.HorizontalSplit.ToString())
            {
                graphType = GraphType.HorizontalSplit;
            }
            else if (graphTypeStr == GraphType.Lamp.ToString())
            {
                graphType = GraphType.Lamp;
            }
            else
            {
                throw new ArgumentException("Unknown 'graphType' in DATA_SET");
            }

            if (node.HasValue("passiveColor"))
            {
                passiveColor = ConfigNode.ParseColor32(node.GetValue("passiveColor"));
            }
            if (node.HasValue("activeColor"))
            {
                activeColor = ConfigNode.ParseColor32(node.GetValue("activeColor"));
            }
            string[] token = node.GetValue("scale").Split(',');
            scale[0] = new VariableOrNumber(token[0].Trim(), this);
            scale[1] = new VariableOrNumber(token[1].Trim(), this);
            variableName = node.GetValue("variableName").Trim();

            if (node.HasValue("reverse"))
            {
                if (!bool.TryParse(node.GetValue("reverse"), out reverse))
                {
                    throw new ArgumentException("So is 'reverse' true or false?");
                }
            }

            if (node.HasValue("threshold"))
            {
                threshold = ConfigNode.ParseVector2(node.GetValue("threshold"));
            }
            if (threshold != Vector2.zero)
            {
                thresholdMode = true;

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

                if (node.HasValue("flashingDelay"))
                {
                    flashingDelay = float.Parse(node.GetValue("flashingDelay"));
                    flashingDelay = Mathf.Max(flashingDelay, 0.0f);
                }
            }

            fillTopLeftCorner = position + new Vector2((float)lineWidth, (float)lineWidth);
            fillSize = (size - new Vector2((float)(2 * lineWidth), (float)(2 * lineWidth)));
        }
Beispiel #19
0
        internal MathVariable(ConfigNode node, RasterPropMonitorComputer rpmComp)
        {
            name = node.GetValue("name");

            int maxParameters = int.MaxValue;

            string oper = node.GetValue("operator");

            if (oper == Operator.NONE.ToString())
            {
                op            = Operator.NONE;
                indexOperator = false;
            }
            else if (oper == Operator.ADD.ToString())
            {
                op            = Operator.ADD;
                indexOperator = false;
            }
            else if (oper == Operator.SUBTRACT.ToString())
            {
                op            = Operator.SUBTRACT;
                indexOperator = false;
            }
            else if (oper == Operator.MULTIPLY.ToString())
            {
                op            = Operator.MULTIPLY;
                indexOperator = false;
            }
            else if (oper == Operator.DIVIDE.ToString())
            {
                op            = Operator.DIVIDE;
                indexOperator = false;
            }
            else if (oper == Operator.MAX.ToString())
            {
                op            = Operator.MAX;
                indexOperator = false;
            }
            else if (oper == Operator.MIN.ToString())
            {
                op            = Operator.MIN;
                indexOperator = false;
            }
            else if (oper == Operator.POWER.ToString())
            {
                op            = Operator.POWER;
                indexOperator = false;
            }
            else if (oper == Operator.ANGLEDELTA.ToString())
            {
                op            = Operator.ANGLEDELTA;
                indexOperator = false;
                maxParameters = 2;
            }
            else if (oper == Operator.ATAN2.ToString())
            {
                op            = Operator.ATAN2;
                indexOperator = false;
                maxParameters = 2;
            }
            else if (oper == Operator.MAXINDEX.ToString())
            {
                op            = Operator.MAXINDEX;
                indexOperator = true;
            }
            else if (oper == Operator.MININDEX.ToString())
            {
                op            = Operator.MININDEX;
                indexOperator = true;
            }
            else
            {
                throw new ArgumentException("Found an invalid operator type in RPM_CUSTOM_VARIABLE", oper);
            }

            string[] sources    = node.GetValues("sourceVariable");
            int      numIndices = Math.Min(sources.Length, maxParameters);

            for (int i = 0; i < numIndices; ++i)
            {
                VariableOrNumber sv = rpmComp.InstantiateVariableOrNumber(sources[i]);
                sourceVariables.Add(sv);
            }

            if (sourceVariables.Count == 0)
            {
                throw new ArgumentException("Did not find any SOURCE_VARIABLE nodes in RPM_CUSTOM_VARIABLE", name);
            }
        }
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            try
            {
                if (string.IsNullOrEmpty(perPodPersistenceName))
                {
                    JUtil.LogErrorMessage(this, "perPodPersistenceName must be defined");
                    return;
                }
                if (string.IsNullOrEmpty(defaultValue))
                {
                    JUtil.LogErrorMessage(this, "defaultValue must be defined");
                    return;
                }

                if (stepSize < 0.0f)
                {
                    stepSize = 0.0f;
                }

                //JUtil.LogMessage(this, "Start(): {0}, {1}, {2}, {3}, {4}", perPodPersistenceName, defaultValue, minValue, maxValue, stepSize);

                if (!string.IsNullOrEmpty(minValue))
                {
                    minRange = VariableOrNumber.Instantiate(minValue);
                    //JUtil.LogMessage(this, "Created lower bound variable");
                }
                if (!string.IsNullOrEmpty(maxValue))
                {
                    maxRange = VariableOrNumber.Instantiate(maxValue);
                    //JUtil.LogMessage(this, "Created upper bound variable");
                }
                if ((minRange == null || maxRange == null) && loopInput == true)
                {
                    JUtil.LogErrorMessage(this, "Overriding loopInput - minValue or maxValue is missing");
                    loopInput = false;
                }

                RPMVesselComputer comp = RPMVesselComputer.Instance(vessel);
                if (!comp.HasPersistentVariable(perPodPersistenceName))
                {
                    //JUtil.LogMessage(this, "Initializing per pod persistence value {0}", perPodPersistenceName);

                    VariableOrNumber von = VariableOrNumber.Instantiate(defaultValue);
                    float            value;
                    if (von.Get(out value, comp))
                    {
                        if (stepSize > 0.0f)
                        {
                            float remainder = value % stepSize;
                            value -= remainder;
                        }
                        comp.SetPersistentVariable(perPodPersistenceName, value);
                    }
                    else
                    {
                        JUtil.LogErrorMessage(this, "Failed to evaluate default value of {0} for {1}", defaultValue, perPodPersistenceName);
                        return;
                    }
                }

                ConfigNode moduleConfig = null;
                foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP"))
                {
                    if (node.GetValue("name") == internalProp.propName)
                    {
                        moduleConfig = node.GetNodes("MODULE")[moduleID];
                        ConfigNode[] inputNodes = moduleConfig.GetNodes("USERINPUTSET");

                        for (int i = 0; i < inputNodes.Length; i++)
                        {
                            try
                            {
                                numericInputs.Add(new NumericInput(inputNodes[i], internalProp));
                                //JUtil.LogMessage(this, "Added USERINPUTSET {0}", inputNodes[i].GetValue("switchTransform"));
                            }
                            catch (ArgumentException e)
                            {
                                JUtil.LogErrorMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID);
                            }
                        }
                        break;
                    }
                }

                enabled = true;
            }
            catch
            {
                JUtil.AnnoyUser(this);
                enabled = false;
                throw;
            }
        }
Beispiel #21
0
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            try
            {
                rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true);

                if (!groupList.ContainsKey(actionName) && !customGroupList.ContainsKey(actionName))
                {
                    JUtil.LogErrorMessage(this, "Action \"{0}\" is not supported.", actionName);
                    return;
                }

                // Parse the needs-electric-charge here.
                if (!string.IsNullOrEmpty(needsElectricCharge))
                {
                    switch (needsElectricCharge.ToLowerInvariant().Trim())
                    {
                    case "true":
                    case "yes":
                    case "1":
                        needsElectricChargeValue = true;
                        break;

                    case "false":
                    case "no":
                    case "0":
                        needsElectricChargeValue = false;
                        break;
                    }
                }

                // Now parse consumeOnToggle and consumeWhileActive...
                if (!string.IsNullOrEmpty(consumeOnToggle))
                {
                    string[] tokens = consumeOnToggle.Split(',');
                    if (tokens.Length == 3)
                    {
                        consumeOnToggleName = tokens[0].Trim();
                        if (!(PartResourceLibrary.Instance.GetDefinition(consumeOnToggleName) != null &&
                              float.TryParse(tokens[1].Trim(), NumberStyles.Any, CultureInfo.InvariantCulture,
                                             out consumeOnToggleAmount)))
                        {
                            JUtil.LogErrorMessage(this, "Could not parse \"{0}\"", consumeOnToggle);
                        }
                        switch (tokens[2].Trim().ToLower())
                        {
                        case "on":
                            consumingOnToggleUp = true;
                            break;

                        case "off":
                            consumingOnToggleDown = true;
                            break;

                        case "both":
                            consumingOnToggleUp   = true;
                            consumingOnToggleDown = true;
                            break;

                        default:
                            JUtil.LogErrorMessage(this, "So should I consume resources when turning on, turning off, or both in \"{0}\"?", consumeOnToggle);
                            break;
                        }
                    }
                }

                if (!string.IsNullOrEmpty(consumeWhileActive))
                {
                    string[] tokens = consumeWhileActive.Split(',');
                    if (tokens.Length == 2)
                    {
                        consumeWhileActiveName = tokens[0].Trim();
                        if (!(PartResourceLibrary.Instance.GetDefinition(consumeWhileActiveName) != null &&
                              float.TryParse(tokens[1].Trim(),
                                             NumberStyles.Any, CultureInfo.InvariantCulture,
                                             out consumeWhileActiveAmount)))
                        {
                            JUtil.LogErrorMessage(this, "Could not parse \"{0}\"", consumeWhileActive);
                        }
                        else
                        {
                            consumingWhileActive = true;
                            JUtil.LogMessage(this, "Switch in prop {0} prop id {1} will consume {2} while active at a rate of {3}", internalProp.propName,
                                             internalProp.propID, consumeWhileActiveName, consumeWhileActiveAmount);
                        }
                    }
                }

                if (groupList.ContainsKey(actionName))
                {
                    kspAction    = groupList[actionName];
                    currentState = vessel.ActionGroups[kspAction];
                    // action group switches may not belong to a radio group
                    switchGroupIdentifier = -1;
                }
                else
                {
                    isCustomAction = true;
                    switch (actionName)
                    {
                    case "intlight":
                        persistentVarName = internalLightName;
                        if (!string.IsNullOrEmpty(internalLightName))
                        {
                            Light[] availableLights = internalModel.FindModelComponents <Light>();
                            if (availableLights != null && availableLights.Length > 0)
                            {
                                List <Light> lights = new List <Light>(availableLights);
                                for (int i = lights.Count - 1; i >= 0; --i)
                                {
                                    if (lights[i].name != internalLightName)
                                    {
                                        lights.RemoveAt(i);
                                    }
                                }
                                if (lights.Count > 0)
                                {
                                    lightObjects              = lights.ToArray();
                                    needsElectricChargeValue |= string.IsNullOrEmpty(needsElectricCharge) || needsElectricChargeValue;
                                }
                                else
                                {
                                    actionName = "dummy";
                                }
                            }
                        }
                        else
                        {
                            actionName = "dummy";
                        }
                        break;

                    case "plugin":
                        persistentVarName = string.Empty;
                        rpmComp.UpdateDataRefreshRate(refreshRate);

                        foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP"))
                        {
                            if (node.GetValue("name") == internalProp.propName)
                            {
                                foreach (ConfigNode pluginConfig in node.GetNodes("MODULE")[moduleID].GetNodes("PLUGINACTION"))
                                {
                                    if (pluginConfig.HasValue("name") && pluginConfig.HasValue("actionMethod"))
                                    {
                                        string action = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("actionMethod").Trim();
                                        actionHandler = (Action <bool>)rpmComp.GetMethod(action, internalProp, typeof(Action <bool>));

                                        if (actionHandler == null)
                                        {
                                            JUtil.LogErrorMessage(this, "Failed to instantiate action handler {0}", action);
                                        }
                                        else
                                        {
                                            if (pluginConfig.HasValue("stateMethod"))
                                            {
                                                string state = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("stateMethod").Trim();
                                                stateVariable = rpmComp.InstantiateVariableOrNumber("PLUGIN_" + state);
                                            }
                                            else if (pluginConfig.HasValue("stateVariable"))
                                            {
                                                stateVariable = rpmComp.InstantiateVariableOrNumber(pluginConfig.GetValue("stateVariable").Trim());
                                            }
                                            isPluginAction = true;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        if (actionHandler == null)
                        {
                            actionName = "dummy";
                            JUtil.LogMessage(this, "Plugin handlers did not start, reverting to dummy mode.");
                        }
                        break;

                    case "transfer":
                        persistentVarName = string.Empty;
                        rpmComp.UpdateDataRefreshRate(refreshRate);

                        foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP"))
                        {
                            if (node.GetValue("name") == internalProp.propName)
                            {
                                foreach (ConfigNode pluginConfig in node.GetNodes("MODULE")[moduleID].GetNodes("TRANSFERACTION"))
                                {
                                    if (pluginConfig.HasValue("name") || pluginConfig.HasValue("getVariable"))
                                    {
                                        if (pluginConfig.HasValue("stateMethod"))
                                        {
                                            string state = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("stateMethod").Trim();
                                            stateVariable = rpmComp.InstantiateVariableOrNumber("PLUGIN_" + state);
                                        }
                                        else if (pluginConfig.HasValue("stateVariable"))
                                        {
                                            stateVariable = rpmComp.InstantiateVariableOrNumber(pluginConfig.GetValue("stateVariable").Trim());
                                        }
                                        if (pluginConfig.HasValue("setMethod"))
                                        {
                                            string action = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("setMethod").Trim();
                                            transferSetter = (Action <double>)rpmComp.GetMethod(action, internalProp, typeof(Action <double>));

                                            if (transferSetter == null)
                                            {
                                                JUtil.LogErrorMessage(this, "Failed to instantiate transfer handler {0}", pluginConfig.GetValue("name"));
                                            }
                                            else if (pluginConfig.HasValue("perPodPersistenceName"))
                                            {
                                                transferPersistentName = pluginConfig.GetValue("perPodPersistenceName").Trim();
                                                actionName             = "transferFromPersistent";
                                                customAction           = CustomActions.TransferFromPersistent;
                                            }
                                            else if (pluginConfig.HasValue("getVariable"))
                                            {
                                                transferGetter = rpmComp.InstantiateVariableOrNumber(pluginConfig.GetValue("getVariable").Trim());
                                                actionName     = "transferFromVariable";
                                                customAction   = CustomActions.TransferFromVariable;
                                            }
                                            else
                                            {
                                                JUtil.LogErrorMessage(this, "Unable to configure transfer setter method in {0} - no perPodPersistenceName or getVariable", internalProp.name);
                                                transferSetter = null;
                                                //JUtil.LogMessage(this, "Got setter {0}", action);
                                            }
                                        }
                                        else if (pluginConfig.HasValue("getMethod"))
                                        {
                                            if (pluginConfig.HasValue("perPodPersistenceName"))
                                            {
                                                string action = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("getMethod").Trim();
                                                var    getter = (Func <double>)rpmComp.GetMethod(action, internalProp, typeof(Func <double>));

                                                if (getter == null)
                                                {
                                                    JUtil.LogErrorMessage(this, "Failed to instantiate transfer handler {0} in {1}", pluginConfig.GetValue("name"), internalProp.name);
                                                }
                                                else
                                                {
                                                    transferGetter         = rpmComp.InstantiateVariableOrNumber("PLUGIN_" + action);
                                                    transferPersistentName = pluginConfig.GetValue("perPodPersistenceName").Trim();
                                                    actionName             = "transferToPersistent";
                                                    customAction           = CustomActions.TransferToPersistent;
                                                    //JUtil.LogMessage(this, "Got getter {0}", action);
                                                    break;
                                                }
                                            }
                                            else
                                            {
                                                JUtil.LogErrorMessage(this, "Transfer handler in {0} configured with 'getVariable', but no 'perPodPeristenceName'", internalProp.name);
                                            }
                                        }
                                        else if (pluginConfig.HasValue("getVariable"))
                                        {
                                            if (pluginConfig.HasValue("perPodPersistenceName"))
                                            {
                                                transferGetter         = rpmComp.InstantiateVariableOrNumber(pluginConfig.GetValue("getVariable").Trim());
                                                transferPersistentName = pluginConfig.GetValue("perPodPersistenceName").Trim();
                                                actionName             = "transferToPersistent";
                                                customAction           = CustomActions.TransferToPersistent;
                                            }
                                            else
                                            {
                                                JUtil.LogErrorMessage(this, "Transfer handler in {0} configured with 'getVariable', but no 'perPodPeristenceName'", internalProp.name);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (transferGetter == null && transferSetter == null)
                        {
                            actionName    = "dummy";
                            stateVariable = null;
                            JUtil.LogMessage(this, "Transfer handlers did not start, reverting to dummy mode.");
                        }
                        break;

                    default:
                        persistentVarName = "switch" + internalProp.propID + "_" + moduleID;
                        break;
                    }
                    if (!string.IsNullOrEmpty(perPodPersistenceName))
                    {
                        persistentVarName = perPodPersistenceName;
                    }
                    else
                    {
                        // If there's no persistence name, there's no valid group id for this switch
                        switchGroupIdentifier = -1;
                    }

                    persistentVarValid = !string.IsNullOrEmpty(persistentVarName);
                }

                perPodPersistenceValid = !string.IsNullOrEmpty(perPodPersistenceName);

                if (customGroupList.ContainsKey(actionName))
                {
                    customAction = customGroupList[actionName];
                }

                if (needsElectricChargeValue || persistentVarValid || !string.IsNullOrEmpty(perPodMasterSwitchName) || !string.IsNullOrEmpty(masterVariableName) ||
                    transferGetter != null || transferSetter != null)
                {
                    rpmComp.UpdateDataRefreshRate(refreshRate);

                    if (!string.IsNullOrEmpty(masterVariableName))
                    {
                        string[] range = masterVariableRange.Split(',');
                        if (range.Length == 2)
                        {
                            masterVariable = new VariableOrNumberRange(rpmComp, masterVariableName, range[0], range[1]);
                        }
                        else
                        {
                            masterVariable = null;
                        }
                    }
                }

                if (needsElectricChargeValue)
                {
                    del = (Action <bool>)Delegate.CreateDelegate(typeof(Action <bool>), this, "ResourceDepletedCallback");
                    rpmComp.RegisterResourceCallback(resourceName, del);
                }

                // set up the toggle switch
                if (!string.IsNullOrEmpty(switchTransform))
                {
                    if (momentarySwitch)
                    {
                        SmarterButton.CreateButton(internalProp, switchTransform, Click, Click);
                    }
                    else
                    {
                        SmarterButton.CreateButton(internalProp, switchTransform, Click);
                    }
                }

                if (isCustomAction)
                {
                    if (isPluginAction && stateVariable != null)
                    {
                        currentState = stateVariable.AsInt() > 0;
                    }
                    else
                    {
                        if (persistentVarValid)
                        {
                            if (switchGroupIdentifier >= 0)
                            {
                                int activeSwitch = rpmComp.GetPersistentVariable(persistentVarName, 0, perPodPersistenceIsGlobal).MassageToInt();

                                currentState = customGroupState = (switchGroupIdentifier == activeSwitch);
                            }
                            else
                            {
                                currentState = customGroupState = rpmComp.GetPersistentVariable(persistentVarName, initialState, perPodPersistenceIsGlobal);
                            }

                            if (customAction == CustomActions.IntLight)
                            {
                                // We have to restore lighting after reading the
                                // persistent variable.
                                SetInternalLights(customGroupState);
                            }
                        }
                    }
                }

                if (persistentVarValid && !rpmComp.HasPersistentVariable(persistentVarName, perPodPersistenceIsGlobal))
                {
                    if (switchGroupIdentifier >= 0)
                    {
                        if (currentState)
                        {
                            rpmComp.SetPersistentVariable(persistentVarName, switchGroupIdentifier, perPodPersistenceIsGlobal);
                        }
                    }
                    else
                    {
                        rpmComp.SetPersistentVariable(persistentVarName, currentState, perPodPersistenceIsGlobal);
                    }
                }

                if (!string.IsNullOrEmpty(animationName))
                {
                    // Set up the animation
                    Animation[] animators = animateExterior ? part.FindModelAnimators(animationName) : internalProp.FindModelAnimators(animationName);
                    if (animators.Length > 0)
                    {
                        anim = animators[0];
                    }
                    else
                    {
                        JUtil.LogErrorMessage(this, "Could not find animation \"{0}\" on {2} \"{1}\"",
                                              animationName, animateExterior ? part.name : internalProp.name, animateExterior ? "part" : "prop");
                        return;
                    }
                    anim[animationName].wrapMode = WrapMode.Once;

                    if (currentState ^ reverse)
                    {
                        anim[animationName].speed          = float.MaxValue;
                        anim[animationName].normalizedTime = 0;
                    }
                    else
                    {
                        anim[animationName].speed          = float.MinValue;
                        anim[animationName].normalizedTime = 1;
                    }
                    anim.Play(animationName);
                }
                else if (!string.IsNullOrEmpty(coloredObject))
                {
                    // Set up the color shift.
                    Renderer colorShiftRenderer = internalProp.FindModelComponent <Renderer>(coloredObject);
                    disabledColorValue = JUtil.ParseColor32(disabledColor, part, ref rpmComp);
                    enabledColorValue  = JUtil.ParseColor32(enabledColor, part, ref rpmComp);
                    colorShiftMaterial = colorShiftRenderer.material;
                    colorNameId        = Shader.PropertyToID(colorName);
                    colorShiftMaterial.SetColor(colorNameId, (currentState ^ reverse ? enabledColorValue : disabledColorValue));
                }
                else
                {
                    JUtil.LogMessage(this, "Warning, neither color nor animation are defined in prop {0} #{1} (this may be okay).", internalProp.propName, internalProp.propID);
                }

                audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false);

                if (!string.IsNullOrEmpty(loopingSound) && loopingSoundVolume > 0.0f)
                {
                    loopingOutput = JUtil.SetupIVASound(internalProp, loopingSound, loopingSoundVolume, true);
                }

                perPodMasterSwitchValid = !string.IsNullOrEmpty(perPodMasterSwitchName);

                JUtil.LogMessage(this, "Configuration complete in prop {0} ({1}).", internalProp.propID, internalProp.propName);

                startupComplete = true;
            }
            catch (Exception e)
            {
                JUtil.LogErrorMessage(this, "Exception configuring prop {0} ({1}): {2}", internalProp.propID, internalProp.propName, e);
                JUtil.AnnoyUser(this);
                enabled = false;
            }
        }
 public VariableOrNumberRange(RasterPropMonitorComputer rpmComp, string sourceVariable, string range1, string range2, string moduloVariable = null)
 {
     sourceValue = rpmComp.InstantiateVariableOrNumber(sourceVariable);
     lowerBound = rpmComp.InstantiateVariableOrNumber(range1);
     upperBound = rpmComp.InstantiateVariableOrNumber(range2);
     if (!string.IsNullOrEmpty(moduloVariable))
     {
         modulo = rpmComp.InstantiateVariableOrNumber(moduloVariable);
     }
 }
 public VariableOrNumberRange(string sourceVariable, string range1, string range2)
 {
     sourceValue = VariableOrNumber.Instantiate(sourceVariable);
     lowerBound = VariableOrNumber.Instantiate(range1);
     upperBound = VariableOrNumber.Instantiate(range2);
 }
        /// <summary>
        /// Create a new VariableOrNumber, or return an existing one that
        /// tracks the same value.
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static VariableOrNumber Instantiate(string input)
        {
            string varName = input.Trim();
            float floatval;
            if(float.TryParse(varName, out floatval))
            {
                // If it's a numeric value, let's canonicalize it using
                // ToString, so we don't have duplicates that evaluate to the
                // same value (eg, 1.0, 1, 1.00, etc).
                varName = floatval.ToString();
            }

            if (varName == "MetersToFeet")
            {
                varName = RPMVesselComputer.MetersToFeet.ToString();
            }
            else if (varName == "MetersPerSecondToKnots")
            {
                varName = RPMVesselComputer.MetersPerSecondToKnots.ToString();
            }
            else if (varName == "MetersPerSecondToFeetPerMinute")
            {
                varName = RPMVesselComputer.MetersPerSecondToFeetPerMinute.ToString();
            }

            if(!vars.ContainsKey(varName))
            {
                VariableOrNumber VoN = new VariableOrNumber(varName);
                vars.Add(varName, VoN);
                //JUtil.LogMessage(null, "Adding VoN {0}", varName);
            }
            return vars[varName];
        }
 public VariableOrNumberRange(string sourceVariable, string range1, string range2)
 {
     sourceValue = VariableOrNumber.Instantiate(sourceVariable);
     lowerBound  = VariableOrNumber.Instantiate(range1);
     upperBound  = VariableOrNumber.Instantiate(range2);
 }
        internal VerticalBar(ConfigNode node, float screenWidth, float screenHeight, int drawingLayer, Shader displayShader, GameObject cameraBody)
        {
            JUtil.LogMessage(this, "Configuring for {0}", node.GetValue("name"));
            if (!node.HasValue("variableName"))
            {
                throw new Exception("VerticalBar " + node.GetValue("name") + " missing variableName");
            }
            variable = new VariableOrNumber(node.GetValue("variableName"), this);

            if (!node.HasValue("texture"))
            {
                throw new Exception("VerticalBar " + node.GetValue("name") + " missing texture");
            }

            Texture2D tex = GameDatabase.Instance.GetTexture(node.GetValue("texture"), false);
            if (tex == null)
            {
                throw new Exception("VerticalBar " + node.GetValue("name") + " texture " + node.GetValue("texture") + " can't be loaded.");
            }
            tex.wrapMode = TextureWrapMode.Clamp;

            if (node.HasValue("useLog10") && bool.TryParse(node.GetValue("useLog10"), out useLog10) == false)
            {
                // I think this is redundant
                useLog10 = false;
            }

            if (!node.HasValue("scale"))
            {
                throw new Exception("VerticalBar " + node.GetValue("name") + " missing scale");
            }

            scale = ConfigNode.ParseVector2(node.GetValue("scale"));
            if (useLog10)
            {
                scale.x = JUtil.PseudoLog10(scale.x);
                scale.y = JUtil.PseudoLog10(scale.y);
            }

            if (!node.HasValue("textureSize"))
            {
                throw new Exception("VerticalBar " + node.GetValue("name") + " missing textureSize");
            }

            if (!float.TryParse(node.GetValue("textureSize"), out textureSize))
            {
                throw new Exception("VerticalBar " + node.GetValue("name") + " failed parsing textureSize");
            }

            textureSize = 0.5f * textureSize / (float)tex.height;

            if (!node.HasValue("textureLimit"))
            {
                throw new Exception("VerticalBar " + node.GetValue("name") + " missing textureLimit");
            }

            textureLimit = ConfigNode.ParseVector2(node.GetValue("textureLimit"));
            textureLimit.x = 1.0f - textureLimit.x / (float)tex.height;
            textureLimit.y = 1.0f - textureLimit.y / (float)tex.height;

            if (!node.HasValue("position"))
            {
                throw new Exception("VerticalBar " + node.GetValue("name") + " missing position");
            }

            Vector4 position = ConfigNode.ParseVector4(node.GetValue("position"));

            if (node.HasValue("enablingVariable") && node.HasValue("enablingVariableRange"))
            {
                string[] range = node.GetValue("enablingVariableRange").Split(',');
                if (range.Length != 2)
                {
                    throw new Exception("VerticalBar " + node.GetValue("name") + " has an invalid enablingVariableRange");
                }

                enablingVariable = new VariableOrNumberRange(node.GetValue("enablingVariable").Trim(), range[0].Trim(), range[1].Trim());
            }

            barObject = JUtil.CreateSimplePlane("VerticalBar" + node.GetValue("name"), new Vector2(0.5f * position.z, 0.5f * position.w), new Rect(0.0f, 0.0f, 1.0f, 1.0f), drawingLayer);

            Material barMaterial = new Material(displayShader);
            barMaterial.color = Color.white;
            barMaterial.mainTexture = tex;

            // Position in camera space has (0, 0) in the center, so we need to
            // translate everything appropriately.  Y is odd since the coordinates
            // supplied are Left-Handed (0Y on top, growing down), not RH.
            barObject.transform.position = new Vector3(position.x + 0.5f * (position.z - screenWidth), 0.5f * (screenHeight - position.w) - position.y, 1.4f);
            barObject.renderer.material = barMaterial;
            barObject.transform.parent = cameraBody.transform;

            JUtil.ShowHide(true, barObject);
        }
Beispiel #27
0
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            try
            {
                RPMVesselComputer comp = RPMVesselComputer.Instance(vessel);

                if (!groupList.ContainsKey(actionName) && !customGroupList.ContainsKey(actionName))
                {
                    JUtil.LogErrorMessage(this, "Action \"{0}\" is not supported.", actionName);
                    return;
                }

                // Parse the needs-electric-charge here.
                if (!string.IsNullOrEmpty(needsElectricCharge))
                {
                    switch (needsElectricCharge.ToLowerInvariant().Trim())
                    {
                    case "true":
                    case "yes":
                    case "1":
                        needsElectricChargeValue = true;
                        break;

                    case "false":
                    case "no":
                    case "0":
                        needsElectricChargeValue = false;
                        break;
                    }
                }

                // Now parse consumeOnToggle and consumeWhileActive...
                if (!string.IsNullOrEmpty(consumeOnToggle))
                {
                    string[] tokens = consumeOnToggle.Split(',');
                    if (tokens.Length == 3)
                    {
                        consumeOnToggleName = tokens[0].Trim();
                        if (!(PartResourceLibrary.Instance.GetDefinition(consumeOnToggleName) != null &&
                              float.TryParse(tokens[1].Trim(), NumberStyles.Any, CultureInfo.InvariantCulture,
                                             out consumeOnToggleAmount)))
                        {
                            JUtil.LogErrorMessage(this, "Could not parse \"{0}\"", consumeOnToggle);
                        }
                        switch (tokens[2].Trim().ToLower())
                        {
                        case "on":
                            consumingOnToggleUp = true;
                            break;

                        case "off":
                            consumingOnToggleDown = true;
                            break;

                        case "both":
                            consumingOnToggleUp   = true;
                            consumingOnToggleDown = true;
                            break;

                        default:
                            JUtil.LogErrorMessage(this, "So should I consume resources when turning on, turning off, or both in \"{0}\"?", consumeOnToggle);
                            break;
                        }
                    }
                }

                if (!string.IsNullOrEmpty(consumeWhileActive))
                {
                    string[] tokens = consumeWhileActive.Split(',');
                    if (tokens.Length == 2)
                    {
                        consumeWhileActiveName = tokens[0].Trim();
                        if (!(PartResourceLibrary.Instance.GetDefinition(consumeWhileActiveName) != null &&
                              float.TryParse(tokens[1].Trim(),
                                             NumberStyles.Any, CultureInfo.InvariantCulture,
                                             out consumeWhileActiveAmount)))
                        {
                            JUtil.LogErrorMessage(this, "Could not parse \"{0}\"", consumeWhileActive);
                        }
                        else
                        {
                            consumingWhileActive = true;
                            if (JUtil.debugLoggingEnabled)
                            {
                                JUtil.LogMessage(this, "Switch in prop {0} prop id {1} will consume {2} while active at a rate of {3}", internalProp.propName,
                                                 internalProp.propID, consumeWhileActiveName, consumeWhileActiveAmount);
                            }
                        }
                    }
                }

                if (groupList.ContainsKey(actionName))
                {
                    currentState = vessel.ActionGroups[groupList[actionName]];
                    // action group switches may not belong to a radio group
                    switchGroupIdentifier = -1;
                }
                else
                {
                    isCustomAction = true;
                    switch (actionName)
                    {
                    case "intlight":
                        persistentVarName         = internalLightName;
                        lightObjects              = internalModel.FindModelComponents <Light>();
                        needsElectricChargeValue |= string.IsNullOrEmpty(needsElectricCharge) || needsElectricChargeValue;
                        break;

                    case "plugin":
                        persistentVarName = string.Empty;
                        comp.UpdateDataRefreshRate(refreshRate);

                        foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP"))
                        {
                            if (node.GetValue("name") == internalProp.propName)
                            {
                                foreach (ConfigNode pluginConfig in node.GetNodes("MODULE")[moduleID].GetNodes("PLUGINACTION"))
                                {
                                    if (pluginConfig.HasValue("name") && pluginConfig.HasValue("actionMethod"))
                                    {
                                        string action = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("actionMethod").Trim();
                                        actionHandler = (Action <bool>)comp.GetMethod(action, internalProp, typeof(Action <bool>));

                                        if (actionHandler == null)
                                        {
                                            JUtil.LogErrorMessage(this, "Failed to instantiate action handler {0}", pluginConfig.GetValue("name"));
                                        }
                                        else
                                        {
                                            if (pluginConfig.HasValue("stateMethod"))
                                            {
                                                string state = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("stateMethod").Trim();
                                                stateHandler = (Func <bool>)comp.GetMethod(state, internalProp, typeof(Func <bool>));
                                            }
                                            isPluginAction = true;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        if (actionHandler == null)
                        {
                            actionName = "dummy";
                            JUtil.LogMessage(this, "Plugin handlers did not start, reverting to dummy mode.");
                        }
                        break;

                    default:
                        persistentVarName = "switch" + internalProp.propID + "_" + moduleID;
                        break;
                    }
                    if (!string.IsNullOrEmpty(perPodPersistenceName))
                    {
                        persistentVarName = perPodPersistenceName;
                    }
                    else
                    {
                        // If there's no persistence name, there's no valid group id for this switch
                        switchGroupIdentifier = -1;
                    }
                }

                if (needsElectricChargeValue || !string.IsNullOrEmpty(persistentVarName) || !string.IsNullOrEmpty(perPodMasterSwitchName) || !string.IsNullOrEmpty(masterVariableName))
                {
                    persistence = new PersistenceAccessor(internalProp);

                    comp.UpdateDataRefreshRate(refreshRate);

                    if (!string.IsNullOrEmpty(masterVariableName))
                    {
                        masterVariable = new VariableOrNumber(masterVariableName, this);
                        string[] range = masterVariableRange.Split(',');
                        if (range.Length == 2)
                        {
                            masterRange[0] = new VariableOrNumber(range[0], this);
                            masterRange[1] = new VariableOrNumber(range[1], this);
                        }
                        else
                        {
                            masterVariable = null;
                        }
                    }
                }

                // set up the toggle switch
                if (!string.IsNullOrEmpty(switchTransform))
                {
                    SmarterButton.CreateButton(internalProp, switchTransform, Click);
                }

                if (isCustomAction)
                {
                    if (isPluginAction && stateHandler != null)
                    {
                        currentState = stateHandler();
                    }
                    else
                    {
                        if (persistence != null)
                        {
                            if (switchGroupIdentifier >= 0)
                            {
                                int activeSwitch = persistence.GetVar(persistentVarName, 0);

                                currentState = customGroupList[actionName] = (switchGroupIdentifier == activeSwitch);
                            }
                            else
                            {
                                currentState = customGroupList[actionName] = persistence.GetBool(persistentVarName, initialState);
                            }

                            if (actionName == "intlight")
                            {
                                // We have to restore lighting after reading the
                                // persistent variable.
                                SetInternalLights(customGroupList[actionName]);
                            }
                        }
                    }
                }

                if (persistence != null && !persistence.HasVar(persistentVarName))
                {
                    if (switchGroupIdentifier >= 0)
                    {
                        if (currentState)
                        {
                            persistence.SetVar(persistentVarName, switchGroupIdentifier);
                        }
                    }
                    else
                    {
                        persistence.SetVar(persistentVarName, currentState);
                    }
                }

                if (!string.IsNullOrEmpty(animationName))
                {
                    // Set up the animation
                    Animation[] animators = animateExterior ? part.FindModelAnimators(animationName) : internalProp.FindModelAnimators(animationName);
                    if (animators.Length > 0)
                    {
                        anim = animators[0];
                    }
                    else
                    {
                        JUtil.LogErrorMessage(this, "Could not find animation \"{0}\" on {2} \"{1}\"",
                                              animationName, animateExterior ? part.name : internalProp.name, animateExterior ? "part" : "prop");
                        return;
                    }
                    anim[animationName].wrapMode = WrapMode.Once;

                    if (currentState ^ reverse)
                    {
                        anim[animationName].speed          = float.MaxValue;
                        anim[animationName].normalizedTime = 0;
                    }
                    else
                    {
                        anim[animationName].speed          = float.MinValue;
                        anim[animationName].normalizedTime = 1;
                    }
                    anim.Play(animationName);
                }
                else if (!string.IsNullOrEmpty(coloredObject))
                {
                    // Set up the color shift.
                    colorShiftRenderer = internalProp.FindModelComponent <Renderer>(coloredObject);
                    disabledColorValue = ConfigNode.ParseColor32(disabledColor);
                    enabledColorValue  = ConfigNode.ParseColor32(enabledColor);
                    colorShiftRenderer.material.SetColor(colorName, (currentState ^ reverse ? enabledColorValue : disabledColorValue));
                }
                else
                {
                    JUtil.LogMessage(this, "Warning, neither color nor animation are defined in prop {0} #{1}.", internalProp.propName, internalProp.propID);
                }

                audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false);

                startupComplete = true;
            }
            catch
            {
                JUtil.AnnoyUser(this);
                enabled = false;
                throw;
            }
        }