Esempio n. 1
0
 private void EvaAddResource(Part part, double rate, string name, bool full)
 {
     try
     {
         double     max          = rate * HighLogic.CurrentGame.Parameters.CustomParams <TAC_SettingsParms_Sec3>().EvaDefaultResourceAmount;
         ConfigNode resourceNode = new ConfigNode("RESOURCE");
         resourceNode.AddValue("name", name);
         resourceNode.AddValue("maxAmount", max);
         if (full)
         {
             resourceNode.AddValue("amount", max);
         }
         else
         {
             resourceNode.AddValue("amount", 0);
         }
         resourceNode.AddValue("isTweakable", false);
         //Check prefab part doesn't have resource already. If it does remove it first, then re-add it.
         if (part.Resources.Contains(name))
         {
             part.Resources.Remove(name);
         }
         PartResource resource = part.AddResource(resourceNode);
         resource.flowState = true;
         resource.flowMode  = PartResource.FlowMode.Both;
     }
     catch (Exception ex)
     {
         if (!ex.Message.Contains("Object reference not set"))
         {
             this.LogError("Unexpected error while adding resource " + name + " to the EVA: " + ex.Message + "\n" + ex.StackTrace);
         }
     }
 }
Esempio n. 2
0
        private void AddResource(Part part, int id, string name, double rate, bool full)
        {
            try
            {
                if (!part.Resources.Contains(id))
                {
                    double     max  = part.CrewCapacity * rate * settings.DefaultResourceAmount;
                    ConfigNode node = new ConfigNode("RESOURCE");
                    node.AddValue("name", name);
                    node.AddValue("maxAmount", max);

                    if (full)
                    {
                        node.AddValue("amount", max);
                    }
                    else
                    {
                        node.AddValue("amount", 0);
                    }

                    part.AddResource(node);
                }
            }
            catch (Exception ex)
            {
                Debug.LogError("TAC Life Support (AddLifeSupport) [" + this.GetInstanceID().ToString("X") + "][" + Time.time
                               + "]: Failed to add resource " + name + " to " + part.name + ": " + ex.Message + "\n" + ex.StackTrace);
            }
        }
Esempio n. 3
0
        private void AddResource(Part part, int id, string name, double rate, bool full)
        {
            try
            {
                if (!part.Resources.Contains(id))
                {
                    double     max  = part.CrewCapacity * rate * globalSettings.DefaultResourceAmount;
                    ConfigNode node = new ConfigNode("RESOURCE");
                    node.AddValue("name", name);
                    node.AddValue("maxAmount", max);

                    if (full)
                    {
                        node.AddValue("amount", max);
                    }
                    else
                    {
                        node.AddValue("amount", 0);
                    }

                    part.AddResource(node);
                }
            }
            catch (Exception ex)
            {
                this.LogError("Failed to add resource " + name + " to " + part.name + ": " + ex.Message + "\n" + ex.StackTrace);
            }
        }
Esempio n. 4
0
 private void EvaAddResource(Part part, double rate, string name, bool full)
 {
     try
     {
         double     max          = rate * TacStartOnce.Instance.globalSettings.EvaDefaultResourceAmount;
         ConfigNode resourceNode = new ConfigNode("RESOURCE");
         resourceNode.AddValue("name", name);
         resourceNode.AddValue("maxAmount", max);
         if (full)
         {
             resourceNode.AddValue("amount", max);
         }
         else
         {
             resourceNode.AddValue("amount", 0);
         }
         resourceNode.AddValue("isTweakable", false);
         PartResource resource = part.AddResource(resourceNode);
         resource.flowState = true;
         resource.flowMode  = PartResource.FlowMode.Both;
     }
     catch (Exception ex)
     {
         if (!ex.Message.Contains("Object reference not set"))
         {
             this.LogError("Unexpected error while adding resource " + name + " to the EVA: " + ex.Message + "\n" + ex.StackTrace);
         }
     }
 }
Esempio n. 5
0
        public void applyToPart(Part part, float modifier, bool keepExistingAmount)
        {
            PartResource pr = part.Resources[name];

            if (pr != null)
            {
                pr.maxAmount = max * modifier;
                if (keepExistingAmount)
                {
                    pr.amount = Math.Min(pr.amount, pr.maxAmount);
                }
                else
                {
                    pr.amount = fill * modifier;
                }
            }
            else
            {
                ConfigNode resourceNode;
                resourceNode = new ConfigNode("RESOURCE");
                resourceNode.AddValue("name", name);
                resourceNode.AddValue("maxAmount", max * modifier);
                resourceNode.AddValue("amount", fill * modifier);
                part.AddResource(resourceNode);
            }
        }
Esempio n. 6
0
        private void onEditorPartPlaced(Part part)
        {
            if (part == null)
            {
                Debug.Log("[Snacks] Nothing to do in onEditorPartPlaced, returning.");
                return;
            }

            try
            {
                //Make sure the crewed part has snacks
                if (part.Resources.Contains(SnacksProperties.SnacksResourceName) == false && part.CrewCapacity >= 1)
                {
                    ConfigNode node   = new ConfigNode("RESOURCE");
                    double     amount = 0;
                    node.AddValue("name", SnacksProperties.SnacksResourceName);
                    if (part.FindModuleImplementing <ModuleCommand>() != null)
                    {
                        amount = SnacksProperties.SnacksPerCommand * part.CrewCapacity;
                    }
                    else
                    {
                        amount = SnacksProperties.SnacksPerCrewModule * part.CrewCapacity;
                    }
                    node.AddValue("amount", amount.ToString());
                    node.AddValue("maxAmount", amount.ToString());
                    part.AddResource(node);
                }
            }
            catch (Exception ex)
            {
                Debug.Log("[Snacks] Encountered an error during onEditorPartPlaced: " + ex);
            }
        }
        // Amount < 0 signifies use existing amount if exists, or create with max amount
        public static PartResource AddOrCreateResource(this Part part, PartResourceDefinition info, float maxAmount, float amount)
        {
            if (amount > maxAmount)
            {
                part.LogWarning($"Cannot add resource '{info.name}' with amount > maxAmount, will use maxAmount (amount = {amount}, maxAmount = {maxAmount})");
                amount = maxAmount;
            }

            PartResource resource = part.Resources[info.name];

            if (resource == null)
            {
                if (amount < 0f)
                {
                    amount = maxAmount;
                }

                resource = part.AddResource(info, maxAmount, amount);
            }
            else
            {
                resource.maxAmount = maxAmount;

                if (amount >= 0f)
                {
                    resource.amount = amount;
                }
            }

            return(resource);
        }
Esempio n. 8
0
        // return maxmass
        public static PartResource addResource(Part p, string name, float amount, float maxAmount)
        {
            ConfigNode newPartResource = new ConfigNode("RESOURCE");

            newPartResource.AddValue("name", name);
            newPartResource.AddValue("amount", amount);
            newPartResource.AddValue("maxAmount", maxAmount);
            return(p.AddResource(newPartResource));
        }
Esempio n. 9
0
        //
        //methods
        //

        public void Enable(ModuleSwitchablePart m)
        {
            //activate profile model objects
            _active = true;

            int count = modelTransforms.Count;

            for (int i = 0; i < count; i++)
            {
                modelTransforms[i].gameObject.SetActive(true);
            }

            int count_1 = resourceList.Count;

            //remove current resources
            part.Resources.Clear();

            //add new resources
            for (int i = 0; i < count_1; i++)
            {
                part.AddResource(resourceList[i]);
            }

            if (mass != 0)
            {
                part.mass = mass;
            }
            else
            {
            }

            if (cost != 0)
            {
                part.partInfo.cost = cost;
            }
            else
            {
            }

            if (desc != string.Empty)
            {
                part.partInfo.description = desc;
            }
            else
            {
            }

            if (dragcube != null)
            {
                part.DragCubes.ClearCubes();
                part.DragCubes.Cubes.Add(dragcube[0]);
                part.DragCubes.ResetCubeWeights();
            }
            else
            {
            }
        }
        void _SetPartResources()
        {
            owner.ClearPartResources();
            Part part = owner.part;

            for (int i = 0; i < tanks.Count; i++)
            {
                var t = tanks[i];
                part.AddResource(t.name, t.amount, t.maxAmount);
            }
            part.ResetSimulationResources();
        }
Esempio n. 11
0
        public static void AddResource(Part part, String name, float amount, float max)
        {
            if (getResource(part, name) != null)
            {
                return;
            }

            ConfigNode node = new ConfigNode("RESOURCE");

            node.AddValue("name", name);
            node.AddValue("maxAmount", max);
            node.AddValue("amount", amount);
            part.AddResource(node);
        }
Esempio n. 12
0
        public void applyToPart(Part part, float modifier, bool keepExistingAmount)
        {
            PartResource pr = part.Resources[name];

            if (pr != null)
            {
                pr.maxAmount = max * modifier;
                if (keepExistingAmount)
                {
                    pr.amount = Math.Min(pr.amount, pr.maxAmount);
                }
                else
                {
                    pr.amount = fill * modifier;
                }
            }
            else
            {
                ConfigNode resourceNode;
                resourceNode = new ConfigNode("RESOURCE");
                resourceNode.AddValue("name", name);
                resourceNode.AddValue("maxAmount", max * modifier);
                resourceNode.AddValue("amount", fill * modifier);
                pr = part.AddResource(resourceNode);
            }

            //handle stock delta-v simulation resource setup
            //SR resource code adapted from B9 code by @blowfishpro
            //https://github.com/blowfishpro/B9PartSwitch/pull/110/files
            PartResource sr = part.SimulationResources[name];

            if (sr != null)
            {
                sr.maxAmount = max * modifier;
                if (keepExistingAmount)
                {
                    sr.amount = Math.Min(pr.amount, pr.maxAmount);
                }
                else
                {
                    sr.amount = fill * modifier;
                }
            }
            else
            {
                sr = new PartResource(pr);
                sr.simulationResource = true;
                part.SimulationResources.dict.Add(name.GetHashCode(), sr);
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Actually set the resources from this list to the input part; if the current part resources match this list exactly they will be updated in-place,
        /// else all resources from the part will be cleared and the new list of resources added.
        /// </summary>
        /// <param name="part"></param>
        /// <param name="fill"></param>
        public void setResourcesToPart(Part part)
        {
            int len = part.Resources.Count;

            if (len == resourceList.Count)//potentially the same resources exist as we are trying to setup
            {
                bool foundAll = true;
                foreach (String name in resourceList.Keys)
                {
                    ResourceListEntry entry = resourceList[name];
                    if (part.Resources.Contains(name))//go ahead and set them as found; if not all are found we'll delete them anyway...
                    {
                        PartResource pr = part.Resources[name];
                        pr.maxAmount = entry.max;
                        pr.amount    = entry.fill;
                    }
                    else
                    {
                        foundAll = false;
                        break;
                    }
                }
                if (foundAll)
                {
                    SSTUModInterop.updatePartResourceDisplay(part);
                    return;
                }
            }
            part.Resources.list.Clear();
            PartResource[] resources = part.GetComponents <PartResource>();
            len = resources.Length;
            for (int i = 0; i < len; i++)
            {
                GameObject.Destroy(resources[i]);
            }
            ConfigNode resourceNode;

            foreach (String name in resourceList.Keys)
            {
                ResourceListEntry entry = resourceList[name];
                resourceNode = new ConfigNode("RESOURCE");
                resourceNode.AddValue("name", name);
                resourceNode.AddValue("maxAmount", entry.max);
                resourceNode.AddValue("amount", entry.fill);
                part.AddResource(resourceNode);
            }
            SSTUModInterop.updatePartResourceDisplay(part);
        }
Esempio n. 14
0
        private void setupTankInPart(Part currentPart, bool calledByPlayer)
        {
            currentPart.Resources.list.Clear();
            PartResource[] partResources = currentPart.GetComponents <PartResource>();
            for (int i = 0; i < partResources.Length; i++)
            {
                DestroyImmediate(partResources[i]);
            }

            for (int tankCount = 0; tankCount < tankList.Count; tankCount++)
            {
                if (selectedTankSetup == tankCount)
                {
                    for (int resourceCount = 0; resourceCount < tankList[tankCount].resources.Count; resourceCount++)
                    {
                        if (tankList[tankCount].resources[resourceCount].name != "Structural")
                        {
                            //Debug.Log("new node: " + tankList[i].resources[j].name);
                            ConfigNode newResourceNode = new ConfigNode("RESOURCE");
                            newResourceNode.AddValue("name", tankList[tankCount].resources[resourceCount].name);
                            if (calledByPlayer || brandNewPart)
                            {
                                newResourceNode.AddValue("amount", tankList[tankCount].resources[resourceCount].maxAmount);
                                setResource(resourceCount, tankList[tankCount].resources[resourceCount].amount);
                            }
                            else
                            {
                                newResourceNode.AddValue("amount", getResource(resourceCount));
                            }
                            newResourceNode.AddValue("maxAmount", tankList[tankCount].resources[resourceCount].maxAmount);

                            //Debug.Log("add node to part");
                            currentPart.AddResource(newResourceNode);
                        }
                        else
                        {
                            //Debug.Log("Skipping structural fuel type");
                        }
                    }
                }
            }
            currentPart.Resources.UpdateList();
            updateWeight(currentPart, selectedTankSetup);
            updateCost();
        }
        public static void ModifyPart(Part part, ConfigNode node)
        {
            part.Fields.Load(node);

            //Step 2A: clear the old Resources
            part.Resources.list.Clear();
            //Step 2B: load the new Resources
            foreach (ConfigNode rNode in node.GetNodes("RESOURCE"))
            {
                part.AddResource(rNode);
            }

            //Step 3A: clear the old Modules
            while (part.Modules.Count > 0)
            {
                part.RemoveModule(part.Modules [0]);
            }
            //Step 3B: load the new Modules
            foreach (ConfigNode mNode in node.GetNodes("MODULE"))
            {
                PartModule module = part.AddModule(mNode.GetValue("name"));
                if (module)
                {
                    // really? REALLY? It appears the only way to make this work, is to molest KSP's privates.
                    if (Awaken(module))                       // uses reflection to find and call the PartModule.Awake() private method
                    {
                        module.Load(mNode);
                    }
                    else
                    {
                        print("Awaken failed for new module.");
                    }
                    if (module.part == null)
                    {
                        print("new module has null part.");
                    }
                    else
                    {
                                                #if DEBUG
                        print("Created module for " + module.part.name);
                                                #endif
                    }
                }
            }
        }
Esempio n. 16
0
        private void setupTankInPart(Part currentPart, bool calledByPlayer)
        {
            currentPart.Resources.dict = new DictionaryValueList <int, PartResource>();
            PartResource[] partResources = currentPart.GetComponents <PartResource>();
            //for (int i = 0; i < partResources.Length; i++)
            //{
            //    DestroyImmediate(partResources[i]);
            //}

            for (int tankCount = 0; tankCount < tankList.Count; tankCount++)
            {
                if (selectedTankSetup == tankCount)
                {
                    for (int resourceCount = 0; resourceCount < tankList[tankCount].resources.Count; resourceCount++)
                    {
                        if (tankList[tankCount].resources[resourceCount].name != "Structural")
                        {
                            //Debug.Log("new node: " + tankList[i].resources[j].name);
                            ConfigNode newResourceNode = new ConfigNode("RESOURCE");
                            newResourceNode.AddValue("name", tankList[tankCount].resources[resourceCount].name);
                            newResourceNode.AddValue("maxAmount", tankList[tankCount].resources[resourceCount].maxAmount);
                            if (calledByPlayer && !HighLogic.LoadedSceneIsEditor)
                            {
                                newResourceNode.AddValue("amount", 0.0f);
                            }
                            else
                            {
                                newResourceNode.AddValue("amount", tankList[tankCount].resources[resourceCount].amount);
                            }

                            //Debug.Log("add node to part");
                            currentPart.AddResource(newResourceNode);
                        }
                        else
                        {
                            //Debug.Log("Skipping structural fuel type");
                        }
                    }
                }
            }

            updateWeight(currentPart, selectedTankSetup);
            updateCost();
        }
Esempio n. 17
0
        public static PartResource setResourceMaxAmount(Part part, string name, double max)
        {
            PartResource res = getResource(part, name);

            if (res == null && max > 0)
            {
                ConfigNode node = new ConfigNode("RESOURCE");
                node.AddValue("name", name);
                node.AddValue("amount", 0);
                node.AddValue("maxAmount", max);
                res = part.AddResource(node);
            }
            else if (res != null && max > 0)
            {
                res.maxAmount = max;
            }
            else if (res != null && max <= 0)
            {
                part.Resources.list.Remove(res);
            }
            return(res);
        }
        // Amount < 0 signifies use existing amount if exists, or create with max amount
        public static PartResource AddOrCreateResource(this Part part, PartResourceDefinition info, float maxAmount, float amount, bool modifyAmountIfPresent)
        {
            if (amount > maxAmount)
            {
                part.LogWarning($"Cannot add resource '{info.name}' with amount > maxAmount, will use maxAmount (amount = {amount}, maxAmount = {maxAmount})");
                amount = maxAmount;
            }
            else if (amount < 0f)
            {
                part.LogWarning($"Cannot add resource '{info.name}' with amount < 0, will use 0 (amount = {amount})");
                amount = 0f;
            }

            PartResource resource = part.Resources[info.name];

            if (resource == null)
            {
                resource = part.AddResource(info, maxAmount, amount);
            }
            else
            {
                resource.maxAmount = maxAmount;

                PartResource simulationResource = part.SimulationResources?[info.name];
                if (simulationResource.IsNotNull())
                {
                    simulationResource.maxAmount = maxAmount;
                }

                if (modifyAmountIfPresent)
                {
                    resource.amount = amount;
                }
            }

            return(resource);
        }
 public static PartResource setResourceMaxAmount(Part part, string name, double max)
 {
     PartResource res = getResource(part, name);
     if (res == null && max > 0)
     {
         ConfigNode node = new ConfigNode("RESOURCE");
         node.AddValue("name", name);
         node.AddValue("amount", 0);
         node.AddValue("maxAmount", max);
         res = part.AddResource(node);
     }
     else if (res != null && max > 0)
     {
         res.maxAmount = max;
     }
     else if (res != null && max <= 0)
     {
         part.Resources.list.Remove(res);
     }
     return res;
 }
        /// <summary>
        /// Switch the resources from the parts
        /// </summary>
        /// <param name="currentPart">The part which resources have to be switched</param>
        /// <param name="newResourceID">The ID of the new resource</param>
        private void switchResources(Part currentPart, int newResourceID)
        {
            if ((initialized) && (switchableResources.Count > 0))
            {
                //only switch when a valid resourceID is set
                if ((newResourceID >= 0) && (newResourceID < switchableResources.Count))
                {
                    //List<LynxDefaultResource> removedDefaultResources = new List<LynxDefaultResource>();

                    //remove the previous resources from the part
                    if (selectedResourceID != -1)
                    {
                        //when the default resources should be replaced
                        if (replaceDefaultResources)
                        {
                            currentPart.Resources.Clear();
                        }
                        else
                        {
                            //get the list of resources from the last setup
                            KerbetrotterSwitchableResource oldResources      = switchableResources[selectedResourceID];
                            List <PartResource>            resourcesToRemove = new List <PartResource>();

                            //remove all of the resources that are not default, update the default ones
                            int numResources = currentPart.Resources.Count;
                            for (int i = 0; i < numResources; i++)
                            {
                                PartResource partResource = currentPart.Resources[i];

                                KerbetrotterDefaultResource defaultResource = getResourceFromList(partResource.resourceName, defaultResources);

                                //When the part containes this resource as a default resource, change its values
                                if (defaultResource != null)
                                {
                                    double amount = getDefaultResourceAmount(defaultResource.name, defaultResource.maxAmount, currentPart);
                                    partResource.amount      = amount;
                                    partResource.maxAmount   = defaultResource.maxAmount;
                                    partResource.isTweakable = defaultResource.isTweakable;
                                }
                                //else add resource to remove list
                                else
                                {
                                    resourcesToRemove.Add(partResource);
                                }
                            }

                            //remove the resources that are scheduled to be removed
                            for (int i = 0; i < resourcesToRemove.Count; i++)
                            {
                                currentPart.RemoveResource(resourcesToRemove[i]);
                            }
                        }
                    }

                    //update the new resource id
                    selectedResourceID = newResourceID;
                    KerbetrotterResourceDefinition[] newResources = switchableResources[selectedResourceID].resources;

                    //update costs and weights
                    resourceCostsModifier = (float)switchableResources[selectedResourceID].costModifier;
                    resourceMassModifier  = (float)switchableResources[selectedResourceID].massModifier;

                    //add all the defined resources to the part
                    for (int i = 0; i < newResources.Length; i++)
                    {
                        //Skip resources with the name Structural (why?)
                        if (newResources[i].name == "Structural")
                        {
                            continue;
                        }

                        double maxAmount = newResources[i].maxAmount;
                        double amount    = 0.0;

                        //when in editor, we will set the configured amount
                        if (HighLogic.LoadedSceneIsEditor)
                        {
                            amount = newResources[i].amount;
                        }

                        //get the data of the default resource if available
                        KerbetrotterDefaultResource defaultResource = getResourceFromList(newResources[i].name, defaultResources);

                        //when we have a default resource and do not replace them, update their data
                        if ((!replaceDefaultResources) && (defaultResource != null))
                        {
                            PartResource partResource = currentPart.Resources[defaultResource.name];

                            partResource.maxAmount  += newResources[i].maxAmount;
                            partResource.amount     += amount;
                            partResource.isTweakable = newResources[i].isTweakable;
                        }
                        //else create and add a new resource
                        else
                        {
                            ConfigNode newResourceNode = new ConfigNode("RESOURCE");
                            newResourceNode.AddValue("name", newResources[i].name);
                            newResourceNode.AddValue("maxAmount", newResources[i].maxAmount);
                            newResourceNode.AddValue("isTweakable", newResources[i].isTweakable);
                            newResourceNode.AddValue("amount", amount);

                            //when we are in the editor, fill the tank with the new amount
                            if (HighLogic.LoadedSceneIsEditor)
                            {
                                newResourceNode.AddValue("amount", newResources[i].amount);
                            }
                            //else the tank is empty
                            else
                            {
                                newResourceNode.AddValue("amount", 0.0f);
                            }

                            currentPart.AddResource(newResourceNode);
                        }
                    }
                }
            }
        }
Esempio n. 21
0
        public void Update()
        {
            this.enabled = true;
            AvailablePart intakePart = PartLoader.getPartInfoByName("CircularIntake");

            if (intakePart != null)
            {
                if (intakePart.partPrefab.FindModulesImplementing <AtmosphericIntake>().Count <= 0 && PartLoader.Instance.IsReady())
                {
                    plugin_init = false;
                }
            }

            if (!resources_configured)
            {
                ConfigNode plugin_settings = GameDatabase.Instance.GetConfigNode("WarpPlugin/WarpPluginSettings/WarpPluginSettings");
                if (plugin_settings != null)
                {
                    if (plugin_settings.HasValue("HydrogenResourceName"))
                    {
                        PluginHelper.hydrogen_resource_name = plugin_settings.GetValue("HydrogenResourceName");
                        Debug.Log("[KSP Interstellar] Hydrogen resource name set to " + PluginHelper.hydrogen_resource_name);
                    }
                    if (plugin_settings.HasValue("OxygenResourceName"))
                    {
                        PluginHelper.oxygen_resource_name = plugin_settings.GetValue("OxygenResourceName");
                        Debug.Log("[KSP Interstellar] Oxygen resource name set to " + PluginHelper.oxygen_resource_name);
                    }
                    if (plugin_settings.HasValue("AluminiumResourceName"))
                    {
                        PluginHelper.aluminium_resource_name = plugin_settings.GetValue("AluminiumResourceName");
                        Debug.Log("[KSP Interstellar] Aluminium resource name set to " + PluginHelper.aluminium_resource_name);
                    }
                    if (plugin_settings.HasValue("MethaneResourceName"))
                    {
                        PluginHelper.methane_resource_name = plugin_settings.GetValue("MethaneResourceName");
                        Debug.Log("[KSP Interstellar] Methane resource name set to " + PluginHelper.methane_resource_name);
                    }
                    if (plugin_settings.HasValue("ArgonResourceName"))
                    {
                        PluginHelper.argon_resource_name = plugin_settings.GetValue("ArgonResourceName");
                        Debug.Log("[KSP Interstellar] Argon resource name set to " + PluginHelper.argon_resource_name);
                    }
                    if (plugin_settings.HasValue("WaterResourceName"))
                    {
                        PluginHelper.water_resource_name = plugin_settings.GetValue("WaterResourceName");
                        Debug.Log("[KSP Interstellar] Water resource name set to " + PluginHelper.water_resource_name);
                    }
                    if (plugin_settings.HasValue("HydrogenPeroxideResourceName"))
                    {
                        PluginHelper.hydrogen_peroxide_resource_name = plugin_settings.GetValue("HydrogenPeroxideResourceName");
                        Debug.Log("[KSP Interstellar] Hydrogen Peroxide resource name set to " + PluginHelper.hydrogen_peroxide_resource_name);
                    }
                    if (plugin_settings.HasValue("AmmoniaResourceName"))
                    {
                        PluginHelper.ammonia_resource_name = plugin_settings.GetValue("AmmoniaResourceName");
                        Debug.Log("[KSP Interstellar] Ammonia resource name set to " + PluginHelper.ammonia_resource_name);
                    }
                    if (plugin_settings.HasValue("ThermalMechanicsDisabled"))
                    {
                        PluginHelper.is_thermal_dissip_disabled = bool.Parse(plugin_settings.GetValue("ThermalMechanicsDisabled"));
                        Debug.Log("[KSP Interstellar] ThermalMechanics set to enabled: " + !PluginHelper.is_thermal_dissip_disabled);
                    }
                    resources_configured = true;
                }
                else
                {
                    showInstallationErrorMessage();
                }
            }

            if (!plugin_init)
            {
                gdb         = GameDatabase.Instance;
                plugin_init = true;

                AvailablePart kerbalRadiationPart = PartLoader.getPartInfoByName("kerbalEVA");
                if (kerbalRadiationPart.partPrefab.Modules != null)
                {
                    if (kerbalRadiationPart.partPrefab.FindModulesImplementing <FNModuleRadiation>().Count == 0)
                    {
                        kerbalRadiationPart.partPrefab.gameObject.AddComponent <FNModuleRadiation>();
                    }
                }
                else
                {
                    kerbalRadiationPart.partPrefab.gameObject.AddComponent <FNModuleRadiation>();
                }

                List <AvailablePart> available_parts = PartLoader.LoadedPartsList;
                foreach (AvailablePart available_part in available_parts)
                {
                    Part prefab_available_part = available_part.partPrefab;
                    try {
                        if (prefab_available_part.Modules != null)
                        {
                            if (prefab_available_part.FindModulesImplementing <ModuleResourceIntake>().Count > 0)
                            {
                                ModuleResourceIntake intake = prefab_available_part.Modules["ModuleResourceIntake"] as ModuleResourceIntake;
                                if (intake.resourceName == "IntakeAir")
                                {
                                    Type type            = AssemblyLoader.GetClassByName(typeof(PartModule), "AtmosphericIntake");
                                    AtmosphericIntake pm = null;
                                    if (type != null)
                                    {
                                        pm = prefab_available_part.gameObject.AddComponent(type) as AtmosphericIntake;
                                        prefab_available_part.Modules.Add(pm);
                                        pm.area = intake.area * intake.unitScalar * intake.maxIntakeSpeed / 20;
                                    }

                                    PartResource intake_air_resource = prefab_available_part.Resources["IntakeAir"];

                                    if (intake_air_resource != null && !prefab_available_part.Resources.Contains("IntakeAtm"))
                                    {
                                        ConfigNode node = new ConfigNode("RESOURCE");
                                        node.AddValue("name", "IntakeAtm");
                                        node.AddValue("maxAmount", intake_air_resource.maxAmount);
                                        node.AddValue("amount", intake_air_resource.amount);
                                        prefab_available_part.AddResource(node);
                                    }
                                }
                            }

                            if (prefab_available_part.FindModulesImplementing <ModuleDeployableSolarPanel>().Count > 0)
                            {
                                ModuleDeployableSolarPanel panel = prefab_available_part.Modules["ModuleDeployableSolarPanel"] as ModuleDeployableSolarPanel;
                                if (panel.chargeRate > 0)
                                {
                                    Type type = AssemblyLoader.GetClassByName(typeof(PartModule), "FNSolarPanelWasteHeatModule");
                                    FNSolarPanelWasteHeatModule pm = null;
                                    if (type != null)
                                    {
                                        pm = prefab_available_part.gameObject.AddComponent(type) as FNSolarPanelWasteHeatModule;
                                        prefab_available_part.Modules.Add(pm);
                                    }
                                }


                                if (!prefab_available_part.Resources.Contains("WasteHeat") && panel.chargeRate > 0)
                                {
                                    ConfigNode node = new ConfigNode("RESOURCE");
                                    node.AddValue("name", "WasteHeat");
                                    node.AddValue("maxAmount", panel.chargeRate * 100);
                                    node.AddValue("amount", 0);
                                    PartResource pr = prefab_available_part.AddResource(node);

                                    if (available_part.resourceInfo != null && pr != null)
                                    {
                                        if (available_part.resourceInfo.Length == 0)
                                        {
                                            available_part.resourceInfo = pr.resourceName + ":" + pr.amount + " / " + pr.maxAmount;
                                        }
                                        else
                                        {
                                            available_part.resourceInfo = available_part.resourceInfo + "\n" + pr.resourceName + ":" + pr.amount + " / " + pr.maxAmount;
                                        }
                                    }
                                }
                            }

                            if (prefab_available_part.FindModulesImplementing <ElectricEngineController>().Count() > 0)
                            {
                                available_part.moduleInfo = prefab_available_part.FindModulesImplementing <ElectricEngineController>().First().GetInfo();
                                available_part.moduleInfos.RemoveAll(modi => modi.moduleName == "Engine");
                                AvailablePart.ModuleInfo mod_info = available_part.moduleInfos.Where(modi => modi.moduleName == "Electric Engine Controller").First();
                                mod_info.moduleName = "Electric Engine";
                            }

                            if (prefab_available_part.FindModulesImplementing <FNNozzleController>().Count() > 0)
                            {
                                available_part.moduleInfo = prefab_available_part.FindModulesImplementing <FNNozzleController>().First().GetInfo();
                                available_part.moduleInfos.RemoveAll(modi => modi.moduleName == "Engine");
                                AvailablePart.ModuleInfo mod_info = available_part.moduleInfos.Where(modi => modi.moduleName == "FNNozzle Controller").First();
                                mod_info.moduleName = "Thermal Nozzle";
                            }

                            if (prefab_available_part.CrewCapacity > 0)
                            {
                                Type type            = AssemblyLoader.GetClassByName(typeof(PartModule), "FNModuleRadiation");
                                FNModuleRadiation pm = null;
                                if (type != null)
                                {
                                    pm = prefab_available_part.gameObject.AddComponent(type) as FNModuleRadiation;
                                    prefab_available_part.Modules.Add(pm);
                                    double rad_hardness = prefab_available_part.mass / ((double)prefab_available_part.CrewCapacity) * 7.5;
                                    pm.rad_hardness = rad_hardness;
                                }
                                print("Adding ModuleRadiation to " + prefab_available_part.name);
                            }
                        }
                    }catch (Exception ex) {
                        if (prefab_available_part != null)
                        {
                            print("[KSP Interstellar] Exception caught adding to: " + prefab_available_part.name + " part: " + ex.ToString());
                        }
                        else
                        {
                            print("[KSP Interstellar] Exception caught adding to unknown module");
                        }
                    }
                }
            }

            //Destroy (this);
        }
Esempio n. 22
0
 /// <summary>
 /// Actually set the resources from this list to the input part; if the current part resources match this list exactly they will be updated in-place,
 /// else all resources from the part will be cleared and the new list of resources added.
 /// </summary>
 /// <param name="part"></param>
 /// <param name="fill"></param>
 public void setResourcesToPart(Part part)
 {
     int len = part.Resources.Count;
     if (len == resourceList.Count)//potentially the same resources exist as we are trying to setup
     {
         bool foundAll = true;
         foreach (String name in resourceList.Keys)
         {
             ResourceListEntry entry = resourceList[name];
             if (part.Resources.Contains(name))//go ahead and set them as found; if not all are found we'll delete them anyway...
             {
                 PartResource pr = part.Resources[name];
                 pr.maxAmount = entry.max;
                 pr.amount = entry.fill;
             }
             else
             {
                 foundAll = false;
                 break;
             }
         }
         if (foundAll)
         {
             SSTUModInterop.updatePartResourceDisplay(part);
             return;
         }
     }
     part.Resources.dict.Clear();
     ConfigNode resourceNode;
     foreach (String name in resourceList.Keys)
     {
         ResourceListEntry entry = resourceList[name];
         resourceNode = new ConfigNode("RESOURCE");
         resourceNode.AddValue("name", name);
         resourceNode.AddValue("maxAmount", entry.max);
         resourceNode.AddValue("amount", entry.fill);
         part.AddResource(resourceNode);
     }
     SSTUModInterop.updatePartResourceDisplay(part);
 }
Esempio n. 23
0
 private void EvaAddResource(Part part, double rate, string name, bool full)
 {
     try
     {
         double max = rate * TacStartOnce.Instance.globalSettings.EvaDefaultResourceAmount;
         ConfigNode resourceNode = new ConfigNode("RESOURCE");
         resourceNode.AddValue("name", name);
         resourceNode.AddValue("maxAmount", max);
         if (full)
         {
             resourceNode.AddValue("amount", max);
         }
         else
         {
             resourceNode.AddValue("amount", 0);
         }
         resourceNode.AddValue("isTweakable", false);
         PartResource resource = part.AddResource(resourceNode);
         resource.flowState = true;
         resource.flowMode = PartResource.FlowMode.Both;
     }
     catch (Exception ex)
     {
         if (!ex.Message.Contains("Object reference not set"))
         {
             this.LogError("Unexpected error while adding resource " + name + " to the EVA: " + ex.Message + "\n" + ex.StackTrace);
         }
     }
 }
Esempio n. 24
0
        public void SetState(Part thatPart, bool newstate, GameObject objectLocal)
        {
            if (inverted)
            {
                newstate = !newstate;
            }
            switch (type)
            {
            case ActuatorType.PartComponent:
                // Note to other people who want to use this:
                // If you want to control a JSIPartComponentToggle, this is how you do it!
                var eventData = new BaseEventData(BaseEventData.Sender.USER);
                eventData.Set("moduleID", moduleID);
                eventData.Set("state", newstate);
                eventData.Set("objectLocal", objectLocal);
                thatPart.SendEvent("JSIComponentToggle", eventData);
                break;

            case ActuatorType.PartComponentGroup:
                // Note to other people who want to use this:
                // If you want to control a JSIPartComponentToggle, this is how you do it!
                var eventgroupData = new BaseEventData(BaseEventData.Sender.USER);
                eventgroupData.Set("groupID", moduleID);
                eventgroupData.Set("state", newstate);
                eventgroupData.Set("objectLocal", objectLocal);
                thatPart.SendEvent("JSIGroupToggle", eventgroupData);
                break;

            case ActuatorType.PartModule:
                controlledModule.enabled   = newstate;
                controlledModule.isEnabled = newstate;
                break;

            case ActuatorType.TransformTexture:
                Renderer mat = targetTransform.GetComponent <Renderer> ();
                mat.material.SetTexture(textureLayer, newstate ? GameDatabase.Instance.GetTexture(trueString, false) : GameDatabase.Instance.GetTexture(falseString, false));
                break;

            case ActuatorType.TransformShader:
                Renderer shm = targetTransform.GetComponent <Renderer> ();
                shm.material.shader = Shader.Find(newstate ? trueString : falseString);
                break;

            case ActuatorType.StraightParameter:
                if (newstate)
                {
                    SetParameter(nameOfParameter, thatPart, originalParameterValue + addToParameterWhenEnabled);
                }
                else
                {
                    SetParameter(nameOfParameter, thatPart, originalParameterValue);
                }
                break;

            case ActuatorType.CrewCapacity:
                var eventccData = new BaseEventData(BaseEventData.Sender.USER);
                eventccData.Set("state", newstate);
                eventccData.Set("objectLocal", objectLocal);
                thatPart.SendEvent("JSISetCrewCapacity", eventccData);
                break;

            case ActuatorType.Resource:
                // We do not manipulate resource records out of the editor because fsckit.
                if (HighLogic.LoadedSceneIsEditor)
                {
                    if (!newstate)
                    {
                        if (resourcePointer == null)
                        {
                            resourcePointer = thatPart.Resources [resourceName];
                        }
                        // We can, hopefully, avoid deleting the tank that this particular actuator did not create.
                        if (resourcePointer != null && resourcePointer.maxAmount == maxAmount)
                        {
                            thatPart.Resources.list.Remove(resourcePointer);
                            UnityEngine.Object.Destroy(resourcePointer);
                            resourcePointer = null;
                        }
                    }
                    if (newstate && resourcePointer == null && thatPart.Resources [resourceName] == null)
                    {
                        var node = new ConfigNode("RESOURCE");
                        node.AddValue("name", resourceName);
                        node.AddValue("amount", maxAmount);
                        node.AddValue("maxAmount", maxAmount);
                        resourcePointer         = thatPart.AddResource(node);
                        resourcePointer.enabled = true;
                    }
                }
                break;

            case ActuatorType.AttachmentNode:
                if (HighLogic.LoadedSceneIsEditor && savedNodePosition != faraway)
                {
                    var foundNode = thatPart.findAttachNode(nodeName);
                    if (foundNode.attachedPart == null)
                    {
                        foundNode.position = newstate ? faraway : savedNodePosition;
                    }
                }
                break;
            }
            if (HighLogic.LoadedSceneIsEditor)
            {
                // We need to also notify the editor that we changed the part so that Engineers' Toolbox works.
                GameEvents.onEditorShipModified.Fire(EditorLogic.fetch.ship);
            }
        }
Esempio n. 25
0
        public void SetState(Part thatPart, bool newstate, GameObject objectLocal)
        {
            if (inverted)
                newstate = !newstate;
            switch (type) {
            case ActuatorType.PartComponent:
            // Note to other people who want to use this:
            // If you want to control a JSIPartComponentToggle, this is how you do it!
                var eventData = new BaseEventData (BaseEventData.Sender.USER);
                eventData.Set ("moduleID", moduleID);
                eventData.Set ("state", newstate);
                eventData.Set ("objectLocal", objectLocal);
                thatPart.SendEvent ("JSIComponentToggle", eventData);
                break;
            case ActuatorType.PartComponentGroup:
                // Note to other people who want to use this:
                // If you want to control a JSIPartComponentToggle, this is how you do it!
                var eventgroupData = new BaseEventData (BaseEventData.Sender.USER);
                eventgroupData.Set ("groupID", moduleID);
                eventgroupData.Set ("state", newstate);
                eventgroupData.Set ("objectLocal", objectLocal);
                thatPart.SendEvent ("JSIGroupToggle", eventgroupData);
                break;
            case ActuatorType.PartModule:
                controlledModule.enabled = newstate;
                controlledModule.isEnabled = newstate;
                break;
            case ActuatorType.TransformTexture:
                Renderer mat = targetTransform.GetComponent<Renderer> ();
                mat.material.SetTexture (textureLayer, newstate ? GameDatabase.Instance.GetTexture (trueString, false) : GameDatabase.Instance.GetTexture (falseString, false));
                break;
            case ActuatorType.TransformShader:
                Renderer shm = targetTransform.GetComponent<Renderer> ();
                shm.material.shader = Shader.Find (newstate ? trueString : falseString);
                break;
            case ActuatorType.StraightParameter:
                if (newstate) {
                    SetParameter (nameOfParameter, thatPart, originalParameterValue + addToParameterWhenEnabled);
                } else {
                    SetParameter (nameOfParameter, thatPart, originalParameterValue);
                }
                break;
            case ActuatorType.CrewCapacity:
                var eventccData = new BaseEventData (BaseEventData.Sender.USER);
                eventccData.Set ("state", newstate);
                eventccData.Set ("objectLocal", objectLocal);
                thatPart.SendEvent ("JSISetCrewCapacity", eventccData);
                break;
            case ActuatorType.Resource:
                // We do not manipulate resource records out of the editor because fsckit.
                if (HighLogic.LoadedSceneIsEditor) {
                    if (!newstate) {
                        if (resourcePointer == null) {
                            resourcePointer = thatPart.Resources [resourceName];
                        }
                        // We can, hopefully, avoid deleting the tank that this particular actuator did not create.
                        if (resourcePointer != null && resourcePointer.maxAmount == maxAmount) {
                            thatPart.Resources.Remove (resourcePointer);
                            //UnityEngine.Object.Destroy (resourcePointer);
                            resourcePointer = null;
                        }
                    }
                    if (newstate && resourcePointer == null && thatPart.Resources [resourceName] == null) {
                        var node = new ConfigNode ("RESOURCE");
                        node.AddValue ("name", resourceName);
                        node.AddValue ("amount", maxAmount);
                        node.AddValue ("maxAmount", maxAmount);
                        resourcePointer = thatPart.AddResource (node);
                        resourcePointer.flowState = true;
                    }

                }
                break;
            case ActuatorType.AttachmentNode:
                if (HighLogic.LoadedSceneIsEditor && savedNodePosition != faraway) {
                    var foundNode = thatPart.FindAttachNode (nodeName);
                    if (foundNode.attachedPart == null) {
                        foundNode.position = newstate ? faraway : savedNodePosition;
                    }
                }
                break;
            }
            if (HighLogic.LoadedSceneIsEditor) {
                // We need to also notify the editor that we changed the part so that Engineers' Toolbox works.
                GameEvents.onEditorShipModified.Fire(EditorLogic.fetch.ship);
            }
        }
        private List <string> SetupTankInPart(Part currentPart, bool calledByPlayer)
        {
            try
            {
                // find selected tank
                var selectedTank = calledByPlayer || String.IsNullOrEmpty(selectedTankSetupTxt)
                    ? selectedTankSetup < tankList.Count ? tankList[selectedTankSetup] : tankList[0]
                    : tankList.FirstOrDefault(t => t.GuiName == selectedTankSetupTxt) ?? (selectedTankSetup < tankList.Count ? tankList[selectedTankSetup] : tankList[0]);

                // update txt and index for future
                selectedTankSetupTxt = selectedTank.GuiName;
                selectedTankSetup    = tankList.IndexOf(selectedTank);

                // check if we need to change anything
                //if (!HighLogic.LoadedSceneIsEditor && gameLoaded && !calledByPlayer)
                //{
                //    Debug.Log("InsterstellarFuelSwitch assignResourcesToPart, no change required");
                //    return part.Resources.list.Select(r => r.resourceName).ToList();
                //}

                // create new ResourceNode
                var newResources       = new List <string>();
                var newResourceNodes   = new List <ConfigNode>();
                var parsedConfigAmount = new List <float>();

                // parse configured amounts
                if (configuredAmounts.Length > 0)
                {
                    // empty configuration if switched by user
                    if (calledByPlayer)
                    {
                        configuredAmounts = String.Empty;
                        //Debug.Log("InsterstellarFuelSwitch assignResourcesToPart calledByPlayer reset configuredAmounts");
                    }

                    //Debug.Log("InsterstellarFuelSwitch assignResourcesToPart parsing configuredAmounts = " + configuredAmounts);
                    string[] configAmount = configuredAmounts.Split(',');
                    foreach (string item in configAmount)
                    {
                        float value;
                        if (float.TryParse(item, out value))
                        {
                            parsedConfigAmount.Add(value);
                        }
                    }

                    // empty configuration if in flight
                    if (!HighLogic.LoadedSceneIsEditor)
                    {
                        configuredAmounts = String.Empty;
                        //Debug.Log("InsterstellarFuelSwitch assignResourcesToPart not HighLogic.LoadedSceneIsEditor reset configuredAmounts");
                    }
                }

                // imitialise minimum boiloff temperature at current part temperature
                double minimumBoiloffTemerature = -1;

                for (int resourceId = 0; resourceId < selectedTank.Resources.Count; resourceId++)
                {
                    var selectedTankResource = selectedTank.Resources[resourceId];

                    if (minimumBoiloffTemerature == -1 || (selectedTankResource.boiloffTemp > 0 && selectedTankResource.boiloffTemp < minimumBoiloffTemerature))
                    {
                        minimumBoiloffTemerature = selectedTankResource.boiloffTemp;
                    }

                    if (selectedTankResource.name == "Structural")
                    {
                        continue;
                    }

                    newResources.Add(selectedTankResource.name);

                    ConfigNode newResourceNode = new ConfigNode("RESOURCE");
                    double     maxAmount       = selectedTankResource.maxAmount * currentVolumeMultiplier;

                    newResourceNode.AddValue("name", selectedTankResource.name);
                    newResourceNode.AddValue("maxAmount", maxAmount);

                    PartResource existingResource = null;
                    if (!HighLogic.LoadedSceneIsEditor || (HighLogic.LoadedSceneIsEditor && !calledByPlayer))
                    {
                        foreach (PartResource partResource in currentPart.Resources)
                        {
                            if (partResource.resourceName.Equals(selectedTankResource.name))
                            {
                                existingResource = partResource;
                                break;
                            }
                        }
                    }

                    double resourceNodeAmount;
                    if (existingResource != null)
                    {
                        resourceNodeAmount = Math.Min(existingResource.amount, maxAmount);
                    }
                    else if (!HighLogic.LoadedSceneIsEditor && resourceId < parsedConfigAmount.Count)
                    {
                        resourceNodeAmount = parsedConfigAmount[resourceId];
                    }
                    else if (!HighLogic.LoadedSceneIsEditor && calledByPlayer)
                    {
                        resourceNodeAmount = 0.0;
                    }
                    else
                    {
                        resourceNodeAmount = selectedTank.Resources[resourceId].amount * currentVolumeMultiplier;
                    }

                    newResourceNode.AddValue("amount", resourceNodeAmount);
                    newResourceNodes.Add(newResourceNode);
                }


                //// prepare part to initialise temerature
                //if (minimumBoiloffTemerature != -1)
                //{
                //    var currentFuelswitch = part.FindModuleImplementing<InterstellarFuelSwitch>();
                //    if (currentFuelswitch != null)
                //    {
                //        Debug.Log("InsterstellarFuelSwitch SetupTankInPart prepared to initialise part temperature at " + minimumBoiloffTemerature);
                //        currentFuelswitch.initializePartTemperature = minimumBoiloffTemerature;
                //    }
                //}

                var finalResourceNodes = new List <ConfigNode>();

                // remove all resources except those we ignore
                PartResource[] partResources = currentPart.GetComponents <PartResource>();
                foreach (PartResource resource in partResources)
                {
                    if (activeResourceList.Contains(resource.resourceName))
                    {
                        if (newResourceNodes.Count > 0)
                        {
                            finalResourceNodes.AddRange(newResourceNodes);
                            newResourceNodes.Clear();
                        }

                        currentPart.Resources.list.Remove(resource);
                        DestroyImmediate(resource);
                    }
                    else
                    {
                        ConfigNode newResourceNode = new ConfigNode("RESOURCE");
                        newResourceNode.AddValue("name", resource.resourceName);
                        newResourceNode.AddValue("maxAmount", resource.maxAmount);
                        newResourceNode.AddValue("amount", resource.amount);

                        finalResourceNodes.Add(newResourceNode);
                        Debug.Log("InsterstellarFuelSwitch SetupTankInPart created confignode for: " + resource.resourceName);

                        // remove all
                        currentPart.Resources.list.Remove(resource);
                        DestroyImmediate(resource);
                        Debug.Log("InsterstellarFuelSwitch SetupTankInPart remove resource " + resource.resourceName);
                    }
                }

                // add any remaining bew nodes
                if (newResourceNodes.Count > 0)
                {
                    finalResourceNodes.AddRange(newResourceNodes);
                    newResourceNodes.Clear();
                }

                // add new resources
                //if (newResourceNodes.Count > 0)
                if (finalResourceNodes.Count > 0)
                {
                    Debug.Log("InsterstellarFuelSwitch SetupTankInPart adding resources: " + ParseTools.Print(newResources));
                    //foreach (var resourceNode in newResourceNodes)
                    foreach (var resourceNode in finalResourceNodes)
                    {
                        currentPart.AddResource(resourceNode);
                    }
                }

                // This also needs to be done when going from a setup with resources to a setup with no resources.
                currentPart.Resources.UpdateList();
                UpdateMass(currentPart, selectedTankSetup, calledByPlayer);
                UpdateCost();

                return(newResources);
            }
            catch (Exception e)
            {
                Debug.LogError("InsterstellarFuelSwitch SetupTankInPart Error");
                throw;
            }
        }
Esempio n. 27
0
        private void setupTankInPart(Part currentPart, bool calledByPlayer)
        {
            currentPart.Resources.list.Clear();
            PartResource[] partResources = currentPart.GetComponents<PartResource>();
            for (int i = 0; i < partResources.Length; i++)
            {
                DestroyImmediate(partResources[i]);
            }            

            for (int tankCount = 0; tankCount < tankList.Count; tankCount++)
            {
                if (selectedTankSetup == tankCount)
                {
                    for (int resourceCount = 0; resourceCount < tankList[tankCount].resources.Count; resourceCount++)
                    {
                        if (tankList[tankCount].resources[resourceCount].name != "Structural")
                        {
                            //Debug.Log("new node: " + tankList[i].resources[j].name);
                            ConfigNode newResourceNode = new ConfigNode("RESOURCE");
                            newResourceNode.AddValue("name", tankList[tankCount].resources[resourceCount].name);
                            newResourceNode.AddValue("maxAmount", tankList[tankCount].resources[resourceCount].maxAmount);
                            if (calledByPlayer && !HighLogic.LoadedSceneIsEditor)
                            {
                                newResourceNode.AddValue("amount", 0.0f);
                            } 
                            else
                            {
                                newResourceNode.AddValue("amount", tankList[tankCount].resources[resourceCount].amount);
                            }

                            //Debug.Log("add node to part");
                            currentPart.AddResource(newResourceNode);                          
                        }
                        else
                        {
                            //Debug.Log("Skipping structural fuel type");
                        }
                    }
                }
            }
            currentPart.Resources.UpdateList();
            updateWeight(currentPart, selectedTankSetup);
            updateCost();
        }
Esempio n. 28
0
        private void updateIntake(bool calledByPlayer, string callingFunction = "player")
        {
            ConfigNode newIntakeNode = new ConfigNode();
            Part       currentPart   = this.part;
            int        resIniAmount  = 0;
            bool       removethis    = false;


            //foreach (PartModule moduleIntake in ModuleIntakes)
            //Apparently the foreach does not work properly with Intakes. Don't know why.
            for (int i = 0; i < ModuleIntakes.Count; i++)
            {
                //*****************************
                //Debug.Log("Intake Switcher: Update Resource Intake");

                //Define the node object
                ConfigNode IntakeNode     = newIntakeNode;      //.GetNode("ModuleResourceIntake");
                ConfigNode IntakeResource = newIntakeNode;

                //Debug.Log("Confignode defined");
                //Debug.Log("checkForOxygen: " + arrIntakeNames[selectedIntake]);

                //Set new setting values
                if (!resourceNamesEmpty)
                {
                    IntakeNode.SetValue("resourceName", arrIntakeNames[selectedIntake], true);
                }
                if (!checkForOxygenEmpty)
                {
                    IntakeNode.SetValue("checkForOxygen", arrcheckForOxygen[selectedIntake], true);
                }
                else
                {
                    IntakeNode.RemoveNode("checkForOxygen");
                }

                //Debug.Log("Confignode value added");

                //Load changes (nodeobject) into the moduleIntake
                ModuleIntakes[i].Load(IntakeNode);

                //Debug.Log("Cleanout old resources");

                #region Intake Resource
                //Clean out any previous resources in the intake
                currentPart.Resources.Clear();
                //PartResource[] partResources = currentPart.GetComponents<PartResource>();
                //foreach (PartResource resource in partResources)
                //List<PartResource> resourcesDeleteList = new List<PartResource>();

                //currentPart.symmetryCounterparts;
                removethis = false;
                foreach (PartResource resource in currentPart.Resources)
                {
                    //Check if the resource is part of the switching resources, so that we do not destroy resources which are not intended for this switching
                    foreach (string inIntakeResource in arrIntakeNames)
                    {
                        if (inIntakeResource == resource.resourceName)
                        {
                            removethis = true;
                            break;
                        }
                    }

                    //currentPart.Resources.list.Remove(resource);
                    //if (removethis == true) { DestroyImmediate(resource., false); }              //*********COMMENTED OUT BECAUSE OF ERROR
                    //if (removethis == true) { Destroy(resource); }                              //*********COMMENTED OUT BECAUSE OF ERROR
                    //if (removethis == true) { PartResourceList[0].Remove(resource); }
                    //PartResourceList[0].;
                    //resource.;
                    //bool a;
                    //a = PartResourceList.Remove(resource);
                    if (removethis == true)
                    {
                        currentPart.Resources.Remove(resource);
                    }
                    removethis = false;
                }

                resIniAmount = HighLogic.LoadedSceneIsFlight ? 0 : int.Parse(resMaxAmount);

                //Create Resource node
                IntakeResource.AddNode("RESOURCE");
                IntakeResource.AddValue("name", arrIntakeNames[selectedIntake]);
                IntakeResource.AddValue("amount", resIniAmount);
                IntakeResource.AddValue("maxAmount", int.Parse(resMaxAmount));
                //Add the resources
                currentPart.AddResource(IntakeResource);

                //Update the part resources
                //currentPart.Resources.UpdateList();
                GUIResourceName = ModuleIntakes[0].resourceName;
                #endregion

                //added check for called by player, since the ResourceDisplay update fails when called from the OnStart function.
                try
                { if (HighLogic.LoadedSceneIsFlight && calledByPlayer)
                  {
                      KSP.UI.Screens.ResourceDisplay.Instance.Refresh();
                  }
                }
                catch { Debug.LogError("Update of resource panel failed" + "\ncallingFunction: " + callingFunction + "\ncalledByPlayer: " + calledByPlayer); }
                //Debug.Log("Confignode Loaded");
            }
        }
Esempio n. 29
0
 public void setResourcesInPart(Part part, float volume, bool fill)
 {
     part.Resources.list.Clear ();
     PartResource[] resources = part.GetComponents<PartResource> ();
     int len = resources.Length;
     for (int i = 0; i < len; i++)
     {
         GameObject.Destroy(resources[i]);
     }
     int rawFuelUnits = (int)(volume * unitsPerCubicMeter);
     int units;
     ConfigNode resourceNode;
     foreach (SSTUFuelEntry entry in fuelEntries)
     {
         units = entry.ratio * rawFuelUnits;
         resourceNode = new ConfigNode("RESOURCE");
         resourceNode.AddValue("name", entry.resourceName);
         resourceNode.AddValue("maxAmount", units);
         resourceNode.AddValue("amount", fill? units : 0);
         part.AddResource(resourceNode);
     }
 }
Esempio n. 30
0
 public void setResourcesToPart(Part part, bool fill)
 {
     part.Resources.list.Clear();
     PartResource[] resources = part.GetComponents<PartResource>();
     int len = resources.Length;
     for (int i = 0; i < len; i++)
     {
         GameObject.Destroy(resources[i]);
     }            
     ConfigNode resourceNode;
     float amt = 0;
     foreach (String name in resourceMap.Keys)
     {
         amt = resourceMap[name];
         resourceNode = new ConfigNode("RESOURCE");
         resourceNode.AddValue("name", name);
         resourceNode.AddValue("maxAmount", amt);
         resourceNode.AddValue("amount", fill ? amt : 0);
         part.AddResource(resourceNode);
     }
 }
Esempio n. 31
0
        public void Update()
        {
            this.enabled = true;
            AvailablePart intakePart = PartLoader.getPartInfoByName("CircularIntake");

            if (intakePart != null)
            {
                if (intakePart.partPrefab.FindModulesImplementing <AtmosphericIntake>().Count <= 0 && PartLoader.Instance.IsReady())
                {
                    plugin_init = false;
                }
            }

            if (!resources_configured)
            {
                // read WarpPluginSettings.cfg
                ConfigNode plugin_settings = GameDatabase.Instance.GetConfigNode("WarpPlugin/WarpPluginSettings/WarpPluginSettings");
                if (plugin_settings != null)
                {
                    if (plugin_settings.HasValue("PartTechUpgrades"))
                    {
                        PartTechUpgrades = new Dictionary <string, string>();

                        string   rawstring   = plugin_settings.GetValue("PartTechUpgrades");
                        string[] splitValues = rawstring.Split(',').Select(sValue => sValue.Trim()).ToArray();

                        int pairs       = splitValues.Length / 2;
                        int totalValues = splitValues.Length / 2 * 2;
                        for (int i = 0; i < totalValues; i += 2)
                        {
                            PartTechUpgrades.Add(splitValues[i], splitValues[i + 1]);
                        }

                        Debug.Log("[KSP Interstellar] Part Tech Upgrades set to: " + rawstring);
                    }
                    if (plugin_settings.HasValue("OrsResourceMappings"))
                    {
                        OrsResourceMappings = new Dictionary <string, string>();

                        string   rawstring   = plugin_settings.GetValue("OrsResourceMappings");
                        string[] splitValues = rawstring.Split(',').Select(sValue => sValue.Trim()).ToArray();

                        int pairs       = splitValues.Length / 2;
                        int totalValues = pairs * 2;
                        for (int i = 0; i < totalValues; i += 2)
                        {
                            OrsResourceMappings.Add(splitValues[i], splitValues[i + 1]);
                        }
                    }
                    if (plugin_settings.HasValue("RadiationMechanicsDisabled"))
                    {
                        PluginHelper._radiationMechanicsDisabled = bool.Parse(plugin_settings.GetValue("RadiationMechanicsDisabled"));
                        Debug.Log("[KSP Interstellar] Radiation Mechanics Disabled set to: " + PluginHelper.RadiationMechanicsDisabled.ToString());
                    }
                    if (plugin_settings.HasValue("ThermalMechanicsDisabled"))
                    {
                        PluginHelper._isThermalDissipationDisabled = bool.Parse(plugin_settings.GetValue("ThermalMechanicsDisabled"));
                        Debug.Log("[KSP Interstellar] ThermalMechanics set to : " + (!PluginHelper.IsThermalDissipationDisabled).ToString());
                    }
                    if (plugin_settings.HasValue("SolarPanelClampedHeating"))
                    {
                        PluginHelper._isPanelHeatingClamped = bool.Parse(plugin_settings.GetValue("SolarPanelClampedHeating"));
                        Debug.Log("[KSP Interstellar] Solar panels clamped heating set to enabled: " + PluginHelper.IsSolarPanelHeatingClamped.ToString());
                    }
                    if (plugin_settings.HasValue("RecieverTempTweak"))
                    {
                        PluginHelper._isRecieverTempTweaked = bool.Parse(plugin_settings.GetValue("RecieverTempTweak"));
                        Debug.Log("[KSP Interstellar] Microwave reciever CoreTemp tweak is set to enabled: " + PluginHelper.IsRecieverCoreTempTweaked.ToString());
                    }
                    if (plugin_settings.HasValue("LimitedWarpTravel"))
                    {
                        PluginHelper._limitedWarpTravel = bool.Parse(plugin_settings.GetValue("LimitedWarpTravel"));
                        Debug.Log("[KSP Interstellar] Apply Limited Warp Travel: " + PluginHelper.LimitedWarpTravel.ToString());
                    }
                    if (plugin_settings.HasValue("MatchDemandWithSupply"))
                    {
                        PluginHelper._matchDemandWithSupply = bool.Parse(plugin_settings.GetValue("MatchDemandWithSupply"));
                        Debug.Log("[KSP Interstellar] Match Demand With Supply: " + PluginHelper.MatchDemandWithSupply.ToString());
                    }
                    if (plugin_settings.HasValue("MaxPowerDrawForExoticMatterMult"))
                    {
                        PluginHelper._maxPowerDrawForExoticMatterMult = float.Parse(plugin_settings.GetValue("MaxPowerDrawForExoticMatterMult"));
                        Debug.Log("[KSP Interstellar] Max Power Draw For Exotic Matter Multiplier set to: " + PluginHelper.MaxPowerDrawForExoticMatterMult.ToString("0.000000"));
                    }
                    if (plugin_settings.HasValue("GravityConstant"))
                    {
                        PluginHelper._gravityConstant = Single.Parse(plugin_settings.GetValue("GravityConstant"));
                        Debug.Log("[KSP Interstellar] Gravity constant set to: " + PluginHelper.GravityConstant.ToString("0.000000"));
                    }
                    if (plugin_settings.HasValue("IspCoreTempMult"))
                    {
                        PluginHelper._ispCoreTempMult = double.Parse(plugin_settings.GetValue("IspCoreTempMult"));
                        Debug.Log("[KSP Interstellar] Isp core temperature multiplier set to: " + PluginHelper.IspCoreTempMult.ToString("0.000000"));
                    }
                    if (plugin_settings.HasValue("ElectricEngineIspMult"))
                    {
                        PluginHelper._electricEngineIspMult = double.Parse(plugin_settings.GetValue("ElectricEngineIspMult"));
                        Debug.Log("[KSP Interstellar] Electric EngineIsp Multiplier set to: " + PluginHelper.ElectricEngineIspMult.ToString("0.000000"));
                    }



                    if (plugin_settings.HasValue("GlobalThermalNozzlePowerMaxTrustMult"))
                    {
                        PluginHelper._globalThermalNozzlePowerMaxThrustMult = double.Parse(plugin_settings.GetValue("GlobalThermalNozzlePowerMaxTrustMult"));
                        Debug.Log("[KSP Interstellar] Maximum Global Thermal Power Maximum Thrust Multiplier set to: " + PluginHelper.GlobalThermalNozzlePowerMaxThrustMult.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("GlobalMagneticNozzlePowerMaxTrustMult"))
                    {
                        PluginHelper._globalMagneticNozzlePowerMaxThrustMult = double.Parse(plugin_settings.GetValue("GlobalMagneticNozzlePowerMaxTrustMult"));
                        Debug.Log("[KSP Interstellar] Maximum Global Magnetic Nozzle Power Maximum Thrust Multiplier set to: " + PluginHelper.GlobalMagneticNozzlePowerMaxThrustMult.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("GlobalElectricEnginePowerMaxTrustMult"))
                    {
                        PluginHelper._globalElectricEnginePowerMaxThrustMult = double.Parse(plugin_settings.GetValue("GlobalElectricEnginePowerMaxTrustMult"));
                        Debug.Log("[KSP Interstellar] Maximum Global Electric Engine Power Maximum Thrust Multiplier set to: " + PluginHelper.GlobalElectricEnginePowerMaxThrustMult.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("LfoFuelTrustModifier"))
                    {
                        PluginHelper._lfoFuelThrustModifier = double.Parse(plugin_settings.GetValue("LfoFuelTrustModifier"));
                        Debug.Log("[KSP Interstellar] Maximum Lfo Fuel Thrust Multiplier set to: " + PluginHelper.LfoFuelThrustModifier.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("MaxThermalNozzleIsp"))
                    {
                        PluginHelper._maxThermalNozzleIsp = float.Parse(plugin_settings.GetValue("MaxThermalNozzleIsp"));
                        Debug.Log("[KSP Interstellar] Maximum Thermal Nozzle Isp set to: " + PluginHelper.MaxThermalNozzleIsp.ToString("0.0"));
                    }

                    if (plugin_settings.HasValue("TrustCoreTempThreshold"))
                    {
                        PluginHelper._thrustCoreTempThreshold = double.Parse(plugin_settings.GetValue("TrustCoreTempThreshold"));
                        Debug.Log("[KSP Interstellar] Thrust core temperature threshold set to: " + PluginHelper.ThrustCoreTempThreshold.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("LowCoreTempBaseTrust"))
                    {
                        PluginHelper._lowCoreTempBaseThrust = double.Parse(plugin_settings.GetValue("LowCoreTempBaseTrust"));
                        Debug.Log("[KSP Interstellar] Low core temperature base thrust modifier set to: " + PluginHelper.LowCoreTempBaseThrust.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("HighCoreTempTrustMult"))
                    {
                        PluginHelper._highCoreTempThrustMult = double.Parse(plugin_settings.GetValue("HighCoreTempTrustMult"));
                        Debug.Log("[KSP Interstellar] High core temperature thrust divider set to: " + PluginHelper.HighCoreTempThrustMult.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("BasePowerConsumption"))
                    {
                        PluginHelper._basePowerConsumption = double.Parse(plugin_settings.GetValue("BasePowerConsumption"));
                        Debug.Log("[KSP Interstellar] Base Power Consumption set to: " + PluginHelper.BasePowerConsumption.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("PowerConsumptionMultiplier"))
                    {
                        PluginHelper._powerConsumptionMultiplier = double.Parse(plugin_settings.GetValue("PowerConsumptionMultiplier"));
                        Debug.Log("[KSP Interstellar] Base Power Consumption set to: " + PluginHelper.PowerConsumptionMultiplier.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("IspNtrPropellantModifierBase"))
                    {
                        PluginHelper._ispNtrPropellantModifierBase = float.Parse(plugin_settings.GetValue("IspNtrPropellantModifierBase"));
                        Debug.Log("[KSP Interstellar] Isp Ntr Propellant Modifier Base set to: " + PluginHelper.IspNtrPropellantModifierBase.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("IspElectroPropellantModifierBase"))
                    {
                        PluginHelper._ispElectroPropellantModifierBase = float.Parse(plugin_settings.GetValue("IspNtrPropellantModifierBase"));
                        Debug.Log("[KSP Interstellar] Isp Ntr Propellant Modifier Base set to: " + PluginHelper.IspElectroPropellantModifierBase.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("ElectricEnginePowerPropellantIspMultLimiter"))
                    {
                        PluginHelper._electricEnginePowerPropellantIspMultLimiter = float.Parse(plugin_settings.GetValue("ElectricEnginePowerPropellantIspMultLimiter"));
                        Debug.Log("[KSP Interstellar] Electric Engine Power Propellant IspMultiplier Limiter set to: " + PluginHelper.ElectricEnginePowerPropellantIspMultLimiter.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("ElectricEngineAtmosphericDensityTrustLimiter"))
                    {
                        PluginHelper._electricEngineAtmosphericDensityThrustLimiter = float.Parse(plugin_settings.GetValue("ElectricEngineAtmosphericDensityTrustLimiter"));
                        Debug.Log("[KSP Interstellar] Electric Engine Power Propellant IspMultiplier Limiter set to: " + PluginHelper.ElectricEngineAtmosphericDensityThrustLimiter.ToString("0.0"));
                    }

                    if (plugin_settings.HasValue("MaxAtmosphericAltitudeMult"))
                    {
                        PluginHelper._maxAtmosphericAltitudeMult = double.Parse(plugin_settings.GetValue("MaxAtmosphericAltitudeMult"));
                        Debug.Log("[KSP Interstellar] Maximum Atmospheric Altitude Multiplier set to: " + PluginHelper.MaxAtmosphericAltitudeMult.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("MinAtmosphericAirDensity"))
                    {
                        PluginHelper._minAtmosphericAirDensity = double.Parse(plugin_settings.GetValue("MinAtmosphericAirDensity"));
                        Debug.Log("[KSP Interstellar] Minimum Atmospheric Air Density set to: " + PluginHelper.MinAtmosphericAirDensity.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("JetUpgradeTech0"))
                    {
                        PluginHelper.JetUpgradeTech0 = plugin_settings.GetValue("JetUpgradeTech0");
                        Debug.Log("[KSP Interstellar] JetUpgradeTech0" + PluginHelper.JetUpgradeTech0);
                    }
                    if (plugin_settings.HasValue("JetUpgradeTech1"))
                    {
                        PluginHelper.JetUpgradeTech1 = plugin_settings.GetValue("JetUpgradeTech1");
                        Debug.Log("[KSP Interstellar] JetUpgradeTech1" + PluginHelper.JetUpgradeTech1);
                    }
                    if (plugin_settings.HasValue("JetUpgradeTech2"))
                    {
                        PluginHelper.JetUpgradeTech2 = plugin_settings.GetValue("JetUpgradeTech2");
                        Debug.Log("[KSP Interstellar] JetUpgradeTech2" + PluginHelper.JetUpgradeTech2);
                    }
                    if (plugin_settings.HasValue("JetUpgradeTech3"))
                    {
                        PluginHelper.JetUpgradeTech3 = plugin_settings.GetValue("JetUpgradeTech3");
                        Debug.Log("[KSP Interstellar] JetUpgradeTech3" + PluginHelper.JetUpgradeTech3);
                    }

                    resources_configured = true;
                }
                else
                {
                    showInstallationErrorMessage();
                }
            }

            if (plugin_init)
            {
                return;
            }

            gdb         = GameDatabase.Instance;
            plugin_init = true;

            List <AvailablePart> available_parts = PartLoader.LoadedPartsList;

            foreach (AvailablePart available_part in available_parts)
            {
                Part prefab_available_part = available_part.partPrefab;
                try
                {
                    if (prefab_available_part.Modules == null)
                    {
                        continue;
                    }

                    ModuleResourceIntake intake = prefab_available_part.FindModuleImplementing <ModuleResourceIntake>();

                    if (intake != null && intake.resourceName == "IntakeAir")
                    {
                        var pm = prefab_available_part.gameObject.AddComponent <AtmosphericIntake>();
                        prefab_available_part.Modules.Add(pm);
                        pm.area = intake.area;
                        //pm.aoaThreshold = intake.aoaThreshold;
                        pm.intakeTransformName = intake.intakeTransformName;
                        //pm.maxIntakeSpeed = intake.maxIntakeSpeed;
                        pm.unitScalar = intake.unitScalar;
                        //pm.useIntakeCompensation = intake.useIntakeCompensation;
                        //pm.storesResource = intake.storesResource;

                        PartResource intake_air_resource = prefab_available_part.Resources["IntakeAir"];

                        if (intake_air_resource != null && !prefab_available_part.Resources.Contains(InterstellarResourcesConfiguration.Instance.IntakeAtmosphere))
                        {
                            ConfigNode node = new ConfigNode("RESOURCE");
                            node.AddValue("name", InterstellarResourcesConfiguration.Instance.IntakeAtmosphere);
                            node.AddValue("maxAmount", intake_air_resource.maxAmount);
                            node.AddValue("possibleAmount", intake_air_resource.amount);
                            prefab_available_part.AddResource(node);
                        }
                    }

                    if (prefab_available_part.FindModulesImplementing <ModuleDeployableSolarPanel>().Any())
                    {
                        var existingSolarControlModule = prefab_available_part.FindModuleImplementing <FNSolarPanelWasteHeatModule>();
                        if (existingSolarControlModule == null)
                        {
                            ModuleDeployableSolarPanel panel = prefab_available_part.FindModuleImplementing <ModuleDeployableSolarPanel>();
                            if (panel.chargeRate > 0)
                            {
                                //Type type = AssemblyLoader.GetClassByName(typeof(PartModule), "FNSolarPanelWasteHeatModule");
                                Type type = typeof(FNSolarPanelWasteHeatModule);
                                //if (type != null)
                                //{
                                FNSolarPanelWasteHeatModule pm = prefab_available_part.gameObject.AddComponent(type) as FNSolarPanelWasteHeatModule;
                                prefab_available_part.Modules.Add(pm);
                                //}
                            }

                            //if (!prefab_available_part.Resources.Contains("WasteHeat") && panel.chargeRate > 0)
                            //{
                            //    ConfigNode node = new ConfigNode("RESOURCE");
                            //    node.AddValue("name", "WasteHeat");
                            //    node.AddValue("maxAmount", panel.chargeRate * 100);
                            //    node.AddValue("possibleAmount", 0);

                            //    PartResource pr = prefab_available_part.AddResource(node);

                            //    if (available_part.resourceInfo != null && pr != null)
                            //    {
                            //        if (available_part.resourceInfo.Length == 0)
                            //            available_part.resourceInfo = pr.resourceName + ":" + pr.amount + " / " + pr.maxAmount;
                            //        else
                            //            available_part.resourceInfo = available_part.resourceInfo + "\n" + pr.resourceName + ":" + pr.amount + " / " + pr.maxAmount;
                            //    }
                            //}
                        }
                    }

                    if (prefab_available_part.FindModulesImplementing <ElectricEngineControllerFX>().Count() > 0)
                    {
                        available_part.moduleInfo = prefab_available_part.FindModulesImplementing <ElectricEngineControllerFX>().First().GetInfo();
                        available_part.moduleInfos.RemoveAll(modi => modi.moduleName == "Engine");
                        AvailablePart.ModuleInfo mod_info = available_part.moduleInfos.FirstOrDefault(modi => modi.moduleName == "Electric Engine Controller");

                        if (mod_info != null)
                        {
                            mod_info.moduleName = "Electric Engine";
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (prefab_available_part != null)
                    {
                        print("[KSP Interstellar] Exception caught adding to: " + prefab_available_part.name + " part: " + ex.ToString());
                    }
                    else
                    {
                        print("[KSP Interstellar] Exception caught adding to unknown module");
                    }
                }
            }
        }
Esempio n. 32
0
        private void AddResource(Part part, int id, string name, double rate, bool full)
        {
            try
            {
                if (!part.Resources.Contains(id))
                {
                    double max = part.CrewCapacity * rate * globalSettings.DefaultResourceAmount;
                    ConfigNode node = new ConfigNode("RESOURCE");
                    node.AddValue("name", name);
                    node.AddValue("maxAmount", max);

                    if (full)
                    {
                        node.AddValue("amount", max);
                    }
                    else
                    {
                        node.AddValue("amount", 0);
                    }

                    part.AddResource(node);
                }
            }
            catch (Exception ex)
            {
                this.LogError("Failed to add resource " + name + " to " + part.name + ": " + ex.Message + "\n" + ex.StackTrace);
            }
        }
Esempio n. 33
0
        private void ProcessResources(Part oPart, PartVariant oVariant)
        {
            string       sValue;
            double       dValue;
            double       dValue2;
            PartResource oResource;
            ConfigNode   oConfigNode;

            foreach (PartResourceDefinition oResourceDef in PartResourceLibrary.Instance.resourceDefinitions)
            {
                sValue = oVariant.GetExtraInfoValue("Resource/" + oResourceDef.name);

                if (!string.IsNullOrEmpty(sValue))
                {
                    oResource = oPart.Resources[oResourceDef.name];

                    if (oResource != null)
                    {
                        if (sValue.ToLower() == "none")
                        {
                            oPart.RemoveResource(oResource);
                        }
                        else if (double.TryParse(sValue, out dValue))
                        {
                            if (oResource.maxAmount == 0.0)
                            {
                                dValue2 = 0.0;
                            }
                            else
                            {
                                dValue2 = oResource.amount / oResource.maxAmount;
                            }

                            oResource.maxAmount = dValue;

                            if (HighLogic.LoadedSceneIsEditor)
                            {
                                oResource.amount = dValue * dValue2;
                            }
                        }
                    }
                    else if (double.TryParse(sValue, out dValue))
                    {
                        oConfigNode = new ConfigNode("RESOURCE");
                        oConfigNode.AddValue("name", oResourceDef.name);

                        if (HighLogic.LoadedSceneIsEditor)
                        {
                            oConfigNode.AddValue("amount", dValue);
                        }
                        else
                        {
                            oConfigNode.AddValue("amount", 0.0);
                        }

                        oConfigNode.AddValue("maxAmount", dValue);

                        oPart.AddResource(oConfigNode);
                    }
                }
            }
        }
Esempio n. 34
0
        public override void updateMultiMode(bool silentUpdate = false)
        {
            GTIDebug.Log(this.GetType().Name + " --> GTI_MultiModeIntake: updateMultiMode() --> Begin", iDebugLevel.High);
            Part currentPart = this.part;

            if (silentUpdate == false)
            {
                writeScreenMessage();
            }

            for (int i = 0; i < ModuleIntakes.Count; i++)
            {
                if (i == modes[selectedMode].moduleIndex)
                {
                    GTIDebug.Log("GTI_MultiMode (" + (silentUpdate ? "silent" : "non-silent") + "): Activate Module [" + modes[i].moduleIndex + "] --> " + ModuleIntakes[modes[i].moduleIndex].resourceName, iDebugLevel.High);
                    GTIDebug.Log("selectedMode Intake: " + selectedMode + "\tselectedModeStatus: " + selectedModeStatus);
                    if (selectedModeStatus)
                    {
                        GTIDebug.Log("Activating Intake Mode: " + modes[selectedMode].resourceName);
                        ModuleIntakes[i].intakeEnabled = true;
                    }
                    else
                    {
                        ModuleIntakes[i].intakeEnabled = false;
                    }
                    ModuleIntakes[i].enabled   = true;
                    ModuleIntakes[i].isEnabled = true;
                }
                else
                {
                    GTIDebug.Log("GTI_MultiMode (" + (silentUpdate ? "silent" : "non-silent") + "): Deactivate Module [" + modes[i].moduleIndex + "] --> " + ModuleIntakes[modes[i].moduleIndex].resourceName, iDebugLevel.High);
                    ModuleIntakes[i].enabled       = false;
                    ModuleIntakes[i].isEnabled     = false;     //=> FixedUpdate() will update status = "Closed" and exit
                    ModuleIntakes[i].intakeEnabled = false;
                }
            }
            this.Events["IntakeActivate"].active   = !selectedModeStatus;
            this.Events["IntakeDeactivate"].active = selectedModeStatus;

            #region Create new Resource node
            //Only handle resources if preservation is not activated
            if (!preserveResourceNodes)
            {
                //List<ConfigNode> IntakeResources = new List<ConfigNode>();
                ConfigNode IntakeResource = new ConfigNode("RESOURCE");
                float      resMaxAmount   = (float)ModuleIntakes[modes[selectedMode].moduleIndex].res.maxAmount;
                if (resMaxAmount <= 0)
                {
                    resMaxAmount = 1f;
                }
                float resIniAmount = HighLogic.LoadedSceneIsFlight ? 0f : resMaxAmount;

                //Create Resource node
                IntakeResource.AddValue("name", modes[selectedMode].resourceName);
                IntakeResource.AddValue("amount", resIniAmount);
                IntakeResource.AddValue("maxAmount", resMaxAmount);

                //All resource properties
                //partResource.amount = amount;
                //partResource.maxAmount = maxAmount;
                //partResource.flowState = flowState;
                //partResource.isTweakable = isTweakable;
                //partResource.hideFlow = hideFlow;
                //partResource.isVisible = isVisible;
                //partResource.flowMode = flow;


                //Clear all resources since I get null ref error when I do not do this
                //currentPart.Resources.Clear();
                bool preserveResource;
                // remove all target resources
                List <PartResource> resourcesDeleteList = new List <PartResource>();
                foreach (PartResource resource in currentPart.Resources)
                {
                    preserveResource = true;
                    GTIDebug.Log("Check for resource removal: " + resource.resourceName, iDebugLevel.DebugInfo);
                    for (int j = 0; j < modes.Count; j++)
                    {
                        if (modes[j].resourceName == resource.resourceName)
                        {
                            //Remove resources managed by this mod
                            preserveResource = false;
                            break;
                        }
                    }
                    if (!preserveResource)
                    {
                        GTIDebug.Log("Removing Resource: " + resource.resourceName, iDebugLevel.DebugInfo);
                        //if (currentPart.Resources.Remove(resource)) GTIDebug.Log("Resource removed: " + GetResourceID(resource.resourceName), iDebugLevel.DebugInfo);
                        resourcesDeleteList.Add(resource);
                    }
                }
                foreach (var resource in resourcesDeleteList)
                {
                    if (currentPart.Resources.Remove(resource))
                    {
                        GTIDebug.Log("Resource removed: " + GetResourceID(resource.resourceName), iDebugLevel.DebugInfo);
                    }
                }
                resourcesDeleteList = null;

                //Add the resources
                GTIDebug.Log("MultiModeIntake: Add Resource\n" + IntakeResource.ToString(), iDebugLevel.DebugInfo);
                currentPart.AddResource(IntakeResource);
                //IntakeResource.ClearNodes();
                //IntakeResource.ClearValues();

                GTIDebug.Log("Listing resources defined in part", iDebugLevel.DebugInfo);
                if (DebugLevel == iDebugLevel.DebugInfo)
                {
                    for (int i = 0; i < currentPart.Resources.Count; i++)
                    {
                        GTIDebug.Log("currentPart.Resources[" + i + "].resourceName: " + currentPart.Resources[i].resourceName + " \t" + currentPart.Resources[i].maxAmount, iDebugLevel.DebugInfo);
                    }
                }
            }
            #endregion

            try
            { if (HighLogic.LoadedSceneIsFlight && !silentUpdate)
              {
                  KSP.UI.Screens.ResourceDisplay.Instance.Refresh();
              }
            }
            catch { GTIDebug.LogError("Update resource panel failed."); }
        }
Esempio n. 35
0
        private void AddResource(Part part, int id, string name, double rate, bool full)
        {
            try
            {
                if (!part.Resources.Contains(id))
                {
                    double max = part.CrewCapacity * rate * settings.DefaultResourceAmount;
                    ConfigNode node = new ConfigNode("RESOURCE");
                    node.AddValue("name", name);
                    node.AddValue("maxAmount", max);

                    if (full)
                    {
                        node.AddValue("amount", max);
                    }
                    else
                    {
                        node.AddValue("amount", 0);
                    }

                    part.AddResource(node);
                }
            }
            catch (Exception ex)
            {
                Debug.LogError("TAC Life Support (AddLifeSupport) [" + this.GetInstanceID().ToString("X") + "][" + Time.time
                    + "]: Failed to add resource " + name + " to " + part.name + ": " + ex.Message + "\n" + ex.StackTrace);
            }
        }