public static ResourceUpdateDelegate Instance(PartModule module) { MethodInfo methodInfo = null; var type = module.GetType(); supportedModules.TryGetValue(type, out methodInfo); if (methodInfo != null) { return(new ResourceUpdateDelegate(methodInfo, module)); } if (unsupportedModules.Contains(type)) { return(null); } methodInfo = module.GetType().GetMethod("ResourceUpdate", BindingFlags.Instance | BindingFlags.Public); if (methodInfo == null) { unsupportedModules.Add(type); return(null); } supportedModules[type] = methodInfo; return(new ResourceUpdateDelegate(methodInfo, module)); }
public static bool IsOn(PartModule light) { switch (light.moduleName) { case "ModuleColorChanger": case "ModuleColorChangerConsumer": ModuleColorChanger castMCC = (ModuleColorChanger)light; return(castMCC.animState); case "ModuleLight": case "ModuleStockLightColoredLens": case "ModuleMultiPointSurfaceLight": case "ModuleColoredLensLight": ModuleLight castML = (ModuleLight)light; return(castML.isOn); case "ModuleAnimateGeneric": case "ModuleAnumateGenericConsumer": ModuleAnimateGeneric castMAG = (ModuleAnimateGeneric)light; return(!castMAG.animSwitch); case "WBILight": return((bool)light.GetType().InvokeMember("isDeployed", BindingFlags.GetField, null, light, null)); case "ModuleKELight": return((bool)light.GetType().InvokeMember("isOn", BindingFlags.GetField, null, light, null)); default: return(false); } }
private ConfigNode mergeConfigs(PartModule module, ConfigNode target) { ConfigNode source = new ConfigNode(); source.AddValue("name", module.GetType().Name); System.Reflection.FieldInfo[] fieldInfos = module.GetType().GetFields( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance ); System.Reflection.FieldInfo field; for (int fIdx = 0; fIdx < fieldInfos.Length; fIdx++) { field = fieldInfos[fIdx]; object[] attrs = field.GetCustomAttributes(true); object attr; for (int aIdx = 0; aIdx < attrs.Length; aIdx++) { attr = attrs[aIdx]; if (attr is KSPField) { source.AddValue(field.Name, field.GetValue(module)); break; } } } return(this.mergeConfigs(source, target)); }
private void LoadPartModulesAndFields() { if (!HighLogic.LoadedSceneIsEditor) { return; } _procPartPM = GetProcPartPM(); if (_procPartPM != null) { BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy; _procPartMinVolumeField = _procPartPM.GetType().GetField("volumeMin", flags); _procPartCurShapeProp = _procPartPM.GetType().GetProperty("CurrentShape", flags); } else // is it ROTanks instead? { _roTankPM = GetROTankPM(); } _rfPM = part.Modules.GetModule <ModuleFuelTanks>(); _rfIsDirtyField = typeof(ModuleFuelTanks).GetField("massDirty", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); var fiTanks = typeof(ModuleFuelTanks).GetField("tankList", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); var tankList = (FuelTankList)fiTanks.GetValue(_rfPM); _ecTank = tankList["ElectricCharge"]; _seekVolumeMethod = GetSeekVolumeMethod(); }
private static IRescalable CreateUpdater(PartModule module) { // ReSharper disable once SuspiciousTypeConversion.Global if (module is IRescalable updater) { return(updater); } return(Ctors.ContainsKey(module.GetType()) ? Ctors[module.GetType()](module) : null); }
private static IRescalable createUpdater(PartModule module) { if (module is IRescalable) { return(module as IRescalable); } if (ctors.ContainsKey(module.GetType())) { return(ctors[module.GetType()](module)); } return(null); }
/// <summary>Fixes null persistent fields in the module.</summary> /// <remarks>Used to prevent NREs in methods that persist KSP fields.</remarks> /// <param name="module">Module to fix.</param> public static void CleanupFieldsInModule(PartModule module) { // Ensure the module is awaken. Otherwise, any access to base fields list will result in NRE. // HACK: Accessing Fields property of a non-awaken module triggers NRE. If it happens then do // explicit awakening of the *base* module class. try { var unused = module.Fields.GetEnumerator(); } catch { Logger.logWarning("WORKAROUND. Module {0} on part prefab {1} is not awaken. Call Awake on it", module.GetType(), module.part); AwakePartModule(module); } foreach (var field in module.Fields) { var baseField = field as BaseField; if (baseField.isPersistant && baseField.GetValue(module) == null) { var proto = new StandardOrdinaryTypesProto(); var defValue = proto.ParseFromString("", baseField.FieldInfo.FieldType); Logger.logWarning("WORKAROUND. Found null field {0} in module prefab {1}," + " fixing to default value of type {2}: {3}", baseField.name, module.moduleName, baseField.FieldInfo.FieldType, defValue); baseField.SetValue(defValue, module); } } }
void FindAntenna() { baseAntenna = part.GetComponent <ModuleDataTransmitterFeedeable>(); deployModule = part.GetComponent <ModuleDeployableAntenna>(); if (baseAntenna != null) { baseAntennaRange = baseAntenna.antennaPower; } else { RTAntennaPartModule = part.Modules.Contains("ModuleRTAntenna") ? part.Modules["ModuleRTAntenna"] : null; if (RTAntennaPartModule != null) { try { FieldInfo fi = RTAntennaPartModule.GetType().GetField("Mode1DishRange"); baseAntennaRange = (float)(fi.GetValue(RTAntennaPartModule)); } catch (Exception e) { Debug.LogError("[NearFutureExploration] [ModuleAntennaFeed]: Mismatched RemoteTech antenna module"); } } else { Debug.LogError("[NearFutureExploration] [ModuleAntennaFeed]: Could not find an antenna module for use as feeder"); } } if (deployModule != null) { Debug.Log("[NearFutureExploration] [ModuleAntennaFeed]: Feed is deployable"); deployable = true; } }
private void PurchaseConfig(PartModule pm) { _validationResult = ValidationResult.Rerun; var mi = pm.GetType().GetMethod("ResolveValidationError", BindingFlags.Instance | BindingFlags.Public); mi?.Invoke(pm, new object[] { }); }
void ToggleGear() { List <Part> partsList = EditorLogic.SortedShipList; for (int i = 0; i < partsList.Count; i++) { Part p = partsList[i]; if (p.Modules.Contains <ModuleWheelDeployment>()) { ModuleWheelDeployment l = p.Modules.GetModule <ModuleWheelDeployment>(); l.ActionToggle(new KSPActionParam(KSPActionGroup.Gear, gearToggle ? KSPActionType.Activate : KSPActionType.Deactivate)); } if (p.Modules.Contains("FSwheel")) { PartModule m = p.Modules["FSwheel"]; MethodInfo method = m.GetType().GetMethod("animate", BindingFlags.Instance | BindingFlags.NonPublic); method.Invoke(m, gearToggle ? new object[] { "Deploy" } : new object[] { "Retract" }); } if (p.Modules.Contains("FSBDwheel")) { PartModule m = p.Modules["FSBDwheel"]; MethodInfo method = m.GetType().GetMethod("animate", BindingFlags.Instance | BindingFlags.NonPublic); method.Invoke(m, gearToggle ? new object[] { "Deploy" } : new object[] { "Retract" }); } } gearToggle = !gearToggle; }
List <Propellant> GetEnginePropellants(PartModule engine) { string typename = engine.GetType().ToString(); if (typename.Equals("ModuleEnginesFX")) { ModuleEnginesFX e = (ModuleEnginesFX)engine; return(e.propellants); } else if (typename.Equals("ModuleEngines")) { ModuleEngines e = (ModuleEngines)engine; return(e.propellants); } else if (typename.Equals("ModuleRCSFX")) { ModuleRCS e = (ModuleRCS)engine; return(e.propellants); } else if (typename.Equals("ModuleRCS")) { ModuleRCS e = (ModuleRCS)engine; return(e.propellants); } return(null); }
public IntegratedIntakeEngineCrossSectionAdjuster(PartModule intake, Matrix4x4 worldToVesselMatrix) { this.part = intake.part; //ModuleResourceIntake intake = intake; Type intakeType = intake.GetType(); intakeTrans = (Transform)intakeType.GetField("intakeTransform", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(intake); vehicleBasisForwardVector = Vector3.forward;//intakeTrans.forward; if (intakeTrans == null) intakeTrans = intake.part.partTransform; foreach (AttachNode node in part.attachNodes) if(node.nodeType == AttachNode.NodeType.Stack && Vector3.Dot(node.position, (part.transform.worldToLocalMatrix * intakeTrans.localToWorldMatrix).MultiplyVector(Vector3.forward)) > 0) { frontNode = node; break; } thisToVesselMatrix = worldToVesselMatrix * intakeTrans.localToWorldMatrix; vehicleBasisForwardVector = thisToVesselMatrix.MultiplyVector(vehicleBasisForwardVector); intakeArea = (float)intakeType.GetField("Area").GetValue(intake); }
public void SetupCollider() { baked = new Mesh(); wingSMR.BakeMesh(baked); wingSMR.enabled = false; Transform modelTransform = transform.FindChild("model"); if (modelTransform.GetComponent <MeshCollider>() == null) { modelTransform.gameObject.AddComponent <MeshCollider>(); } MeshCollider meshCol = modelTransform.GetComponent <MeshCollider>(); meshCol.sharedMesh = null; meshCol.sharedMesh = baked; meshCol.convex = true; if (FARactive) { CalculateAerodynamicValues(false); PartModule FARmodule = null; if (part.Modules.Contains("FARControllableSurface")) { FARmodule = part.Modules["FARControllableSurface"]; } else if (part.Modules.Contains("FARWingAerodynamicModel")) { FARmodule = part.Modules["FARWingAerodynamicModel"]; } if (FARmodule != null) { Type FARtype = FARmodule.GetType(); FARtype.GetMethod("TriggerPartColliderUpdate").Invoke(FARmodule, null); } } }
static public void CheckPartForModules(string modName, AvailablePart part) { foreach (PartModule module in part.partPrefab.Modules) { var a = module.GetType(); string fullName = module.moduleName; if (fullName == null) { Log.Error(string.Format("{0} has a null moduleName, skipping it", part.name)); continue; } string usefulModuleName = UsefulModuleName(fullName); //Module mod = new Module(modName, usefulModuleName, a); Module mod = new Module(modName, fullName, a); mod.module = module; if (!ActiveLists.activeModuleList.ContainsKey(mod.ActiveKey)) { // Needs to do another "new" here to have a unique entry inthe commonModulesList mod = new Module(modName, fullName, a); ActiveLists.activeModuleList.Add(mod.ActiveKey, mod); } } }
private void FindAnimStatesInModule(Animation[] animations, PartModule m, string fieldName) { if (FARAnimOverrides.FieldNameForModule(m.moduleName) == fieldName) { return; } FieldInfo field = m.GetType().GetField(fieldName); if (field != null) //This handles stock and Firespitter deployment animations { string animationName = (string)field.GetValue(m); for (int i = 0; i < animations.Length; ++i) { Animation anim = animations[i]; if (anim != null) { AnimationState state = anim[animationName]; if (state) { animStates.Add(state); animStateTime.Add(state.time); } } } } }
public override void OnSave(ConfigNode node) { //Debug.Log("[MUMSF] save for " + moduleName + "." + fieldName); // get the module PartModule mod = part.Modules[moduleName]; if (mod != null) { //Debug.Log("[MUMSF] mod finded"); //set the field try { FieldInfo field = mod.GetType().GetField(fieldName); if (field != null && field.IsDefined(typeof(KSPField), true)) { //Debug.Log("[MUMSF] field finded, value is "+field.GetValue(mod)); node.AddValue(fieldName, field.GetValue(mod)); } } catch (Exception e) { Debug.LogError("[MUMSF] Error: " + e); } } }
private void editModuleByNameFromConfig(Part evaPart, string matchName, ConfigNode config) { PartModule module = this.matchFirstModuleByName(evaPart, matchName); if (module != null) { if (config.HasValue("name")) { config = this.mergeConfigs(module, config); GameObject.Destroy(module); this.LogDebug("EVA module {0} marked for destruction.", module.GetType().Name); ConfigAction copyAction = new ConfigAction(empty, MODULE, empty, config); this.passQueue.Add(copyAction); Logging.PostDebugMessage( this, "EVA module {0} marked for insertion\n(action: {1})", config.GetValue("name"), copyAction ); } else { this.assignFieldsFromConfig(module, config); } } }
public IntegratedIntakeEngineCrossSectionAdjuster(PartModule intake, Matrix4x4 worldToVesselMatrix) { this.part = intake.part; //ModuleResourceIntake intake = intake; Type intakeType = intake.GetType(); intakeTrans = (Transform)intakeType.GetField("intakeTransform", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(intake); vehicleBasisForwardVector = Vector3.forward;//intakeTrans.forward; foreach (AttachNode node in part.attachNodes) { if (node.nodeType == AttachNode.NodeType.Stack && Vector3.Dot(node.position, (part.transform.worldToLocalMatrix * intakeTrans.localToWorldMatrix).MultiplyVector(Vector3.forward)) > 0) { frontNode = node; break; } } thisToVesselMatrix = worldToVesselMatrix * intakeTrans.localToWorldMatrix; vehicleBasisForwardVector = thisToVesselMatrix.MultiplyVector(vehicleBasisForwardVector); intakeArea = (float)intakeType.GetField("Area").GetValue(intake); }
private void UpdateMftModule() { try { if (_prefabPart.Modules.Contains("ModuleFuelTanks")) { scaleMass = false; PartModule m = _prefabPart.Modules["ModuleFuelTanks"]; FieldInfo fieldInfo = m.GetType().GetField("totalVolume", BindingFlags.Public | BindingFlags.Instance); if (fieldInfo != null) { double oldVol = (double)fieldInfo.GetValue(m) * 0.001d; BaseEventDetails data = new BaseEventDetails(BaseEventDetails.Sender.USER); data.Set <string>("volName", "Tankage"); data.Set <double>("newTotalVolume", oldVol * ScalingFactor.absolute.cubic); part.SendEvent("OnPartVolumeChanged", data, 0); } else { Log.warn("MFT interaction failed (fieldinfo=null)"); } } } catch (Exception e) { Log.warn("Exception during MFT interaction" + e.ToString()); } }
private void FindAnimStatesInModule(Animation[] animations, PartModule m, string fieldName) { if (FARAnimOverrides.FieldNameForModule(m.moduleName) == fieldName) { return; } FieldInfo field = m.GetType().GetField(fieldName); if (field == null) { return; } //This handles stock and Firespitter deployment animations string animationName = (string)field.GetValue(m); foreach (Animation anim in animations) { if (anim == null) { continue; } AnimationState state = anim[animationName]; if (!state) { continue; } animStates.Add(state); animStateTime.Add(state.time); } }
void ToggleGear() { List <Part> partsList = EditorLogic.SortedShipList; for (int i = 0; i < partsList.Count; i++) { Part p = partsList[i]; if (p.Modules.Contains("ModuleLandingGear")) { ModuleLandingGear l = (ModuleLandingGear)p.Modules["ModuleLandingGear"]; l.StartDeployed = gearToggle; } if (p.Modules.Contains("ModuleAdvancedLandingGear")) { ModuleAdvancedLandingGear l = (ModuleAdvancedLandingGear)p.Modules["ModuleAdvancedLandingGear"]; l.startDeployed = gearToggle; } if (p.Modules.Contains("FSwheel")) { PartModule m = p.Modules["FSwheel"]; MethodInfo method = m.GetType().GetMethod("animate", BindingFlags.Instance | BindingFlags.NonPublic); method.Invoke(m, gearToggle ? new object[] { "Deploy" } : new object[] { "Retract" }); } if (p.Modules.Contains("FSBDwheel")) { PartModule m = p.Modules["FSBDwheel"]; MethodInfo method = m.GetType().GetMethod("animate", BindingFlags.Instance | BindingFlags.NonPublic); method.Invoke(m, gearToggle ? new object[] { "Deploy" } : new object[] { "Retract" }); } } gearToggle = !gearToggle; }
public void SetupAdjuster(PartModule intake, Matrix4x4 worldToVesselMatrix) { this.part = intake.part; intakeModule = intake as ModuleResourceIntake; intakeTrans = intakeModule.intakeTransform; //ModuleResourceIntake intake = intake; /*vehicleBasisForwardVector = Vector3.forward;//intakeTrans.forward; * * foreach(AttachNode node in part.attachNodes) * if(node.nodeType == AttachNode.NodeType.Stack && Vector3.Dot(node.position, (part.transform.worldToLocalMatrix * intakeTrans.localToWorldMatrix).MultiplyVector(Vector3.forward)) > 0) * { * frontNode = node; * break; * }*/ thisToVesselMatrix = worldToVesselMatrix * intakeTrans.localToWorldMatrix; vehicleBasisForwardVector = Vector3.forward; vehicleBasisForwardVector = thisToVesselMatrix.MultiplyVector(vehicleBasisForwardVector); Type intakeType = intake.GetType(); intakeArea = (float)intakeType.GetField("Area").GetValue(intake); }
public static bool GearDeployed(Part gear) { if (gear != null) { // landing gear contains ModuleWheelDeployment too, so check ModuleWheelBrakes try { if (gear.Modules.Contains <ModuleWheelDeployment>() && gear.Modules.Contains <ModuleWheelBrakes>()) { ModuleWheelDeployment m = gear.Modules.GetModule <ModuleWheelDeployment>(); if (m.stateString != null && m.stateString != "" && m.stateString != "Deployed") // sometimes it's an empty string { return(false); // not down } } } catch (Exception) { } // FSwheel try { if (gear.Modules.Contains("FSwheel")) { PartModule m = gear.Modules["FSwheel"]; if (m.GetType().GetField("deploymentState").GetValue(m).ToString() != "Deployed") { return(false); // not down } } } catch (Exception) { } } return(true); }
public static BackgroundDelegate Instance(PartModule module_prefab) { BackgroundDelegate result = null; var type = module_prefab.GetType(); supportedModules.TryGetValue(type, out result); if (result != null) { return(result); } if (unsupportedModules.Contains(type)) { return(null); } MethodInfo methodInfo = type.GetMethod("BackgroundUpdate", signature); if (methodInfo == null) { unsupportedModules.Add(type); return(null); } result = new BackgroundDelegate(methodInfo); supportedModules[type] = result; return(result); }
private bool IsModuleKerbalismAware(PartModule m) { if (m is IKerbalismModule) { return(true); } if (apiDelegates.ContainsKey(m.moduleName)) { return(true); } if (unsupportedModules.Contains(m.moduleName)) { return(false); } MethodInfo methodInfo = m.GetType().GetMethod("PlannerUpdate", plannerMethodSignature); if (methodInfo == null) { unsupportedModules.Add(m.moduleName); return(false); } apiDelegates[m.moduleName] = new PlannerDelegate(methodInfo); return(true); }
/// <summary> /// Parse a static expression thus: /// /// static(fieldname) /// </summary> /// <param name="module"></param> /// <param name="parameters"></param> /// <returns></returns> private static double TryParseField(PartModule module, ParsedParameters parameters) { if (parameters.Identifier != "static") { return(double.NaN); } parameters.RequireCount(module, 1); string fieldName = parameters[0]; FieldInfo field = module.GetType().GetField( fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (object.ReferenceEquals(field, null)) { throw new ArgumentException("Unknown static field '" + fieldName + "' on " + module.ClassName + " of " + module.part.GetTitle()); } if (StaticField.Is(field)) { return((double)field.GetValue(module)); } else { throw new ArgumentOutOfRangeException("Field '" + fieldName + "' on " + module.ClassName + " of " + module.part.GetTitle() + " is not a static field"); } }
public override void OnStart(StartState state) { if (ferramEnabled) { // Do Ferrem stuff // isn't legacy not even stilln't today but not used? //if (part.Modules.Contains("FARControllableSurface")) { // ferramModule = part.Modules["FARControllableSurface"]; //} else if (part.Modules.Contains("FARWingAerodynamicModel")) { // ferramModule = part.Modules["FARWingAerodynamicModel"]; //} if (part.Modules.Contains("FARAeroPartModule")) { ferramModule = part.Modules ["FARAeroPartModule"]; ferramField = ferramModule.GetType().GetField("worldSpaceAeroForce"); } else { print("FAR module not found"); Destroy(this); return; } //foreach (PartModule pm in part.Modules) { // print ("module: " + pm.ClassName); //} //print ("farrem module: " + ferramModule); print("Ground effect module loaded with FAR"); return; } else { // Look through the list of part modules to find anything that inherits ModuleLiftingSurface foreach (PartModule module in part.Modules) { if (typeof(ModuleLiftingSurface).IsAssignableFrom(module.GetType())) { thingThatLiftsParts = (ModuleLiftingSurface)(module); initialLift = thingThatLiftsParts.deflectionLiftCoeff; if (module is ModuleControlSurface) { //print ("SURFAAAACE!"); thingThatAlsoLiftsPartsButMoves = (ModuleControlSurface)(module); initialLiftCtrl = thingThatAlsoLiftsPartsButMoves.ctrlSurfaceArea; } print("Ground effect module loaded"); return; } } // This means there's a module manager error? } print("Ground effect module loaded for non-aero part?"); Destroy(this); }
private static void releaseWinchReel(PartModule winch, bool releaseState) { FieldInfo releaseField = winch.GetType().GetField("release"); object release = releaseField.GetValue(winch); FieldInfo activeField = release.GetType().GetField("active"); activeField.SetValue(release, releaseState); }
/// <summary>Reads custom type fields from the part's config.</summary> /// <remarks> /// <para> /// The consumer code must call this method from the <c>OnLoad</c> method to capture the /// PartLoader initalization. This method automatically detects the game loading phase, so it's /// safe to call it in every <c>OnLoad</c> inovacation. /// </para> /// </remarks> /// <param name="module">The module to load the data for.</param> /// <param name="cfgNode">The config node, passed by the game to the module.</param> /// <seealso cref="PersistentFieldAttribute"/> /// <seealso cref="StdPersistentGroups.PartConfigLoadGroup"/> /// <seealso cref="CopyPartConfigFromPrefab"/> /// <example> /// <code source="Examples/ConfigUtils/ConfigAccessor-Examples.cs" region="ReadPartConfigExample"/> /// </example> public static void ReadPartConfig(PartModule module, ConfigNode cfgNode) { if (!PartLoader.Instance.IsReady()) { ConfigAccessor.ReadFieldsFromNode( cfgNode, module.GetType(), module, group: StdPersistentGroups.PartConfigLoadGroup); } }
public static void DeployChute(PartModule p) { float currMinPressure = GetReflectionField <float>(p, "minAirPressureToOpen"); SetReflectionField <float>(p, "minAirPressureToOpen", 0.0f); p.GetType().GetMethod("ActivateRC").Invoke(p, null); SetReflectionField <float>(p, "minAirPressureToOpen", currMinPressure); }
/// <summary>Makes a call to <c>Awake()</c> method of the part module.</summary> /// <remarks>Modules added to prefab via <c>AddModule()</c> call are not get activated as they /// would if activated by the Unity core. As a result some vital fields may be left uninitialized /// which may result in an NRE later when working with the prefab (e.g. making a part snapshot). /// This method finds and invokes method <c>Awake</c> via reflection which is normally done by /// Unity. /// <para><b>IMPORTANT!</b> This method cannot awake a module! To make the things right every /// class in the hierarchy should get its <c>Awake</c> called. This method only calls <c>Awake</c> /// method on <c>PartModule</c> parent class which is not enough to do a complete awakening. /// </para> /// <para>This is a HACK since <c>Awake()</c> method is not supposed to be called by anyone but /// Unity. For now it works fine but one day it may awake the kraken.</para> /// </remarks> /// <param name="module">Module instance to awake.</param> public static void AwakePartModule(PartModule module) { // Private method can only be accessed via reflection when requested on the class that declares // it. So, don't use type of the argument and specify it explicitly. var moduleAwakeMethod = typeof(PartModule).GetMethod( "Awake", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (moduleAwakeMethod != null) { moduleAwakeMethod.Invoke(module, new object[] {}); } else { Logger.logError("Cannot find Awake() method on {0}. Skip awakening of component: {1}", module.GetType(), module.GetType()); } }
public static ScienceExperimentFields Construct(PartModule mod, SharedObjects shared) { var typeName = mod.GetType().Name; var baseTypeName = mod.GetType().BaseType.Name; if (baseTypeName.Contains(DMBASICSCIENCEMODULE) || typeName.Contains(DMASTEROIDSCANNER)) { return new DMScienceExperimentFields(mod, shared); } else if (typeName.Contains(DMBATHYMETRY)) { return new DMBathymetryFields(mod as ModuleScienceExperiment, shared); } else if (typeName.Contains(DMSCIENCEANIMATE) || baseTypeName.Contains(DMSCIENCEANIMATE)) { return new DMModuleScienceAnimateFields(mod as ModuleScienceExperiment, shared); } return null; }
public override void OnStart(PartModule.StartState state) { if (state != PartModule.StartState.Editor) { anims = part.FindModelAnimators(animationName); if ((anims == null) || (anims.Length == 0)) { print("ModuleAnimation2Value - animation not found: " + animationName); } moduleType = part.GetType(); if (valueModule != "") { if (part.Modules.Contains(valueModule)) { module = part.Modules[valueModule]; moduleType = module.GetType(); } else { print("ModuleAnimation2Value - module not found: " + valueModule); } } field = moduleType.GetField(valueName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic); if (field == null) { property = moduleType.GetProperty(valueName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic); if (property == null) { print("ModuleAnimation2Value - field/property not found: " + valueName); } } if ((anims != null) && (anims.Length > 0) && ((field != null) || (property != null))) { // Check to see if our part contains the Firespitter module FSwheel if (part.Modules.Contains("FSwheel")) { FSwheel = part.Modules["FSwheel"]; if (FSwheel != null) fswType = FSwheel.GetType (); // Check to see if our animation is the same as the one used by FSwheel if (animationName == (string)fswType.GetField ("animationName").GetValue (FSwheel)) fswHack = true; } } } base.OnStart(state); }
public override void OnStart(PartModule.StartState state) { if (state != PartModule.StartState.Editor) { anims = part.FindModelAnimators(animationName); if ((anims == null) || (anims.Length == 0)) { print("ModuleAnimation2Value - animation not found: " + animationName); } moduleType = part.GetType(); if (valueModule != "") { if (part.Modules.Contains(valueModule)) { module = part.Modules[valueModule]; moduleType = module.GetType(); } else { print("ModuleAnimation2Value - module not found: " + valueModule); } } field = moduleType.GetField(valueName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic); if (field == null) { property = moduleType.GetProperty(valueName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic); if (property == null) { print("ModuleAnimation2Value - field/property not found: " + valueName); } } } base.OnStart(state); }
private static IRescalable createUpdater(PartModule module) { if (module is IRescalable) { return module as IRescalable; } if (ctors.ContainsKey(module.GetType())) { return ctors[module.GetType()](module); } return null; }
public virtual void SetConfiguration(string newConfiguration = null) { if (newConfiguration == null) newConfiguration = configuration; ConfigNode newConfig = configs.Find (c => c.GetValue ("name").Equals (newConfiguration)); if (newConfig != null) { // for asmi if (useConfigAsTitle) part.partInfo.title = configuration; configuration = newConfiguration; config = new ConfigNode ("MODULE"); newConfig.CopyTo (config); config.name = "MODULE"; // fix for HotRockets etc. if (type.Equals("ModuleEngines") && part.Modules.Contains("ModuleEnginesFX") && !part.Modules.Contains("ModuleEngines")) type = "ModuleEnginesFX"; if (type.Equals("ModuleEnginesFX") && part.Modules.Contains("ModuleEngines") && !part.Modules.Contains("ModuleEnginesFX")) type = "ModuleEngines"; // fix for ModuleRCSFX etc if (type.Equals("ModuleRCS") && part.Modules.Contains("ModuleRCSFX") && !part.Modules.Contains("ModuleRCS")) type = "ModuleRCSFX"; if (type.Equals("ModuleRCSFX") && part.Modules.Contains("ModuleRCS") && !part.Modules.Contains("ModuleRCSFX")) type = "ModuleRCS"; config.SetValue("name", type); #if DEBUG print ("replacing " + type + " with:"); print (newConfig.ToString ()); #endif pModule = null; if (part.Modules.Contains(type)) { pModule = part.Modules[type]; // clear all FloatCurves Type mType = pModule.GetType(); foreach (FieldInfo field in mType.GetFields()) { if (field.FieldType == typeof(FloatCurve) && (field.Name.Equals("atmosphereCurve") || field.Name.Equals("velocityCurve"))) { //print("*MFS* resetting curve " + field.Name); field.SetValue(pModule, new FloatCurve()); } } // clear propellant gauges foreach (FieldInfo field in mType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)) { if (field.FieldType == typeof(Dictionary<Propellant, VInfoBox>)) { Dictionary<Propellant, VInfoBox> boxes = (Dictionary<Propellant, VInfoBox>)(field.GetValue(pModule)); if (boxes == null) continue; foreach (VInfoBox v in boxes.Values) { if (v == null) //just in case... continue; try { part.stackIcon.RemoveInfo(v); } catch (Exception e) { print("*MFS* Trying to remove info box: " + e.Message); } } boxes.Clear(); } } } if (type.Equals("ModuleRCS") || type.Equals("ModuleRCSFX")) { ModuleRCS rcs = (ModuleRCS)pModule; if (rcs != null) { rcs.G = 9.80665f; /*bool oldRes = config.HasValue("resourceName"); string resource = ""; if (oldRes) { resource = config.GetValue("resourceName"); rcs.resourceName = resource; }*/ DoConfig(config); if (config.HasNode("PROPELLANT")) { rcs.propellants.Clear(); } pModule.Load(config); /*if (oldRes) { rcs.resourceName = resource; rcs.SetResource(resource); }*/ // PROPELLANT handling is automatic. fastRCS = rcs; if(type.Equals("ModuleRCS") && !part.Modules.Contains("ModuleRCSFX")) fastType = ModuleType.MODULERCS; else fastType = ModuleType.MODULERCSFX; } } else { // is an ENGINE if (type.Equals("ModuleEngines")) { ModuleEngines mE = (ModuleEngines)pModule; if (mE != null) { configMaxThrust = mE.maxThrust; configMinThrust = mE.minThrust; fastEngines = mE; fastType = ModuleType.MODULEENGINES; mE.g = 9.80665f; if (config.HasNode("PROPELLANT")) { mE.propellants.Clear(); } } if (config.HasValue("maxThrust")) { float thr; if(float.TryParse(config.GetValue("maxThrust"), out thr)) configMaxThrust = thr; } if (config.HasValue("minThrust")) { float thr; if(float.TryParse(config.GetValue("minThrust"), out thr)) configMinThrust = thr; } } else if (type.Equals("ModuleEnginesFX")) { ModuleEnginesFX mE = (ModuleEnginesFX)pModule; if (mE != null) { configMaxThrust = mE.maxThrust; configMinThrust = mE.minThrust; fastEnginesFX = mE; fastType = ModuleType.MODULEENGINESFX; mE.g = 9.80665f; if (config.HasNode("PROPELLANT")) { mE.propellants.Clear(); } } if (config.HasValue("maxThrust")) { float thr; if (float.TryParse(config.GetValue("maxThrust"), out thr)) configMaxThrust = thr; } if (config.HasValue("minThrust")) { float thr; if (float.TryParse(config.GetValue("minThrust"), out thr)) configMinThrust = thr; } } DoConfig(config); if(pModule != null) pModule.Load (config); if (config.HasNode("ModuleEngineIgnitor") && part.Modules.Contains("ModuleEngineIgnitor")) { ConfigNode eiNode = config.GetNode("ModuleEngineIgnitor"); if (eiNode.HasValue("ignitionsAvailable")) { int ignitions; if (int.TryParse(eiNode.GetValue("ignitionsAvailable"), out ignitions)) { if (ignitions < 0) { ignitions = techLevel + ignitions; if (ignitions < 1) ignitions = 1; } else if (ignitions == 0) ignitions = -1; eiNode.SetValue("ignitionsAvailable", ignitions.ToString()); if (eiNode.HasValue("ignitionsRemained")) eiNode.SetValue("ignitionsRemained", ignitions.ToString()); else eiNode.AddValue("ignitionsRemained", ignitions.ToString()); } } if (!HighLogic.LoadedSceneIsEditor && !(HighLogic.LoadedSceneIsFlight && vessel != null && vessel.situation == Vessel.Situations.PRELAUNCH)) // fix for prelaunch { int remaining = (int)(part.Modules["ModuleEngineIgnitor"].GetType().GetField("ignitionsRemained").GetValue(part.Modules["ModuleEngineIgnitor"])); if(eiNode.HasValue("ignitionsRemained")) eiNode.SetValue("ignitionsRemained", remaining.ToString()); else eiNode.AddValue("ignitionsRemained", remaining.ToString()); } ConfigNode tNode = new ConfigNode("MODULE"); eiNode.CopyTo(tNode); tNode.SetValue("name", "ModuleEngineIgnitor"); part.Modules["ModuleEngineIgnitor"].Load(tNode); } } if (part.Resources.Contains("ElectricCharge") && part.Resources["ElectricCharge"].maxAmount < 0.1) { // hacking around a KSP bug here part.Resources["ElectricCharge"].amount = 0; part.Resources["ElectricCharge"].maxAmount = 0.1; } UpdateTweakableMenu(); // Check for and enable the thrust curve useThrustCurve = false; //Fields["thrustCurveDisplay"].guiActive = true; if (config.HasNode("thrustCurve") && config.HasValue("curveResource")) { curveResource = config.GetValue("curveResource"); if (curveResource != "") { double ratio = 0.0; switch (fastType) { case ModuleType.MODULEENGINES: for (int i = 0; i < fastEngines.propellants.Count; i++ ) if (fastEngines.propellants[i].name.Equals(curveResource)) curveProp = i; if (curveProp >= 0) ratio = fastEngines.propellants[curveProp].totalResourceAvailable / fastEngines.propellants[curveProp].totalResourceCapacity; break; case ModuleType.MODULEENGINESFX: for (int i = 0; i < fastEnginesFX.propellants.Count; i++) if (fastEnginesFX.propellants[i].name.Equals(curveResource)) curveProp = i; if (curveProp >= 0) ratio = fastEnginesFX.propellants[curveProp].totalResourceAvailable / fastEnginesFX.propellants[curveProp].totalResourceCapacity; break; case ModuleType.MODULERCS: for (int i = 0; i < fastRCS.propellants.Count; i++) if (fastRCS.propellants[i].name.Equals(curveResource)) curveProp = i; if (curveProp >= 0) ratio = fastRCS.propellants[curveProp].totalResourceAvailable / fastRCS.propellants[curveProp].totalResourceCapacity; break; } if (curveProp != -1) { useThrustCurve = true; configThrustCurve = new FloatCurve(); configThrustCurve.Load(config.GetNode("thrustCurve")); print("*RF* Found thrust curve for " + part.name + ", current ratio " + ratio + ", curve: " + configThrustCurve.Evaluate((float)ratio)); //Fields["thrustCurveDisplay"].guiActive = true; } } } } }
//return index count of specific partmodule type only, not of entire part.modules list. Used in save routine public static int PartModuleModuleToIndex(PartModule pm, PartModuleList pmList) { try { List<PartModule> pmListThisType = new List<PartModule>(); foreach (PartModule pm2 in pmList) { if (pm2.GetType().Name == pm.GetType().Name) { pmListThisType.Add(pm2); } } return pmListThisType.IndexOf(pm); } catch { Debug.Log("AGX SavePMIndex Fail, using default"); return 0; } }
public virtual void SetConfiguration(string newConfiguration = null, bool resetTechLevels = false) { if (newConfiguration == null) newConfiguration = configuration; ConfigSaveLoad(); ConfigNode newConfig = configs.Find (c => c.GetValue ("name").Equals (newConfiguration)); if (!UnlockedConfig(newConfig, part)) { if(newConfig == null) Debug.Log("*RFMEC* ERROR Can't find configuration " + newConfiguration + ", falling back to first tech-available config."); foreach(ConfigNode cfg in configs) if (UnlockedConfig(cfg, part)) { newConfig = cfg; newConfiguration = cfg.GetValue("name"); break; } } if (newConfig != null) { if (configuration != newConfiguration && resetTechLevels) techLevel = origTechLevel; // for asmi if (useConfigAsTitle) part.partInfo.title = configuration; configuration = newConfiguration; config = new ConfigNode("MODULE"); newConfig.CopyTo(config); config.name = "MODULE"; #if DEBUG print ("replacing " + type + " with:"); print (newConfig.ToString ()); #endif pModule = null; // get correct module pModule = GetSpecifiedModule(part, engineID, moduleIndex, type, useWeakType); if ((object)pModule == null) { Debug.Log("*RFMEC* Could not find appropriate module of type " + type + ", with ID=" + engineID + " and index " + moduleIndex); return; } Type mType = pModule.GetType(); config.SetValue("name", mType.Name); // clear all FloatCurves we need to clear (i.e. if our config has one, or techlevels are enabled) bool delAtmo = config.HasNode("atmosphereCurve") || techLevel >= 0; bool delDens = config.HasNode("atmCurve") || techLevel >= 0; bool delVel = config.HasNode("velCurve") || techLevel >= 0; foreach (FieldInfo field in mType.GetFields()) { if (field.FieldType == typeof(FloatCurve) && ((field.Name.Equals("atmosphereCurve") && delAtmo) || (field.Name.Equals("atmCurve") && delDens) || (field.Name.Equals("velCurve") && delVel))) { field.SetValue(pModule, new FloatCurve()); } } // clear propellant gauges foreach (FieldInfo field in mType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)) { if (field.FieldType == typeof(Dictionary<Propellant, VInfoBox>)) { Dictionary<Propellant, VInfoBox> boxes = (Dictionary<Propellant, VInfoBox>)(field.GetValue(pModule)); if (boxes == null) continue; foreach (VInfoBox v in boxes.Values) { if (v == null) //just in case... continue; try { part.stackIcon.RemoveInfo(v); } catch (Exception e) { Debug.Log("*RFMEC* Trying to remove info box: " + e.Message); } } boxes.Clear(); } } if (type.Equals("ModuleRCS") || type.Equals("ModuleRCSFX")) { ModuleRCS rcs = (ModuleRCS)pModule; if (rcs != null) { DoConfig(config); if (config.HasNode("PROPELLANT")) { rcs.propellants.Clear(); } pModule.Load(config); } } else { // is an ENGINE ModuleEngines mE = (ModuleEngines)pModule; if (mE != null) { if (config.HasNode("PROPELLANT")) { mE.propellants.Clear(); } } DoConfig(config); // Handle Engine Ignitor if (config.HasNode("ModuleEngineIgnitor")) { if (part.Modules.Contains("ModuleEngineIgnitor")) { ConfigNode eiNode = config.GetNode("ModuleEngineIgnitor"); if (eiNode.HasValue("ignitionsAvailable")) { int ignitions; if (int.TryParse(eiNode.GetValue("ignitionsAvailable"), out ignitions)) { ignitions = ConfigIgnitions(ignitions); eiNode.SetValue("ignitionsAvailable", ignitions.ToString()); if (eiNode.HasValue("ignitionsRemained")) eiNode.SetValue("ignitionsRemained", ignitions.ToString()); else eiNode.AddValue("ignitionsRemained", ignitions.ToString()); } } if (!HighLogic.LoadedSceneIsEditor && !(HighLogic.LoadedSceneIsFlight && vessel != null && vessel.situation == Vessel.Situations.PRELAUNCH)) // fix for prelaunch { int remaining = (int)(part.Modules["ModuleEngineIgnitor"].GetType().GetField("ignitionsRemained").GetValue(part.Modules["ModuleEngineIgnitor"])); if (eiNode.HasValue("ignitionsRemained")) eiNode.SetValue("ignitionsRemained", remaining.ToString()); else eiNode.AddValue("ignitionsRemained", remaining.ToString()); } ConfigNode tNode = new ConfigNode("MODULE"); eiNode.CopyTo(tNode); tNode.SetValue("name", "ModuleEngineIgnitor"); part.Modules["ModuleEngineIgnitor"].Load(tNode); } else // backwards compatible with EI nodes when using RF ullage etc. { ConfigNode eiNode = config.GetNode("ModuleEngineIgnitor"); if (eiNode.HasValue("ignitionsAvailable") && !config.HasValue("ignitions")) { config.AddValue("ignitions", eiNode.GetValue("ignitionsAvailable")); } if (eiNode.HasValue("useUllageSimulation") && !config.HasValue("ullage")) config.AddValue("ullage", eiNode.GetValue("useUllageSimulation")); if (eiNode.HasValue("isPressureFed") && !config.HasValue("pressureFed")) config.AddValue("pressureFed", eiNode.GetValue("isPressureFed")); if (!config.HasNode("IGNITOR_RESOURCE")) foreach (ConfigNode resNode in eiNode.GetNodes("IGNITOR_RESOURCE")) config.AddNode(resNode); } } if (config.HasValue("ignitions")) { int ignitions; if ((!HighLogic.LoadedSceneIsFlight || (vessel != null && vessel.situation == Vessel.Situations.PRELAUNCH))) { if (int.TryParse(config.GetValue("ignitions"), out ignitions)) { ignitions = ConfigIgnitions(ignitions); config.SetValue("ignitions", ignitions.ToString()); } } else config.RemoveValue("ignitions"); } if (pModule is ModuleEnginesRF) (pModule as ModuleEnginesRF).SetScale(1d); pModule.Load(config); } // fix for editor NaN if (part.Resources.Contains("ElectricCharge") && part.Resources["ElectricCharge"].maxAmount < 0.1) { // hacking around a KSP bug here part.Resources["ElectricCharge"].amount = 0; part.Resources["ElectricCharge"].maxAmount = 0.1; } // set gimbal if (config.HasValue("gimbalRange")) { float newGimbal = float.Parse(config.GetValue("gimbalRange")); for (int m = 0; m < part.Modules.Count; ++m) { if (part.Modules[m] is ModuleGimbal) { ModuleGimbal g = part.Modules[m] as ModuleGimbal; if (gimbalTransform.Equals("") || g.gimbalTransformName.Equals(gimbalTransform)) { g.gimbalRange = newGimbal; break; } } } } if (config.HasValue("cost")) configCost = scale * float.Parse(config.GetValue("cost")); else configCost = 0f; UpdateOtherModules(config); // GUI disabled for now - UpdateTweakableMenu(); // Finally, fire the modified event // more trouble than it is worth... /*if((object)(EditorLogic.fetch) != null && (object)(EditorLogic.fetch.ship) != null && HighLogic.LoadedSceneIsEditor) GameEvents.onEditorShipModified.Fire(EditorLogic.fetch.ship);*/ // fire config modified event /*if(HighLogic.LoadedSceneIsEditor || HighLogic.LoadedSceneIsFlight) EngineConfigChanged();*/ // do it manually List<Part> parts; if (HighLogic.LoadedSceneIsEditor && EditorLogic.fetch.ship != null) parts = EditorLogic.fetch.ship.parts; else if (HighLogic.LoadedSceneIsFlight && vessel != null) parts = vessel.parts; else parts = new List<Part>(); for (int i = parts.Count - 1; i >= 0; --i) parts[i].SendMessage("UpdateUsedBy"); SetupFX(); UpdateTFInterops(); // update TestFlight if it's installed } else { Debug.Log("*RFMEC* ERROR could not find configuration of name " + configuration + " and could find no fallback config."); Debug.Log("For part " + part.name + ", Current nodes:" + Utilities.PrintConfigs(configs)); } }
//============================================================================================================================================ public void EngageChute() { //FAR Compatibility =) if (assemblyFARUsed == true) { foreach (Part EnabledPart in EnabledPartList) { if (EnabledPart.Modules.Contains ("RealChuteFAR")) { //FerramAerospaceResearch.RealChuteLite.RealChuteFAR RCF = new FerramAerospaceResearch.RealChuteLite.RealChuteFAR (); //RCF = EnabledPart.FindModuleImplementing<FerramAerospaceResearch.RealChuteLite.RealChuteFAR> (); ChuteFARModuleReference = EnabledPart.Modules ["RealChuteFAR"]; PropertyInfo ChuteFARModuleDeploymentState = ChuteFARModuleReference.GetType().GetProperty("deploymentState"); RoboBrakes_ParaEnabledCount++; ChuteFARDeploymentString = ChuteFARModuleReference.Fields.GetValue ("depState").ToString (); //Repack if Chute was already Cut if ((ChuteFARDeploymentString == "CUT") && (IsLanded == false) && (RoboBrakes_CHUTEAUTO == true)) { //Bypassing RealChutes Repacking Method so we don't have to EVA - Also we can't set 'canRepack' bool as it is read only :-/ ChuteFARModuleDeploymentState.SetValue(ChuteFARModuleReference, 1, null); ChuteFARModuleReference.part.Effect ("rcrepack"); ChuteFARModuleReference.part.stackIcon.SetIconColor (XKCDColors.White); ChuteFARModuleReference.part.DragCubes.SetCubeWeight ("PACKED", 1); ChuteFARModuleReference.part.DragCubes.SetCubeWeight ("RCDEPLOYED", 0); print ("ROBOBRAKES - RealChute " + EnabledPart.name + " was already Cut! Repacked Automatically!"); } //Deploy Chute if ((RoboBrakes_CHUTEREADY == true && RoboBrakes_CHUTEAUTO == true)) { RoboBrakes_CHUTEREADY = false; //Deploy Real Chute ChuteFARModuleReference.SendMessage("ActivateRC"); } //Repack Chute Automatically if (ChuteFARDeploymentString == "DEPLOYED" | ChuteFARDeploymentString == "PREDEPLOYED") { if (RoboBrakes_CUTCHUTE == true) { RoboBrakes_CUTCHUTE = false; //Cut Real Chute ChuteFARModuleReference.SendMessage("Cut"); //Bypassing RealChutes Repacking Method so we don't have to EVA - Also we can't set 'canRepack' bool as it is read only :-/ ChuteFARModuleDeploymentState.SetValue(ChuteFARModuleReference, 1, null); ChuteFARModuleReference.part.Effect ("rcrepack"); ChuteFARModuleReference.part.stackIcon.SetIconColor (XKCDColors.White); ChuteFARModuleReference.part.DragCubes.SetCubeWeight ("PACKED", 1); ChuteFARModuleReference.part.DragCubes.SetCubeWeight ("RCDEPLOYED", 0); print ("ROBOBRAKES - RealChute " + EnabledPart.name + " was Cut & Repacked Automatically!"); } } } } } foreach (Part EnabledPart in EnabledPartList) { //Module Parachutes //--------------------------------------------------------------------------------------------------------------------- if (EnabledPart.Modules.Contains ("ModuleParachute")) { ModuleParachute MPA = new ModuleParachute (); MPA = EnabledPart.FindModuleImplementing<ModuleParachute> (); RoboBrakes_ParaEnabledCount++; //Repack the Chute automatically if it has been manually cut if ((MPA.deploymentState.Equals (ModuleParachute.deploymentStates.CUT)) && (IsLanded == false) && (RoboBrakes_CHUTEAUTO == true)) { MPA.Repack (); print ("ROBOBRAKES - Chute " + EnabledPart.name + " was already Cut! Repacked Automatically!"); } //Deploy Chute if ((RoboBrakes_AUTOMATICBRAKE_ACTIVE == true && RoboBrakes_CHUTEAUTO == true)) { if (RoboBrakes_CHUTEREADY == true) { RoboBrakes_CHUTEREADY = false; MPA.Deploy (); } } //Repack Chute if (MPA.deploymentState.Equals (ModuleParachute.deploymentStates.DEPLOYED)) { if (RoboBrakes_CUTCHUTE == true) { RoboBrakes_CUTCHUTE = false; MPA.CutParachute (); MPA.Repack (); print ("ROBOBRAKES - Chute " + EnabledPart.name + " was Cut & Repacked Automatically!"); } } } } }
public static void dumpPartModule(PartModule pm) { AAprint ("pm: " + pm.moduleName); AAprint ("pm.enabled: " + pm.enabled.ToString () + "/" + pm.isEnabled); AAprint ("pm.gettype: " + pm.GetType ().ToString ()); if (pm.moduleName == "CModuleFuelLine") { AAprint ("FUEL LINE!"); CompoundPart cp = (CompoundPart)pm.part; if (cp.target == null) { print ("target is null"); } else { printPart ("target", cp.target); } } }
public IntakeCrossSectionAdjuster(PartModule intake, Matrix4x4 worldToVesselMatrix) { this.part = intake.part; intakeModule = intake as ModuleResourceIntake; intakeTrans = intakeModule.intakeTransform; if (!string.IsNullOrEmpty(intakeModule.occludeNode)) node = intakeModule.node; foreach (AttachNode candidateNode in part.attachNodes) if (candidateNode.nodeType == AttachNode.NodeType.Stack && Vector3.Dot(candidateNode.position, (part.transform.worldToLocalMatrix * intakeTrans.localToWorldMatrix).MultiplyVector(Vector3.forward)) > 0) { if (candidateNode == node) continue; nodeOffsetArea = candidateNode.size; if (nodeOffsetArea == 0) nodeOffsetArea = 0.5; nodeOffsetArea *= 0.625; //scale it up as needed nodeOffsetArea *= nodeOffsetArea; nodeOffsetArea *= Math.PI; //calc area; nodeOffsetArea *= -1; //and the adjustment area break; } thisToVesselMatrix = worldToVesselMatrix * intakeTrans.localToWorldMatrix; vehicleBasisForwardVector = Vector3.forward; vehicleBasisForwardVector = thisToVesselMatrix.MultiplyVector(vehicleBasisForwardVector); Type intakeType = intake.GetType(); intakeArea = (float)intakeType.GetField("Area").GetValue(intake); }
public override void OnAwake() { base.OnAwake(); if (part && part.Modules != null) // thanks, FlowerChild! { is_engine = (part.Modules.Contains("ModuleEngines") || part.Modules.Contains("ModuleEnginesFX")); is_eva = part.Modules.Contains("KerbalEVA"); if (part.Modules.Contains("ModuleParachute")) parachute = (ModuleParachute)part.Modules["ModuleParachute"]; if (part.Modules.Contains("RealChuteModule")) { realChute = part.Modules["RealChuteModule"]; rCType = realChute.GetType(); } } }