Example #1
0
 /// <summary>
 /// Indicates whether the named persistent variable is present in the
 /// dictionary.
 /// </summary>
 /// <param name="name"></param>
 /// <param name="broadcast">Broadcast the request to other parts of the same craft?</param>
 /// <returns></returns>
 internal bool HasPersistentVariable(string name, bool broadcast)
 {
     if (persistentVars.ContainsKey(name))
     {
         return(true);
     }
     else if (broadcast)
     {
         RPMVesselComputer comp = RPMVesselComputer.Instance(vessel);
         return(comp.HasPersistentVariable(name));
     }
     else
     {
         return(false);
     }
 }
Example #2
0
        public void Click()
        {
            RPMVesselComputer comp = RPMVesselComputer.Instance(vessel);
            bool switchEnabled     = true;

            if (!forcedShutdown)
            {
                if (perPodMasterSwitchValid)
                {
                    switchEnabled = comp.GetPersistentVariable(perPodMasterSwitchName, false);
                }
                if (masterVariable != null)
                {
                    switchEnabled = masterVariable.IsInRange(comp);
                }
            }
            if (!switchEnabled)
            {
                // If the master switch is 'off' and we're not here because
                // of a forced shutdown, don't allow this switch to work.
                // early return
                return;
            }

            if (isCustomAction)
            {
                if (switchGroupIdentifier >= 0)
                {
                    if (!forcedShutdown && !customGroupState)
                    {
                        customGroupState = true;
                        if (persistentVarValid)
                        {
                            comp.SetPersistentVariable(persistentVarName, switchGroupIdentifier);
                        }
                    }
                    // else: can't turn off a radio group switch.
                }
                else if (customAction == CustomActions.Plugin && stateVariableValid)
                {
                    int ivalue = comp.ProcessVariable(stateVariable).MassageToInt();
                    customGroupState = (ivalue < 1) && !forcedShutdown;
                }
                else
                {
                    customGroupState = !customGroupState;
                    if (persistentVarValid)
                    {
                        comp.SetPersistentVariable(persistentVarName, customGroupState);
                    }
                }
            }
            else
            {
                vessel.ActionGroups.ToggleGroup(kspAction);
            }

            // Now we do extra things that with regular actions can't happen.
            switch (customAction)
            {
            case CustomActions.IntLight:
                SetInternalLights(customGroupState);
                break;

            case CustomActions.Plugin:
                actionHandler(customGroupState);
                break;

            case CustomActions.Stage:
                if (InputLockManager.IsUnlocked(ControlTypes.STAGING))
                {
                    StageManager.ActivateNextStage();
                }
                break;

            case CustomActions.TransferToPersistent:
                if (stateVariableValid)
                {
                    // stateVariable can disable the button functionality.
                    int ivalue = comp.ProcessVariable(stateVariable).MassageToInt();
                    if (ivalue < 1)
                    {
                        return;     // early - button disabled
                    }
                }
                float getValue = comp.ProcessVariable(transferGetter).MassageToFloat();
                comp.SetPersistentVariable(transferPersistentName, getValue);
                break;

            case CustomActions.TransferFromPersistent:
                if (stateVariableValid)
                {
                    // stateVariable can disable the button functionality.
                    int ivalue = comp.ProcessVariable(stateVariable).MassageToInt();
                    if (ivalue < 1)
                    {
                        return;     // early - button disabled
                    }
                }
                if (comp.HasPersistentVariable(transferPersistentName))
                {
                    transferSetter(comp.GetPersistentVariable(transferPersistentName, 0.0).MassageToDouble());
                }
                break;

            case CustomActions.TransferFromVariable:
                if (stateVariableValid)
                {
                    // stateVariable can disable the button functionality.
                    int ivalue = comp.ProcessVariable(stateVariable).MassageToInt();
                    if (ivalue < 1)
                    {
                        return;     // early - button disabled
                    }
                }
                double xferValue = comp.ProcessVariable(transferGetter).MassageToDouble();
                transferSetter(xferValue);
                break;

            case CustomActions.Transfer:
                JUtil.LogInfo(this, "The deprecated CustomActions.Transfer path was executed");

                /*if (stateVariableValid)
                 * {
                 *  // stateVariable can disable the button functionality.
                 *  int ivalue = comp.ProcessVariable(stateVariable).MassageToInt();
                 *  if (ivalue < 1)
                 *  {
                 *      return; // early - button disabled
                 *  }
                 * }
                 * if (!string.IsNullOrEmpty(transferGetter))
                 * {
                 *  float value = comp.ProcessVariable(transferGetter).MassageToFloat();
                 *  comp.SetPersistentVariable(transferPersistentName, value);
                 * }
                 * else if (comp.HasPersistentVariable(transferPersistentName))
                 * {
                 *  transferSetter(comp.GetPersistentVariable(transferPersistentName, 0.0).MassageToDouble());
                 * }*/
                break;
            }
        }
Example #3
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;
                            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;
                        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}", action);
                                        }
                                        else
                                        {
                                            if (pluginConfig.HasValue("stateMethod"))
                                            {
                                                string state = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("stateMethod").Trim();
                                                stateVariable      = "PLUGIN_" + state;
                                                stateVariableValid = true;
                                            }
                                            else if (pluginConfig.HasValue("stateVariable"))
                                            {
                                                stateVariable      = pluginConfig.GetValue("stateVariable").Trim();
                                                stateVariableValid = true;
                                            }
                                            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;
                        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("TRANSFERACTION"))
                                {
                                    if (pluginConfig.HasValue("name") || pluginConfig.HasValue("getVariable"))
                                    {
                                        if (pluginConfig.HasValue("stateMethod"))
                                        {
                                            string state = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("stateMethod").Trim();
                                            stateVariable      = "PLUGIN_" + state;
                                            stateVariableValid = true;
                                        }
                                        else if (pluginConfig.HasValue("stateVariable"))
                                        {
                                            stateVariable      = pluginConfig.GetValue("stateVariable").Trim();
                                            stateVariableValid = true;
                                        }
                                        if (pluginConfig.HasValue("setMethod"))
                                        {
                                            string action = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("setMethod").Trim();
                                            transferSetter = (Action <double>)comp.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 = 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>)comp.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         = "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         = 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 (string.IsNullOrEmpty(transferGetter) && transferSetter == null)
                        {
                            actionName         = "dummy";
                            stateVariable      = string.Empty;
                            stateVariableValid = false;
                            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) ||
                    !string.IsNullOrEmpty(transferGetter) || transferSetter != null)
                {
                    comp.UpdateDataRefreshRate(refreshRate);

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

                // 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 && stateVariableValid)
                    {
                        try
                        {
                            currentState = (comp.ProcessVariable(stateVariable).MassageToInt()) > 0;
                        }
                        catch
                        {
                            // no-op
                        }
                    }
                    else
                    {
                        if (persistentVarValid)
                        {
                            if (switchGroupIdentifier >= 0)
                            {
                                int activeSwitch = comp.GetPersistentVariable(persistentVarName, 0).MassageToInt();

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

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

                if (persistentVarValid && !comp.HasPersistentVariable(persistentVarName))
                {
                    if (switchGroupIdentifier >= 0)
                    {
                        if (currentState)
                        {
                            comp.SetPersistentVariable(persistentVarName, switchGroupIdentifier);
                        }
                    }
                    else
                    {
                        comp.SetPersistentVariable(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.
                    Renderer colorShiftRenderer = internalProp.FindModelComponent <Renderer>(coloredObject);
                    disabledColorValue = ConfigNode.ParseColor32(disabledColor);
                    enabledColorValue  = ConfigNode.ParseColor32(enabledColor);
                    colorShiftMaterial = colorShiftRenderer.material;
                    colorShiftMaterial.SetColor(colorName, (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
            {
                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;
                }

                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;
            }
        }