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 void Start() { rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true); if (string.IsNullOrEmpty(soundURL)) { JUtil.LogMessage(this, "JSIInternalBackgroundNoise called with no soundURL"); Destroy(this); return; } if (needsElectricCharge) { rpmComp.UpdateDataRefreshRate(soundCheckRate); RPMVesselComputer comp = RPMVesselComputer.Instance(vessel.id); electricChargeReserve = rpmComp.ProcessVariable(resourceName, comp).MassageToFloat(); } audioOutput = new FXGroup("RPM" + internalModel.internalName + vessel.id); audioOutput.audio = internalModel.gameObject.AddComponent <AudioSource>(); audioOutput.audio.clip = GameDatabase.Instance.GetAudioClip(soundURL.EnforceSlashes()); audioOutput.audio.Stop(); audioOutput.audio.volume = GameSettings.SHIP_VOLUME * soundVolume; audioOutput.audio.rolloffMode = AudioRolloffMode.Logarithmic; audioOutput.audio.maxDistance = 10f; audioOutput.audio.minDistance = 8f; audioOutput.audio.dopplerLevel = 0f; audioOutput.audio.panStereo = 0f; audioOutput.audio.playOnAwake = false; audioOutput.audio.priority = 255; audioOutput.audio.loop = true; audioOutput.audio.pitch = 1f; }
public VariableHandler(ConfigNode node, RasterPropMonitorComputer ourComp) { handlerName = node.GetValue("name"); foreach (string variableRecord in node.GetValues("variable")) { var record = new VariableRecord(); string[] tokens = variableRecord.Split(','); if (tokens.Length >= 2) { double defaultDouble; if (double.TryParse(tokens[1], out defaultDouble)) { record.defaultValue = defaultDouble; } else { if (tokens[1].Trim() == "fallback") { record.fallback = true; } else { record.defaultString = tokens[1]; } } } if (tokens.Length >= 3) { record.cacheable = bool.Parse(tokens[2]); } handledVariables.Add(tokens[0], record); } active = InstantiateHandler(node, ourComp, out handlerFunction); }
internal SelectVariable(ConfigNode node, RasterPropMonitorComputer rpmComp) { name = node.GetValue("name"); foreach (ConfigNode sourceVarNode in node.GetNodes("VARIABLE_DEFINITION")) { bool reverseVal; VariableOrNumberRange vonr = ProcessSourceNode(sourceVarNode, rpmComp, out reverseVal); sourceVariables.Add(vonr); reverse.Add(reverseVal); VariableOrNumber val = rpmComp.InstantiateVariableOrNumber(sourceVarNode.GetValue("value")); result.Add(val); } if (node.HasValue("defaultValue")) { VariableOrNumber val = rpmComp.InstantiateVariableOrNumber(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); } }
public VariableLabelSet(ConfigNode node, Part part) { RasterPropMonitorComputer rpmComp = null; if (node.HasValue("labelText")) { string labelText = node.GetValue("labelText").Trim().UnMangleConfigText(); hasText = true; oneShot = !labelText.Contains("$&$"); rpmComp = RasterPropMonitorComputer.Instantiate(part, true); label = new StringProcessorFormatter(labelText, rpmComp); } else { hasText = false; oneShot = true; } if (node.HasValue("color")) { color = JUtil.ParseColor32(node.GetValue("color").Trim(), part, ref rpmComp); hasColor = true; } else { hasColor = false; } }
public static string ProcessString(string input, RasterPropMonitorComputer rpmComp) { try { if (input.IndexOf(JUtil.VariableListSeparator[0], StringComparison.Ordinal) >= 0) { string[] tokens = input.Split(JUtil.VariableListSeparator, StringSplitOptions.RemoveEmptyEntries); if (tokens.Length != 2) { return "FORMAT ERROR"; } else { RPMVesselComputer comp = RPMVesselComputer.Instance(rpmComp.vessel); string[] vars = tokens[1].Split(JUtil.VariableSeparator, StringSplitOptions.RemoveEmptyEntries); var variables = new object[vars.Length]; for (int i = 0; i < vars.Length; i++) { variables[i] = rpmComp.ProcessVariable(vars[i].Trim(), comp); } string output = string.Format(fp, tokens[0], variables); return output.TrimEnd(); } } } catch (Exception e) { JUtil.LogErrorMessage(rpmComp, "Bad format on string {0}: {1}", input, e); } return input.TrimEnd(); }
public double Evaluate(RasterPropMonitorComputer comp) { float result = comp.ProcessVariable(sourceVariable, -1).MassageToFloat(); Vector2 sourceRange; if (!string.IsNullOrEmpty(sourceMinStr)) { sourceRange.x = comp.ProcessVariable(sourceMinStr, -1).MassageToFloat(); } else { sourceRange.x = sourceMin; } if (!string.IsNullOrEmpty(sourceMaxStr)) { sourceRange.y = comp.ProcessVariable(sourceMaxStr, -1).MassageToFloat(); } else { sourceRange.y = sourceMax; } return JUtil.DualLerp(mappedRange, sourceRange, result); }
public void Start() { rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true); if (string.IsNullOrEmpty(soundURL)) { JUtil.LogMessage(this, "JSIInternalBackgroundNoise called with no soundURL"); Destroy(this); return; } if (needsElectricCharge) { rpmComp.UpdateDataRefreshRate(soundCheckRate); RPMVesselComputer comp = RPMVesselComputer.Instance(vessel.id); electricChargeReserve = rpmComp.ProcessVariable(resourceName, comp).MassageToFloat(); } audioOutput = new FXGroup("RPM" + internalModel.internalName + vessel.id); audioOutput.audio = internalModel.gameObject.AddComponent<AudioSource>(); audioOutput.audio.clip = GameDatabase.Instance.GetAudioClip(soundURL.EnforceSlashes()); audioOutput.audio.Stop(); audioOutput.audio.volume = GameSettings.SHIP_VOLUME * soundVolume; audioOutput.audio.rolloffMode = AudioRolloffMode.Logarithmic; audioOutput.audio.maxDistance = 10f; audioOutput.audio.minDistance = 8f; audioOutput.audio.dopplerLevel = 0f; audioOutput.audio.panStereo = 0f; audioOutput.audio.playOnAwake = false; audioOutput.audio.priority = 255; audioOutput.audio.loop = true; audioOutput.audio.pitch = 1f; }
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); }
internal JSIDummy(ConfigNode node, RasterPropMonitorComputer rpmComp) : base(node) { if (!node.HasValue("perPodPersistenceName")) { throw new Exception("Trying to create Dummy JSIAction with no perPodPersistenceName"); } perPodPersistenceName = node.GetValue("perPodPersistenceName"); if (string.IsNullOrEmpty(perPodPersistenceName)) { throw new Exception("Invalid perPodPersistenceName supplied for Dummy JSIAction"); } if (node.HasValue("initialState")) { if (!bool.TryParse(node.GetValue("initialState"), out currentState)) { currentState = false; } } else { currentState = false; } currentState = rpmComp.GetBool(perPodPersistenceName, currentState); rpmComp.SetVar(perPodPersistenceName, currentState); }
public static string ProcessString(string input, RasterPropMonitorComputer rpmComp) { try { if (input.IndexOf(JUtil.VariableListSeparator[0], StringComparison.Ordinal) >= 0) { string[] tokens = input.Split(JUtil.VariableListSeparator, StringSplitOptions.RemoveEmptyEntries); if (tokens.Length != 2) { return("FORMAT ERROR"); } else { RPMVesselComputer comp = RPMVesselComputer.Instance(rpmComp.vessel); string[] vars = tokens[1].Split(JUtil.VariableSeparator, StringSplitOptions.RemoveEmptyEntries); var variables = new object[vars.Length]; for (int i = 0; i < vars.Length; i++) { variables[i] = rpmComp.ProcessVariable(vars[i].Trim(), comp); } string output = string.Format(fp, tokens[0], variables); return(output.TrimEnd()); } } } catch (Exception e) { JUtil.LogErrorMessage(rpmComp, "Bad format on string {0}: {1}", input, e); } return(input.TrimEnd()); }
public void Start() { if (!string.IsNullOrEmpty(borderColor)) { borderColorValue = ConfigNode.ParseColor32(borderColor); } if (!string.IsNullOrEmpty(backgroundColor)) { backgroundColorValue = ConfigNode.ParseColor32(backgroundColor); } comp = RasterPropMonitorComputer.Instantiate(internalProp); graphSpace = new Rect(); graphSpace.xMin = graphRect.x; graphSpace.yMin = graphRect.y; graphSpace.xMax = graphRect.z; graphSpace.yMax = graphRect.w; xGraphSpan = xSpan; interval = secondsBetweenSamples; if (GameDatabase.Instance.ExistsTexture(backgroundTextureURL.EnforceSlashes())) { backgroundTexture = GameDatabase.Instance.GetTexture(backgroundTextureURL.EnforceSlashes(), false); } var bottomLeft = new Vector2(graphSpace.xMin, graphSpace.yMin); var bottomRight = new Vector2(graphSpace.xMax, graphSpace.yMin); var topLeft = new Vector2(graphSpace.xMin, graphSpace.yMax); var topRight = new Vector2(graphSpace.xMax, graphSpace.yMax); switch (borders) { case 2: borderVertices.Add(bottomRight); borderVertices.Add(bottomLeft); borderVertices.Add(topLeft); break; case 4: borderVertices.Add(bottomLeft); borderVertices.Add(topLeft); borderVertices.Add(topRight); borderVertices.Add(bottomRight); borderVertices.Add(bottomLeft); break; } foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("JSIGRAPHSET")) { if (node.HasValue("name") && node.GetValue("name") == graphSet) { foreach (ConfigNode graphNode in node.GetNodes("GRAPH")) { graphs.Add(new GraphLine(graphNode, xGraphSpan, ySpan, interval, comp)); } } } JUtil.LogMessage(this, "Graphing {0} values.", graphs.Count); startupComplete = true; }
private static VariableOrNumberRange ProcessSourceNode(ConfigNode node, RasterPropMonitorComputer rpmComp, out bool reverse) { VariableOrNumberRange range; if (node.HasValue("range")) { string[] tokens = { }; tokens = node.GetValue("range").Split(','); if (tokens.Length != 2) { throw new ArgumentException("Found an unparseable value reading custom SOURCE_VARIABLE range"); } range = new VariableOrNumberRange(rpmComp, node.GetValue("name").Trim(), tokens[0].Trim(), tokens[1].Trim()); } else { range = new VariableOrNumberRange(rpmComp, node.GetValue("name").Trim(), float.MinValue.ToString(), float.MaxValue.ToString()); } if (node.HasValue("reverse")) { if (!bool.TryParse(node.GetValue("reverse"), out reverse)) { throw new ArgumentException("So is 'reverse' true or false?"); } } else { reverse = false; } return(range); }
public GraphLine(ConfigNode node, double xSpan, Vector2 ySpan, double secondsBetweenSamples, RasterPropMonitorComputer compInstance) { comp = compInstance; maxPoints = (int)(xSpan / secondsBetweenSamples); horizontalSpan = xSpan; verticalSpan = ySpan; if (!node.HasData) { throw new ArgumentException("Graph block with no data?"); } if (node.HasValue("variableName")) { variableName = node.GetValue("variableName").Trim(); isFlat = double.TryParse(variableName, out flatValue); } else { throw new ArgumentException("Draw a graph of what?"); } lineColor = Color.white; if (node.HasValue("color")) { lineColor = ConfigNode.ParseColor32(node.GetValue("color")); } floatingMax = node.HasValue("floatingMaximum"); floatingMin = node.HasValue("floatingMinimum"); JUtil.LogMessage(this, "Graphing {0} in color {1}", variableName, lineColor); }
// TODO: Add support for multi-line processed support. public StringProcessorFormatter(string input, RasterPropMonitorComputer rpmComp) { if (string.IsNullOrEmpty(input)) { formatString = ""; usesComp = false; } else if (input.IndexOf(JUtil.VariableListSeparator[0], StringComparison.Ordinal) >= 0) { string[] tokens = input.Split(JUtil.VariableListSeparator, StringSplitOptions.RemoveEmptyEntries); if (tokens.Length != 2) { throw new ArgumentException(string.Format("Invalid format string: {0}", input)); } else { string[] sourceVarStrings = tokens[1].Split(JUtil.VariableSeparator, StringSplitOptions.RemoveEmptyEntries); sourceVariables = new VariableOrNumber[sourceVarStrings.Length]; for (int i = 0; i < sourceVarStrings.Length; ++i) { sourceVariables[i] = rpmComp.InstantiateVariableOrNumber(sourceVarStrings[i]); } sourceValues = new object[sourceVariables.Length]; formatString = tokens[0].TrimEnd(); usesComp = true; } } else { formatString = input.TrimEnd(); usesComp = false; } }
private void UpdateMethods(RasterPropMonitorComputer rpmComp) { GetSmartassMode = (Func <int>)rpmComp.GetMethod("JSIMechJeb:GetSmartassMode", internalProp, typeof(Func <int>)); SetSmartassMode = (Action <JSIMechJeb.Target>)rpmComp.GetMethod("JSIMechJeb:SetSmartassMode", internalProp, typeof(Action <JSIMechJeb.Target>)); SetForceRoll = (Action <bool, double>)rpmComp.GetMethod("JSIMechJeb:ForceRoll", internalProp, typeof(Action <bool, double>)); GetModuleExists = (Func <string, bool>)rpmComp.GetMethod("JSIMechJeb:GetModuleExists", internalProp, typeof(Func <string, bool>)); CircularizeAt = (Action <double>)rpmComp.GetMethod("JSIMechJeb:CircularizeAt", internalProp, typeof(Action <double>)); PositionTargetExists = (Func <bool>)rpmComp.GetMethod("JSIMechJeb:PositionTargetExists", internalProp, typeof(Func <bool>)); AutopilotEnabled = (Func <bool>)rpmComp.GetMethod("JSIMechJeb:AutopilotEnabled", internalProp, typeof(Func <bool>)); GetForceRollAngle = (Func <double>)rpmComp.GetMethod("JSIMechJeb:GetForceRollAngle", internalProp, typeof(Func <double>)); AscentAP = (Action <bool>)rpmComp.GetMethod("JSIMechJeb:ButtonAscentGuidance", internalProp, typeof(Action <bool>)); AscentAPState = (Func <bool>)rpmComp.GetMethod("JSIMechJeb:ButtonAscentGuidanceState", internalProp, typeof(Func <bool>)); LandingAP = (Action <bool>)rpmComp.GetMethod("JSIMechJeb:ButtonLandingGuidance", internalProp, typeof(Action <bool>)); LandingAPState = (Func <bool>)rpmComp.GetMethod("JSIMechJeb:ButtonLandingGuidanceState", internalProp, typeof(Func <bool>)); DockingAP = (Action <bool>)rpmComp.GetMethod("JSIMechJeb:ButtonDockingGuidance", internalProp, typeof(Action <bool>)); DockingAPState = (Func <bool>)rpmComp.GetMethod("JSIMechJeb:ButtonDockingGuidanceState", internalProp, typeof(Func <bool>)); ForceRoll = (Action <bool>)rpmComp.GetMethod("JSIMechJeb:ButtonForceRoll", internalProp, typeof(Action <bool>)); ForceRollState = (Func <bool>)rpmComp.GetMethod("JSIMechJeb:ButtonForceRollState", internalProp, typeof(Func <bool>)); ExecuteNextNode = (Action <bool>)rpmComp.GetMethod("JSIMechJeb:ButtonNodeExecute", internalProp, typeof(Action <bool>)); ExecuteNextNodeState = (Func <bool>)rpmComp.GetMethod("JSIMechJeb:ButtonNodeExecuteState", internalProp, typeof(Func <bool>)); }
public void Start() { if (HighLogic.LoadedSceneIsEditor) { return; } rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true); lastOrientation = navBall.rotation; if (string.IsNullOrEmpty(variableName) || string.IsNullOrEmpty(range)) { JUtil.LogErrorMessage(this, "variableName or range was null!"); return; } string[] tokens = range.Split(','); if (tokens.Length != 2) { JUtil.LogErrorMessage(this, "range '{0}' did not have exactly two values!", range); return; } enablingVariable = new VariableOrNumberRange(rpmComp, variableName, tokens[0], tokens[1]); }
override internal void Click(bool newState, Vessel vessel, RasterPropMonitorComputer rpmComp) { currentState = !currentState; rpmComp.SetVar(persistentVarName, currentState); SetInternalLights(currentState); }
private void UndockCallback(EventReport report) { if (JUtil.IsActiveVessel(vessel)) { RasterPropMonitorComputer rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true); UpdateMethods(rpmComp); } }
public void Start() { try { comp = RasterPropMonitorComputer.Instantiate(internalProp); textObjTransform = internalProp.FindModelTransform(labelTransform); textObj = InternalComponents.Instance.CreateText(fontName, fontSize, textObjTransform, string.Empty); activeLabel = 0; SmarterButton.CreateButton(internalProp, switchTransform, Click); ConfigNode moduleConfig = null; foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP")) { if (node.GetValue("name") == internalProp.propName) { moduleConfig = node.GetNodes("MODULE")[moduleID]; ConfigNode[] variableNodes = moduleConfig.GetNodes("VARIABLESET"); for (int i = 0; i < variableNodes.Length; i++) { try { labelsEx.Add(new VariableLabelSet(variableNodes[i])); } catch (ArgumentException e) { JUtil.LogMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID); } } break; } } // Fallback: If there are no VARIABLESET blocks, we treat the module configuration itself as a variableset block. if (labelsEx.Count < 1 && moduleConfig != null) { try { labelsEx.Add(new VariableLabelSet(moduleConfig)); } catch (ArgumentException e) { JUtil.LogMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID); } } if (labelsEx.Count == 0) { JUtil.LogMessage(this, "No labels defined."); throw new ArgumentException("No labels defined"); } colorShiftRenderer = internalProp.FindModelComponent<Renderer>(coloredObject); if (labelsEx[activeLabel].hasColor) { colorShiftRenderer.material.SetColor(colorName, labelsEx[activeLabel].color); } if (labelsEx[activeLabel].hasText) { textObj.text.Text = StringProcessor.ProcessString(labelsEx[activeLabel].labelText, comp); } audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false); JUtil.LogMessage(this, "Configuration complete in prop {1}, supporting {0} variable indicators.", labelsEx.Count, internalProp.propID); } catch { JUtil.AnnoyUser(this); enabled = false; throw; } }
public void Start() { comp = RasterPropMonitorComputer.Instantiate(internalProp); textObjTransform = internalProp.FindModelTransform(transformName); textObj = InternalComponents.Instance.CreateText(fontName, fontSize, textObjTransform, string.Empty); // Force oneshot if there's no variables: oneshot |= !labelText.Contains("$&$"); sourceString = labelText.UnMangleConfigText(); }
public void Start() { if (HighLogic.LoadedSceneIsEditor) { return; } try { rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true); if (string.IsNullOrEmpty(layout)) { throw new ArgumentNullException("layout"); } foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("RPM_GRAPHING_BACKGROUND")) { if (node.GetValue("layout") == layout) { if (!node.HasValue("backgroundColor")) { JUtil.LogErrorMessage(this, "?!? no backgroundColor"); } string s = node.GetValue("backgroundColor"); if (string.IsNullOrEmpty(s)) { JUtil.LogErrorMessage(this, "backgroundColor is missing?"); } backgroundColorValue = ConfigNode.ParseColor32(node.GetValue("backgroundColor")); ConfigNode[] dataNodes = node.GetNodes("DATA_SET"); for (int i = 0; i < dataNodes.Length; i++) { try { dataSets.Add(new DataSet(dataNodes[i], rpmComp)); } catch (ArgumentException e) { JUtil.LogErrorMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID); throw; } } break; } } startupComplete = true; } catch { JUtil.AnnoyUser(this); throw; } }
public object Evaluate(RasterPropMonitorComputer comp) { double result = comp.ProcessVariable(name).MassageToDouble(); bool returnResult = (result >= minValue && result <= maxValue); //JUtil.LogMessage(this, "Evaluate {0} ({3}, {4}) = {1}, returning {2}", name, result, returnResult, minValue, maxValue); return((reverse) ? !returnResult : returnResult); }
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 PersistenceAccessor(Part thatPart) { for (int i = 0; i < thatPart.Modules.Count; i++) { if (thatPart.Modules[i].ClassName == typeof(RasterPropMonitorComputer).Name) { persistenceStorage = thatPart.Modules[i] as RasterPropMonitorComputer; } } }
public void OnDestroy() { // MOARdV TODO: Tear down everything. if (screenTexture != null) { screenTexture.Release(); screenTexture = null; } rpmComp = null; }
/// <summary> /// Iterate over all RPMC objects in the craft and set the specified /// persistent var to the same value. /// </summary> /// <param name="name"></param> /// <param name="value"></param> internal void SetPersistentVariable(string name, object value) { if (vessel != null) { for (int partIdx = 0; partIdx < vessel.parts.Count; ++partIdx) { RasterPropMonitorComputer rpmc = RasterPropMonitorComputer.Instantiate(vessel.parts[partIdx], false); rpmc.SetPersistentVariable(name, value, false); } } }
public object Evaluate(RasterPropMonitorComputer comp) { // MOARdV TODO: Reevaluate (SWIDT?) this method if math expressions are added object evaluation = sourceVariables[0].Evaluate(comp); for (int i = 1; i < sourceVariables.Count; ++i) { object nextValue = sourceVariables[i].Evaluate(comp); if (!(nextValue is bool)) { throw new ArgumentException("CustomVariable.Evaluate - source variable did not return a bool?"); } switch (op) { case Operator.AND: case Operator.NAND: if (nextValue is bool) { evaluation = ((bool)evaluation) && ((bool)nextValue); } break; case Operator.OR: case Operator.NOR: if (nextValue is bool) { evaluation = ((bool)evaluation) || ((bool)nextValue); } break; case Operator.XOR: if (nextValue is bool) { evaluation = ((bool)evaluation) ^ ((bool)nextValue); } break; default: throw new ArgumentException("CustomVariable.Evaluate was called with an invalid operator?"); case Operator.NONE: break; } } if (op == Operator.NAND || op == Operator.NOR) { evaluation = !((bool)evaluation); } return(evaluation.GetHashCode()); }
internal CustomVariable(ConfigNode node, RasterPropMonitorComputer rpmComp) { name = node.GetValue("name"); foreach (ConfigNode sourceVarNode in node.GetNodes("SOURCE_VARIABLE")) { bool reverseVal; VariableOrNumberRange vonr = ProcessSourceNode(sourceVarNode, rpmComp, out reverseVal); sourceVariables.Add(vonr); reverse.Add(reverseVal); } 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.AND.ToString()) { op = Operator.AND; } else if (oper == Operator.OR.ToString()) { op = Operator.OR; } else if (oper == Operator.NAND.ToString()) { op = Operator.NAND; } else if (oper == Operator.NOR.ToString()) { op = Operator.NOR; } else if (oper == Operator.XOR.ToString()) { op = Operator.XOR; } else if (oper == Operator.ISNANORINF.ToString()) { op = Operator.ISNANORINF; } else { throw new ArgumentException("Found an invalid operator type in RPM_CUSTOM_VARIABLE", oper); } }
public void Start() { try { if (!string.IsNullOrEmpty(borderColor)) borderColorValue = ConfigNode.ParseColor32(borderColor); if (!string.IsNullOrEmpty(backgroundColor)) backgroundColorValue = ConfigNode.ParseColor32(backgroundColor); comp = RasterPropMonitorComputer.Instantiate(internalProp); graphSpace = new Rect(); graphSpace.xMin = graphRect.x; graphSpace.yMin = graphRect.y; graphSpace.xMax = graphRect.z; graphSpace.yMax = graphRect.w; xGraphSpan = xSpan; interval = secondsBetweenSamples; if (GameDatabase.Instance.ExistsTexture(backgroundTextureURL.EnforceSlashes())) backgroundTexture = GameDatabase.Instance.GetTexture(backgroundTextureURL.EnforceSlashes(), false); var bottomLeft = new Vector2(graphSpace.xMin, graphSpace.yMin); var bottomRight = new Vector2(graphSpace.xMax, graphSpace.yMin); var topLeft = new Vector2(graphSpace.xMin, graphSpace.yMax); var topRight = new Vector2(graphSpace.xMax, graphSpace.yMax); switch (borders) { case 2: borderVertices.Add(bottomRight); borderVertices.Add(bottomLeft); borderVertices.Add(topLeft); break; case 4: borderVertices.Add(bottomLeft); borderVertices.Add(topLeft); borderVertices.Add(topRight); borderVertices.Add(bottomRight); borderVertices.Add(bottomLeft); break; } foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes ("JSIGRAPHSET")) { if (node.HasValue("name") && node.GetValue("name") == graphSet) foreach (ConfigNode graphNode in node.GetNodes("GRAPH")) graphs.Add(new GraphLine(graphNode, xGraphSpan, ySpan, interval, comp)); } JUtil.LogMessage(this, "Graphing {0} values.", graphs.Count); startupComplete = true; } catch { JUtil.AnnoyUser(this); throw; } }
public ExternalVariableHandlers(RasterPropMonitorComputer ourComp) { foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes ("RPMCVARIABLEHANDLER")) { if (!node.HasValue("name") || !node.HasValue("method")) { JUtil.LogMessage(ourComp, "A variable handler configuration block is missing key items and was ignored."); } else { handlers.Add(new VariableHandler(node, ourComp)); } } foreach (VariableHandler thatHandler in handlers) { JUtil.LogMessage(ourComp, "Variable handler {0} is known and {1:;;\"not\"} loaded.", thatHandler.handlerName, thatHandler.active.GetHashCode()); } }
public void Start() { if (HighLogic.LoadedSceneIsEditor) { return; } try { rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true); Transform textObjTransform = internalProp.FindModelTransform(transformName); textObj = InternalComponents.Instance.CreateText("Arial", fontSize * 15.5f, textObjTransform, "", Color.green, false, "TopLeft"); // Force oneshot if there's no variables: oneshot |= !labelText.Contains("$&$"); string sourceString = labelText.UnMangleConfigText(); if (!string.IsNullOrEmpty(sourceString) && sourceString.Length > 1) { // Alow a " character to escape leading whitespace if (sourceString[0] == '"') { sourceString = sourceString.Substring(1); } } spf = new StringProcessorFormatter(sourceString, rpmComp); if (!oneshot) { rpmComp.UpdateDataRefreshRate(refreshRate); } if (!(string.IsNullOrEmpty(variableName) || string.IsNullOrEmpty(positiveColor) || string.IsNullOrEmpty(negativeColor) || string.IsNullOrEmpty(zeroColor))) { positiveColorValue = JUtil.ParseColor32(positiveColor, part, ref rpmComp); negativeColorValue = JUtil.ParseColor32(negativeColor, part, ref rpmComp); zeroColorValue = JUtil.ParseColor32(zeroColor, part, ref rpmComp); del = (Action <float>)Delegate.CreateDelegate(typeof(Action <float>), this, "OnCallback"); rpmComp.RegisterVariableCallback(variableName, del); registeredVessel = vessel.id; // Initialize the text color. Actually, callback registration took care of that } } catch (Exception e) { JUtil.LogErrorMessage(this, "Start failed with exception {0}", e); spf = new StringProcessorFormatter("x", rpmComp); } }
public void Start() { comp = RasterPropMonitorComputer.Instantiate(internalProp); textObjTransform = internalProp.FindModelTransform(labelTransform); textObj = InternalComponents.Instance.CreateText(fontName, fontSize, textObjTransform, string.Empty); activeLabel = 0; SmarterButton.CreateButton(internalProp, switchTransform, Click); ConfigNode moduleConfig = null; foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP")) { if (node.GetValue("name") == internalProp.propName) { moduleConfig = node.GetNodes("MODULE")[moduleID]; ConfigNode[] variableNodes = moduleConfig.GetNodes("VARIABLESET"); for (int i = 0; i < variableNodes.Length; i++) { try { labelsEx.Add(new VariableLabelSet(variableNodes[i])); } catch (ArgumentException e) { JUtil.LogMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID); } } break; } } // Fallback: If there are no VARIABLESET blocks, we treat the module configuration itself as a variableset block. if (labelsEx.Count < 1 && moduleConfig != null) { try { labelsEx.Add(new VariableLabelSet(moduleConfig)); } catch (ArgumentException e) { JUtil.LogMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID); } } colorShiftRenderer = internalProp.FindModelComponent <Renderer>(coloredObject); if (labelsEx[activeLabel].hasColor) { colorShiftRenderer.material.SetColor(colorName, labelsEx[activeLabel].color); } textObj.text.Text = StringProcessor.ProcessString(labelsEx[activeLabel].labelText, comp); audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false); JUtil.LogMessage(this, "Configuration complete in prop {1}, supporting {0} variable indicators.", labelsEx.Count, internalProp.propID); }
public void OnDestroy() { //JUtil.LogMessage(this, "OnDestroy()"); rpmComp = null; if (colorShiftMaterial != null) { UnityEngine.Object.Destroy(colorShiftMaterial); colorShiftMaterial = null; } actionHandler = null; transferGetter = null; transferSetter = null; audioOutput = null; loopingOutput = null; }
override internal void Click(bool newState, Vessel vessel, RasterPropMonitorComputer rpmComp) { if (kspAction == KSPActionGroup.Stage) { if (InputLockManager.IsUnlocked(ControlTypes.STAGING)) { vessel.ActionGroups.ToggleGroup(kspAction); Staging.ActivateNextStage(); } } else { vessel.ActionGroups.ToggleGroup(kspAction); } }
public void UpdateText(RasterPropMonitorComputer rpmComp) { // If there's a handler references method, it gets called before each text call. if (pageHandlerS.getHandlerReferences != null) { pageHandlerS.getHandlerReferences(pageHandlerModule, backgroundHandlerModule); } if (pageHandlerMethod != null) { processedText = pageHandlerMethod(screenWidth, screenHeight); if (processedText.IndexOf("$&$", StringComparison.Ordinal) != -1) { // There are processed variables in here? StringBuilder bf = new StringBuilder(); string[] linesArray = processedText.Split(JUtil.LineSeparator, StringSplitOptions.None); for (int i = 0; i < linesArray.Length; i++) { bf.AppendLine(StringProcessor.ProcessString(linesArray[i], rpmComp)); } processedText = bf.ToString(); } } else { if (isMutable) { if (spf == null) { string[] linesArray = text.Split(JUtil.LineSeparator, StringSplitOptions.None); spf = new StringProcessorFormatter[linesArray.Length]; for (int i = 0; i < linesArray.Length; ++i) { spf[i] = new StringProcessorFormatter(linesArray[i], rpmComp); } } StringBuilder bf = new StringBuilder(); for (int i = 0; i < spf.Length; i++) { bf.AppendLine(StringProcessor.ProcessString(spf[i], rpmComp)); } processedText = bf.ToString(); } } }
public PersistenceAccessor(MonoBehaviour referenceLocation) { if(referenceLocation is InternalProp) { comp = RasterPropMonitorComputer.Instantiate(referenceLocation); propID = (referenceLocation as InternalProp).propID; } else if(referenceLocation is Part) { comp = RasterPropMonitorComputer.Instantiate(referenceLocation); propID = -1; } else { throw new Exception("Instantiating PersistenceAccessor with indeterminate type"); } }
/// <summary> /// Initialize a VariableOrNumber /// </summary> /// <param name="input">The name of the variable</param> /// <param name="cacheable">Whether the variable is cacheable</param> /// <param name="rpmComp">The RasterPropMonitorComputer that owns the variable</param> internal VariableOrNumber(string input, bool cacheable, RasterPropMonitorComputer rpmComp_) { string varName = input.Trim(); if (varName == "MetersToFeet") { varName = RPMGlobals.MetersToFeet.ToString(); } else if (varName == "MetersPerSecondToKnots") { varName = RPMGlobals.MetersPerSecondToKnots.ToString(); } else if (varName == "MetersPerSecondToFeetPerMinute") { varName = RPMGlobals.MetersPerSecondToFeetPerMinute.ToString(); } float realValue; if (float.TryParse(varName, out realValue)) { // 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). variableName = realValue.ToString(); numericValue = realValue; isNumeric = true; variableType = VoNType.ConstantNumeric; } else if (input[0] == '$') { variableName = input; stringValue = input.Substring(1).Trim(); isNumeric = false; variableType = VoNType.ConstantString; } else { variableName = varName; variableType = VoNType.VariableValue; if (!cacheable) { rpmComp = rpmComp_; } } }
public object Evaluate(RasterPropMonitorComputer comp) { // MOARdV TODO: Reevaluate (SWIDT?) this method if math expressions are added object evaluation = sourceVariables[0].Evaluate(comp); for (int i = 1; i < sourceVariables.Count; ++i) { object nextValue = sourceVariables[i].Evaluate(comp); if(!(nextValue is bool)) { throw new ArgumentException("CustomVariable.Evaluate - source variable did not return a bool?"); } switch(op) { case Operator.AND: case Operator.NAND: if (nextValue is bool) { evaluation = ((bool)evaluation) && ((bool)nextValue); } break; case Operator.OR: case Operator.NOR: if (nextValue is bool) { evaluation = ((bool)evaluation) || ((bool)nextValue); } break; case Operator.XOR: if (nextValue is bool) { evaluation = ((bool)evaluation) ^ ((bool)nextValue); } break; default: throw new ArgumentException("CustomVariable.Evaluate was called with an invalid operator?"); case Operator.NONE: break; } } if (op == Operator.NAND || op == Operator.NOR) { evaluation = !((bool)evaluation); } return evaluation.GetHashCode(); }
public static string ProcessString(string input, RasterPropMonitorComputer comp, bool trim = true) { if (input.IndexOf(JUtil.VariableListSeparator[0], StringComparison.Ordinal) >= 0) { string[] tokens = input.Split(JUtil.VariableListSeparator, StringSplitOptions.RemoveEmptyEntries); if (tokens.Length != 2) { return "FORMAT ERROR"; } else { string[] vars = tokens[1].Split(JUtil.VariableSeparator, StringSplitOptions.RemoveEmptyEntries); var variables = new object[vars.Length]; for (int i = 0; i < vars.Length; i++) { variables[i] = comp.ProcessVariable(vars[i]); } string output = string.Format(fp, tokens[0], variables); return trim ? output.TrimEnd() : output; } } return trim ? input.TrimEnd() : input; }
public static string ProcessString(StringProcessorFormatter formatter, RasterPropMonitorComputer rpmComp) { if (formatter.usesComp) { try { RPMVesselComputer comp = RPMVesselComputer.Instance(rpmComp.vessel); for (int i = 0; i < formatter.sourceVariables.Length; ++i) { formatter.sourceValues[i] = formatter.sourceVariables[i].Get(); } return string.Format(fp, formatter.formatString, formatter.sourceValues); } catch(Exception e) { JUtil.LogErrorMessage(formatter, "Exception trapped in ProcessString for {1}: {0}", e, formatter.formatString); } } return formatter.formatString; }
public void Start() { if (needsElectricCharge) { comp = RasterPropMonitorComputer.Instantiate(internalProp); comp.UpdateRefreshRates(soundCheckRate, soundCheckRate); electricChargeReserve = (double)comp.ProcessVariable("ELECTRIC"); } audioOutput = new FXGroup("RPM" + internalModel.internalName + vessel.id); audioOutput.audio = internalModel.gameObject.AddComponent<AudioSource>(); audioOutput.audio.clip = GameDatabase.Instance.GetAudioClip(soundURL.EnforceSlashes()); audioOutput.audio.Stop(); audioOutput.audio.volume = GameSettings.SHIP_VOLUME * soundVolume; audioOutput.audio.rolloffMode = AudioRolloffMode.Logarithmic; audioOutput.audio.maxDistance = 10f; audioOutput.audio.minDistance = 8f; audioOutput.audio.dopplerLevel = 0f; audioOutput.audio.panLevel = 0f; audioOutput.audio.playOnAwake = false; audioOutput.audio.priority = 255; audioOutput.audio.loop = true; audioOutput.audio.pitch = 1f; }
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; } else { JUtil.LogErrorMessage(this, "Could not parse the 'scale' parameter: {0}", scale); } }
public Protractor(RasterPropMonitorComputer computer) { comp = computer; }
public DataSet(ConfigNode node, RasterPropMonitorComputer rpmComp) { 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(','); if(token.Length != 2) { throw new ArgumentException("Background scale did not contain two values"); } variable = new VariableOrNumberRange(rpmComp, node.GetValue("variableName").Trim(), token[0].Trim(), token[1].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, RasterPropMonitorComputer rpmComp, JSIVariableAnimator parent) { varAnim = parent; onChangeDelegate = (Action<float>)Delegate.CreateDelegate(typeof(Action<float>), this, "OnChange"); 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."); } string variableName = string.Empty; if (node.HasValue("variableName")) { variableName = node.GetValue("variableName").Trim(); } else if (node.HasValue("stateMethod")) { string stateMethod = node.GetValue("stateMethod").Trim(); // Verify the state method actually exists Func<bool> stateFunction = (Func<bool>)rpmComp.GetMethod(stateMethod, thisProp, typeof(Func<bool>)); if (stateFunction != null) { variableName = "PLUGIN_" + stateMethod; } else { throw new ArgumentException("Unrecognized stateMethod"); } } else { throw new ArgumentException("Missing variable name."); } if (node.HasValue("modulo")) { variable = new VariableOrNumberRange(rpmComp, variableName, tokens[0], tokens[1], node.GetValue("modulo")); usesModulo = true; } else { variable = new VariableOrNumberRange(rpmComp, variableName, tokens[0], tokens[1]); usesModulo = false; } // 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")) { string colorNameString = "_EmissiveColor"; if (node.HasValue("colorName")) { colorNameString = node.GetValue("colorName"); } colorName = Shader.PropertyToID(colorNameString); if (reverse) { activeColor = JUtil.ParseColor32(node.GetValue("passiveColor"), thisProp.part, ref rpmComp); passiveColor = JUtil.ParseColor32(node.GetValue("activeColor"), thisProp.part, ref rpmComp); } else { passiveColor = JUtil.ParseColor32(node.GetValue("passiveColor"), thisProp.part, ref rpmComp); activeColor = JUtil.ParseColor32(node.GetValue("activeColor"), thisProp.part, ref rpmComp); } Renderer colorShiftRenderer = thisProp.FindModelComponent<Renderer>(node.GetValue("coloredObject")); affectedMaterial = colorShiftRenderer.material; affectedMaterial.SetColor(colorName, 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; if (reverse) { vectorEnd = ConfigNode.ParseVector3(node.GetValue("localRotationStart")); vectorStart = ConfigNode.ParseVector3(node.GetValue("localRotationEnd")); } else { vectorStart = ConfigNode.ParseVector3(node.GetValue("localRotationStart")); vectorEnd = ConfigNode.ParseVector3(node.GetValue("localRotationEnd")); } } else { if (reverse) { rotationEnd = Quaternion.Euler(ConfigNode.ParseVector3(node.GetValue("localRotationStart"))); rotationStart = Quaternion.Euler(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; if (reverse) { vectorEnd = ConfigNode.ParseVector3(node.GetValue("localTranslationStart")); vectorStart = ConfigNode.ParseVector3(node.GetValue("localTranslationEnd")); } else { 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; if (reverse) { vectorEnd = ConfigNode.ParseVector3(node.GetValue("localScaleStart")); vectorStart = ConfigNode.ParseVector3(node.GetValue("localScaleEnd")); } else { 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()).GetComponent<Renderer>().material; var textureLayers = node.GetValue("textureLayers").Split(','); for (int i = 0; i < textureLayers.Length; ++i) { textureLayer.Add(textureLayers[i].Trim()); } if (reverse) { textureShiftEnd = ConfigNode.ParseVector2(node.GetValue("textureShiftStart")); textureShiftStart = ConfigNode.ParseVector2(node.GetValue("textureShiftEnd")); } else { 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()).GetComponent<Renderer>().material; var textureLayers = node.GetValue("textureLayers").Split(','); for (int i = 0; i < textureLayers.Length; ++i) { textureLayer.Add(textureLayers[i].Trim()); } if (reverse) { textureScaleEnd = ConfigNode.ParseVector2(node.GetValue("textureScaleStart")); textureScaleStart = ConfigNode.ParseVector2(node.GetValue("textureScaleEnd")); } else { 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("maxRateChange") && float.TryParse(node.GetValue("maxRateChange"), out maxRateChange))) { maxRateChange = 0.0f; } if (maxRateChange >= 60.0f) { // Animation rate is too fast to even notice @60Hz maxRateChange = 0.0f; } else { lastAnimUpdate = Planetarium.GetUniversalTime(); } 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; } inIVA = (CameraManager.Instance.currentCameraMode == CameraManager.CameraMode.IVA); GameEvents.OnCameraChange.Add(OnCameraChange); } if (node.HasValue("resourceAmount")) { resourceAmount = float.Parse(node.GetValue("resourceAmount")); if (node.HasValue("resourceName")) { resourceName = node.GetValue("resourceName"); } else { resourceName = "ElectricCharge"; } } TurnOff(Planetarium.GetUniversalTime()); } rpmComp.RegisterVariableCallback(variable.variableName, onChangeDelegate); }
public void Start() { rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true); lastOrientation = navBall.rotation; if (string.IsNullOrEmpty(variableName) || string.IsNullOrEmpty(range)) { JUtil.LogErrorMessage(this, "variableName or range was null!"); return; } string[] tokens = range.Split(','); if (tokens.Length != 2) { JUtil.LogErrorMessage(this, "range '{0}' did not have exactly two values!", range); return; } enablingVariable = new VariableOrNumberRange(rpmComp, variableName, tokens[0], tokens[1]); }
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 void Start() { if (HighLogic.LoadedSceneIsEditor) { return; } try { rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true); if (!string.IsNullOrEmpty(odometerMode) && modeList.ContainsKey(odometerMode)) { oMode = modeList[odometerMode]; } //else if (!string.IsNullOrEmpty(odometerMode)) { // JUtil.LogMessage(this, "found odometerMode {0}, but it's not in the dictionary", odometerMode); //} //else { // JUtil.LogMessage(this, "Did not find odometerMode"); //} if (string.IsNullOrEmpty(characterTexture) && oMode == OdometerMode.SI) { JUtil.LogErrorMessage(this, "Prop configured as SI scaled, but there is no characterTexture"); return; } if (string.IsNullOrEmpty(digitTexture)) { // We can't do anything without the digit texture JUtil.LogErrorMessage(this, "Prop can not function without a digitTexture"); return; } digitTex = GameDatabase.Instance.GetTexture(digitTexture.EnforceSlashes(), false); if (digitTex == null) { JUtil.LogErrorMessage(this, "Failed to load digitTexture {0}", digitTexture); return; } if (!string.IsNullOrEmpty(characterTexture)) { characterTex = GameDatabase.Instance.GetTexture(characterTexture.EnforceSlashes(), false); if (characterTex == null) { JUtil.LogErrorMessage(this, "Failed to load characterTexture {0}", characterTexture); return; } } if (!string.IsNullOrEmpty(overlayTexture)) { overlayTex = GameDatabase.Instance.GetTexture(overlayTexture.EnforceSlashes(), false); if (overlayTex == null) { JUtil.LogErrorMessage(this, "Failed to load overlayTexture {0}", overlayTexture); return; } } if (string.IsNullOrEmpty(altVariable) != string.IsNullOrEmpty(perPodPersistenceName)) { JUtil.LogErrorMessage(this, "Both altVariable and perPodPeristenceName must be defined, or neither"); return; } // MOARdV: Which one are we using? HUD uses the latter, OrbitDisplay, the former. Shader unlit = Shader.Find("KSP/Alpha/Unlit Transparent"); //Shader unlit = Shader.Find("Hidden/Internal-GUITexture"); digitMaterial = new Material(unlit); backgroundColorValue = ConfigNode.ParseColor32(backgroundColor); lastUpdate = Planetarium.GetUniversalTime(); screenTexture = new RenderTexture(screenPixelWidth, screenPixelHeight, 24, RenderTextureFormat.ARGB32); screenMat = internalProp.FindModelTransform(screenTransform).GetComponent<Renderer>().material; foreach (string layerID in textureLayerID.Split()) { screenMat.SetTexture(layerID.Trim(), screenTexture); } startupComplete = true; } catch { JUtil.AnnoyUser(this); throw; } }
public object Evaluate(RasterPropMonitorComputer comp) { double result = comp.ProcessVariable(name, -1).MassageToDouble(); bool returnResult = (result >= minValue && result <= maxValue); //JUtil.LogMessage(this, "Evaluate {0} ({3}, {4}) = {1}, returning {2}", name, result, returnResult, minValue, maxValue); return (reverse) ? !returnResult : returnResult; }
// Some things need to be explicitly destroyed due to Unity quirks. internal void TearDown(RasterPropMonitorComputer rpmComp) { //--- new ways if (onChangeDelegate != null) { rpmComp.UnregisterVariableCallback(variable.variableName, onChangeDelegate); } if (audioOutput != null) { GameEvents.OnCameraChange.Remove(OnCameraChange); } //--- if (affectedMaterial != null) { UnityEngine.Object.Destroy(affectedMaterial); affectedMaterial = null; } textureLayer = null; controlledTransform = null; part = null; }
public void Start() { if (HighLogic.LoadedSceneIsEditor) return; try { backgroundColorValue = ConfigNode.ParseColor32(backgroundColor); Shader unlit = Shader.Find("Hidden/Internal-GUITexture"); ladderMaterial = new Material(unlit); ladderMaterial.color = new Color(0.5f, 0.5f, 0.5f, 1.0f); if (!String.IsNullOrEmpty(horizonTexture)) { ladderMaterial.mainTexture = GameDatabase.Instance.GetTexture(horizonTexture.EnforceSlashes(), false); if (ladderMaterial.mainTexture != null) { horizonTextureSize.x = horizonTextureSize.x / ladderMaterial.mainTexture.width; ladderMaterial.mainTexture.wrapMode = TextureWrapMode.Clamp; } } if (!String.IsNullOrEmpty(headingBar)) { headingMaterial = new Material(unlit); headingMaterial.color = new Color(0.5f, 0.5f, 0.5f, 1.0f); headingMaterial.mainTexture = GameDatabase.Instance.GetTexture(headingBar.EnforceSlashes(), false); } if (!String.IsNullOrEmpty(staticOverlay)) { overlayMaterial = new Material(unlit); overlayMaterial.color = new Color(0.5f, 0.5f, 0.5f, 1.0f); overlayMaterial.mainTexture = GameDatabase.Instance.GetTexture(staticOverlay.EnforceSlashes(), false); } if (!String.IsNullOrEmpty(vertBar1Texture) && !String.IsNullOrEmpty(vertBar1Variable)) { vertBar1Material = new Material(unlit); vertBar1Material.color = new Color(0.5f, 0.5f, 0.5f, 1.0f); vertBar1Material.mainTexture = GameDatabase.Instance.GetTexture(vertBar1Texture.EnforceSlashes(), false); if (vertBar1Material.mainTexture != null) { float height = (float)vertBar1Material.mainTexture.height; vertBar1TextureLimit.x = 1.0f - (vertBar1TextureLimit.x / height); vertBar1TextureLimit.y = 1.0f - (vertBar1TextureLimit.y / height); vertBar1TextureSize = 0.5f * (vertBar1TextureSize / height); vertBar1Material.mainTexture.wrapMode = TextureWrapMode.Clamp; } } if (!String.IsNullOrEmpty(vertBar2Texture) && !String.IsNullOrEmpty(vertBar2Variable)) { vertBar2Material = new Material(unlit); vertBar2Material.color = new Color(0.5f, 0.5f, 0.5f, 1.0f); vertBar2Material.mainTexture = GameDatabase.Instance.GetTexture(vertBar2Texture.EnforceSlashes(), false); if (vertBar2Material.mainTexture != null) { float height = (float)vertBar2Material.mainTexture.height; vertBar2TextureLimit.x = 1.0f - (vertBar2TextureLimit.x / height); vertBar2TextureLimit.y = 1.0f - (vertBar2TextureLimit.y / height); vertBar2TextureSize = 0.5f * (vertBar2TextureSize / height); vertBar2Material.mainTexture.wrapMode = TextureWrapMode.Clamp; } } if (vertBar1UseLog10) { vertBar1Limit.x = JUtil.PseudoLog10(vertBar1Limit.x); vertBar1Limit.y = JUtil.PseudoLog10(vertBar1Limit.y); } if (vertBar2UseLog10) { vertBar2Limit.x = JUtil.PseudoLog10(vertBar2Limit.x); vertBar2Limit.y = JUtil.PseudoLog10(vertBar2Limit.y); } if (!string.IsNullOrEmpty(progradeColor)) { progradeColorValue = ConfigNode.ParseColor32(progradeColor); } comp = RasterPropMonitorComputer.Instantiate(internalProp); iconMaterial = new Material(unlit); iconMaterial.color = new Color(0.5f, 0.5f, 0.5f, 1.0f); gizmoTexture = JUtil.GetGizmoTexture(); startupComplete = true; } catch { JUtil.AnnoyUser(this); throw; } }
public void Start() { if (HighLogic.LoadedSceneIsEditor) { return; } try { rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true); useNewMode = RPMGlobals.useNewVariableAnimator; ConfigNode moduleConfig = null; foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP")) { if (node.GetValue("name") == internalProp.propName) { moduleConfig = node.GetNodes("MODULE")[moduleID]; ConfigNode[] variableNodes = moduleConfig.GetNodes("VARIABLESET"); for (int i = 0; i < variableNodes.Length; i++) { try { if (useNewMode) { variableSets.Add(new VariableAnimationSet(variableNodes[i], internalProp, rpmComp, this)); } else { variableSets.Add(new VariableAnimationSet(variableNodes[i], internalProp, rpmComp)); } } catch (ArgumentException e) { JUtil.LogMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID); } } break; } } // Fallback: If there are no VARIABLESET blocks, we treat the module configuration itself as a variableset block. if (variableSets.Count < 1 && moduleConfig != null) { try { if (useNewMode) { variableSets.Add(new VariableAnimationSet(moduleConfig, internalProp, rpmComp, this)); } else { variableSets.Add(new VariableAnimationSet(moduleConfig, internalProp, rpmComp)); } } catch (ArgumentException e) { JUtil.LogMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID); } } JUtil.LogMessage(this, "Configuration complete in prop {1} ({2}), supporting {0} variable indicators.", variableSets.Count, internalProp.propID, internalProp.propName); foreach (VariableAnimationSet thatSet in variableSets) { alwaysActive |= thatSet.alwaysActive; } rpmComp.UpdateDataRefreshRate(refreshRate); startupComplete = true; } catch { JUtil.AnnoyUser(this); enabled = false; throw; } }