Esempio n. 1
0
        public KCT_BuildListVessel(ShipConstruct s, String ls, double bP, String flagURL)
        {
            ship = s;
            shipNode = s.SaveShip();
            shipName = s.shipName;
            //Get total ship cost
            float dry, fuel;
            s.GetShipCosts(out dry, out fuel);
            cost = dry + fuel;
            TotalMass = 0;
            foreach (Part p in s.Parts)
            {
                TotalMass += p.mass;
                TotalMass += p.GetResourceMass();
            }

            launchSite = ls;
            buildPoints = bP;
            progress = 0;
            flag = flagURL;
            if (launchSite == "LaunchPad")
                type = ListType.VAB;
            else
                type = ListType.SPH;
            InventoryParts = new Dictionary<string, int>();
            id = Guid.NewGuid();
            cannotEarnScience = false;
        }
Esempio n. 2
0
        public KCT_BuildListVessel(ShipConstruct s, String ls, double bP, String flagURL)
        {
            ship     = s;
            shipNode = s.SaveShip();
            shipName = s.shipName;
            //Get total ship cost
            float fuel;

            cost      = s.GetShipCosts(out emptyCost, out fuel);
            TotalMass = s.GetShipMass(out emptyMass, out fuel);

            launchSite  = ls;
            buildPoints = bP;
            progress    = 0;
            flag        = flagURL;
            if (s.shipFacility == EditorFacility.VAB)
            {
                type = ListType.VAB;
            }
            else if (s.shipFacility == EditorFacility.SPH)
            {
                type = ListType.SPH;
            }
            else
            {
                type = ListType.None;
            }
            InventoryParts    = new Dictionary <string, int>();
            id                = Guid.NewGuid();
            cannotEarnScience = false;
        }
Esempio n. 3
0
        public KCT_BuildListVessel(ShipConstruct s, String ls, double bP, String flagURL)
        {
            ship     = s;
            shipNode = s.SaveShip();
            shipName = s.shipName;
            //Get total ship cost
            float dry, fuel;

            s.GetShipCosts(out dry, out fuel);
            cost      = dry + fuel;
            TotalMass = 0;
            foreach (Part p in s.Parts)
            {
                TotalMass += p.mass;
                TotalMass += p.GetResourceMass();
            }

            launchSite  = ls;
            buildPoints = bP;
            progress    = 0;
            flag        = flagURL;
            if (launchSite == "LaunchPad")
            {
                type = ListType.VAB;
            }
            else
            {
                type = ListType.SPH;
            }
            InventoryParts    = new Dictionary <string, int>();
            id                = Guid.NewGuid();
            cannotEarnScience = false;
        }
Esempio n. 4
0
        public KCT_BuildListVessel(ShipConstruct s, String ls, double bP, String flagURL)
        {
            ship     = s;
            shipNode = s.SaveShip();
            shipName = s.shipName;
            //Get total ship cost
            float dry, fuel;

            s.GetShipCosts(out dry, out fuel);
            cost = dry + fuel;

            launchSite  = ls;
            buildPoints = bP;
            progress    = 0;
            flag        = flagURL;
            if (launchSite == "LaunchPad")
            {
                type = ListType.VAB;
            }
            else
            {
                type = ListType.SPH;
            }
            InventoryParts    = new List <string>();
            id                = Guid.NewGuid();
            cannotEarnScience = false;
        }
Esempio n. 5
0
        public KCT_BuildListVessel(ShipConstruct s, String ls, double bP, String flagURL)
        {
            ship     = s;
            shipNode = s.SaveShip();
            shipName = s.shipName;
            //Get total ship cost
            float fuel;

            cost      = s.GetShipCosts(out emptyCost, out fuel);
            TotalMass = s.GetShipMass(out emptyMass, out fuel);

            HashSet <int> stages = new HashSet <int>();

            numStageParts = 0;
            stagePartCost = 0d;
            foreach (Part p in s.Parts)
            {
                if (p.stagingOn)
                {
                    stages.Add(p.inverseStage);
                    ++numStageParts;
                    stagePartCost += p.GetModuleCosts(p.partInfo.cost, ModifierStagingSituation.CURRENT) + p.partInfo.cost;
                }
            }
            numStages = stages.Count;

            launchSite  = ls;
            buildPoints = bP;
            progress    = 0;
            flag        = flagURL;
            if (s.shipFacility == EditorFacility.VAB)
            {
                type = ListType.VAB;
            }
            else if (s.shipFacility == EditorFacility.SPH)
            {
                type = ListType.SPH;
            }
            else
            {
                type = ListType.None;
            }
            id = Guid.NewGuid();
            cannotEarnScience = false;

            //get the crew from the editorlogic
            DesiredManifest = new List <string>();
            if (CrewAssignmentDialog.Instance?.GetManifest()?.CrewCount > 0)
            {
                foreach (ProtoCrewMember crew in CrewAssignmentDialog.Instance.GetManifest().GetAllCrew(true) ?? new List <ProtoCrewMember>())
                {
                    DesiredManifest.Add(crew?.name ?? string.Empty);
                }
            }
        }
Esempio n. 6
0
        float CalcVesselCosts(Vessel v)
        {
            ShipConstruct sc = new ShipConstruct();

            foreach (Part p in v.parts)
            {
                sc.parts.Add(p);
            }
            float drycost, fuelcost;
            float shipCost = sc.GetShipCosts(out drycost, out fuelcost);

            return(shipCost);
        }
Esempio n. 7
0
        public KCT_BuildListVessel(ShipConstruct s, String ls, double bP, String flagURL)
        {
            ship = s;
            shipNode = s.SaveShip();
            shipName = s.shipName;
            //Get total ship cost
            float dry, fuel;
            s.GetShipCosts(out dry, out fuel);
            cost = dry + fuel;

            launchSite = ls;
            buildPoints = bP;
            progress = 0;
            flag = flagURL;
            if (launchSite == "LaunchPad")
                type = ListType.VAB;
            else
                type = ListType.SPH;
            InventoryParts = new List<string>();
            id = Guid.NewGuid();
            cannotEarnScience = false;
        }
Esempio n. 8
0
        public KCT_BuildListVessel(ShipConstruct s, String ls, double bP, String flagURL)
        {
            ship = s;
            shipNode = s.SaveShip();
            shipName = s.shipName;
            //Get total ship cost
            float fuel;
            cost = s.GetShipCosts(out emptyCost, out fuel);
            TotalMass = s.GetShipMass(out emptyMass, out fuel);

            launchSite = ls;
            buildPoints = bP;
            progress = 0;
            flag = flagURL;
            if (s.shipFacility == EditorFacility.VAB)
                type = ListType.VAB;
            else if (s.shipFacility == EditorFacility.SPH)
                type = ListType.SPH;
            else
                type = ListType.None;
            InventoryParts = new Dictionary<string, int>();
            id = Guid.NewGuid();
            cannotEarnScience = false;
        }
Esempio n. 9
0
        public BuildListVessel(ShipConstruct s, string ls, double effCost, double bP, string flagURL)
        {
            _ship     = s;
            ShipNode  = s.SaveShip();
            ShipName  = s.shipName;
            Cost      = s.GetShipCosts(out EmptyCost, out _);
            TotalMass = s.GetShipMass(true, out EmptyMass, out _);

            HashSet <int> stages = new HashSet <int>();

            NumStageParts = 0;
            StagePartCost = 0d;

            foreach (Part p in s.Parts)
            {
                if (p.stagingOn)
                {
                    stages.Add(p.inverseStage);
                    ++NumStageParts;
                    StagePartCost += p.GetModuleCosts(p.partInfo.cost, ModifierStagingSituation.CURRENT) + p.partInfo.cost;
                }
            }
            NumStages = stages.Count;

            LaunchSite    = ls;
            EffectiveCost = effCost;
            BuildPoints   = bP;
            Progress      = 0;
            Flag          = flagURL;
            if (s.shipFacility == EditorFacility.VAB)
            {
                Type = ListType.VAB;
            }
            else if (s.shipFacility == EditorFacility.SPH)
            {
                Type = ListType.SPH;
            }
            else
            {
                Type = ListType.None;
            }
            Id = Guid.NewGuid();
            CannotEarnScience = false;

            //get the crew from the editorlogic
            DesiredManifest = new List <string>();
            if (CrewAssignmentDialog.Instance?.GetManifest()?.CrewCount > 0)
            {
                foreach (ProtoCrewMember crew in CrewAssignmentDialog.Instance.GetManifest().GetAllCrew(true) ?? new List <ProtoCrewMember>())
                {
                    DesiredManifest.Add(crew?.name ?? string.Empty);
                }
            }

            if (EffectiveCost == default)
            {
                // Can only happen in older saves that didn't have Effective cost persisted as a separate field
                // This code should be safe to remove after a while.
                EffectiveCost = Utilities.GetEffectiveCost(ShipNode.GetNodes("PART").ToList());
            }

            IntegrationPoints = MathParser.ParseIntegrationTimeFormula(this);
            IntegrationCost   = (float)MathParser.ParseIntegrationCostFormula(this);
        }
Esempio n. 10
0
        protected void drawEmptyBay()
        {
            ShipConstruct ship     = EditorLogic.fetch.ship;
            Color         oldColor = GUI.backgroundColor;

            if (ship.parts.Count > 0)
            {
                GUILayout.FlexibleSpace();
                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();

                //If the new integration button is pressed then record the info we need
                //to add editor bay data to the database.
                GUI.backgroundColor = XKCDColors.ColorTranslator.FromHtml("#97f5ff");
                if (GUILayout.Button(newIcon, buttonOptions))
                {
                    //Set up a new vehicle integration
                    editorBayItem.Clear();
                    editorBayItem.vesselName = ship.shipName;

                    //Generate snapshot of the vessel
                    ConfigNode shipNode = ship.SaveShip();
                    editorBayItem.vesselFilePath = savesFolder + ship.shipName + isVAB + editorBayItem.editorBayID + ".cfg";
                    debugLog("Vessel file: " + editorBayItem.vesselFilePath);
                    if (File.Exists(editorBayItem.vesselFilePath))
                    {
                        File.Delete(editorBayItem.vesselFilePath);
                    }
                    shipNode.Save(editorBayItem.vesselFilePath);
                    editorBayItem.vesselThumbnail = null;

                    float dryCost, fuelCost;
                    ship.GetShipCosts(out dryCost, out fuelCost);
                    editorBayItem.rushJobCost = dryCost;
                    calculateReliability(editorBayItem, ship);
                    editorBayItem.totalVesselParts = ship.parts.Count;

                    //Generate thumbnail
                    ShipConstruction.CaptureThumbnail(ship, "thumbs", thumbnailBaseFileName + ship.shipName);

                    //Generate the full path to the thumbnail and add it to the editorBayItem
                    editorBayItem.thumbnailPath = thumbnailFullPath + ship.shipName + ".png";

                    //Add workers
                    int availableWorkers = BARISScenario.Instance.GetAvailableWorkers(isVAB);
                    if (availableWorkers >= BARISScenario.MaxWorkersPerBay)
                    {
                        editorBayItem.workerCount = BARISScenario.MaxWorkersPerBay;
                        availableWorkers         -= editorBayItem.workerCount;
                        BARISScenario.Instance.SetAvailableWorkers(availableWorkers, isVAB);
                    }
                    else
                    {
                        editorBayItem.workerCount = availableWorkers;
                        BARISScenario.Instance.SetAvailableWorkers(0, isVAB);
                    }

                    //Generate a KAC alarm (if KAC is installed)
                    setKACAlarm(editorBayItem);

                    //Save the new item
                    BARISScenario.Instance.SetEditorBay(editorBayItem);
                    GamePersistence.SaveGame("persistent", HighLogic.SaveFolder, SaveMode.BACKUP);

                    //Cleanup
                    debugLog(editorBayItem.ToString());
                }
                newIcon             = selectNewIcon();
                GUI.backgroundColor = oldColor;

                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();
                GUILayout.FlexibleSpace();

                //Tooltip
                if (string.IsNullOrEmpty(newToolTip) == false)
                {
                    GUILayout.Label(newToolTip);
                }
                else
                {
                    GUILayout.Label(" ");
                }
            }
        }
Esempio n. 11
0
		/// <summary>
		/// Fires when a new vessel is created at the launch pad.
		/// </summary>
		/// <param name="ship">The ship being rolled out.</param>
		public void vesselRolloutEvent(ShipConstruct ship)
		{
			BeanCounter.LogFormatted_DebugOnly("------------- vesselRolloutEvent -------------");

			float dryCost, fuelCost, totalCost;
			totalCost = ship.GetShipCosts (out dryCost, out fuelCost);

			BeanCounter.LogFormatted_DebugOnly("Rollout: {0}", ship.shipName);
			BeanCounter.LogFormatted_DebugOnly("launchID: {0}", HighLogic.fetch.currentGame.launchID);

			Vessel vessel = FlightGlobals.ActiveVessel;
			BeanCounter.LogFormatted_DebugOnly("NEW VESSEL LAUNCH DETECTED: {0}", vessel.vesselName);
			
			BCLaunchData launch = new BCLaunchData(true);
			launch.vesselName = vessel.vesselName;
			launch.missionID = BCUtils.GetVesselMissionID(vessel);
			launch.dryCost = dryCost;
			launch.totalCost = totalCost;
			launch.launchTime = vessel.launchTime;

			// TODO move this to utils?
			List<BCVesselResourceData> resources = new List<BCVesselResourceData>();
			List<BCVesselPartData> parts = new List<BCVesselPartData>();
			float total_resource_cost = 0;
			
            // Iterate over each part so we can log the parts, calculate the vessel resources, and
            // calculate the actual cost of everything
			foreach (Part part in vessel.parts)
			{
				BCVesselPartData part_data = new BCVesselPartData();
				part_data.partName = part.partInfo.name;
				
				float part_full_cost = part.partInfo.cost;
				float part_resource_cost_full = 0;
				float part_resource_cost_actual = 0;
				
				foreach (PartResource res in part.Resources)
				{
					if (res.info.unitCost == 0 || res.amount == 0)
					{
						// Don't need to keep track of free resources
						// Or maybe we should, in case the cost changes due to a mod/game update?
						continue;
					}
					
					part_resource_cost_full += (float)(res.info.unitCost * res.maxAmount);
					part_resource_cost_actual += (float)(res.info.unitCost * res.amount);
					
                    // Either create a new VesselResourceData, or add to the one we already have
                    // TODO perhaps this should be conbined in to a single static method on BCVesselResourceData?
					BCVesselResourceData vr = resources.Find(r => r.resourceName == res.resourceName);
					if (vr == null)
					{
						resources.Add(new BCVesselResourceData(res.info, res.resourceName, res.amount, res.maxAmount));
					}
					else
					{
						vr.Add(res);
					}
				}
				
				float part_dry_cost = part_full_cost - part_resource_cost_full;
				part_data.baseCost = part_dry_cost;
				part_data.moduleCosts = part.GetModuleCosts();
				part_data.status = BCVesselPartStatus.Active;
				part_data.uid = part.flightID;
				parts.Add(part_data);

				total_resource_cost += part_resource_cost_actual;
			}
			
			launch.resources = resources;
			launch.parts = parts;
			launch.resourceCost = total_resource_cost;
			OATBeanCounterData.data.launches.Add(launch);

            // Try to match this to the transaction
            BCTransactionData transaction =
                (from trans in OATBeanCounterData.data.transactions
                 where trans.time == HighLogic.CurrentGame.UniversalTime
                 && trans.reason == TransactionReasons.VesselRollout
                 select trans).SingleOrDefault();
            if (transaction != null)
            {
                BeanCounter.LogFormatted_DebugOnly("Found matching transaction for this rollout: {0}", transaction.id);
                launch.transactionID = transaction.id;
                transaction.dataID = launch.id;
            }

			BeanCounter.LogFormatted_DebugOnly("------------ /vesselRolloutEvent -------------");
		}
Esempio n. 12
0
        void SpawnVessel(VesselData vesselData)
        {
            string gameDataDir = KSPUtil.ApplicationRootPath;

            vesselData.orbit     = vessel.GetOrbit();
            vesselData.orbit.vel = vessel.orbit.vel;
            vesselData.orbit.meanAnomalyAtEpoch = vesselData.orbit.meanAnomalyAtEpoch + Math.Atan(UnityEngine.Random.Range(200, 300) / vesselData.orbit.semiMajorAxis);
            ConfigNode[]  partNodes;
            ShipConstruct shipConstruct = null;
            float         lcHeight      = 0;
            ConfigNode    craftNode;
            ConfigNode    currentShip = ShipConstruction.ShipConfig;

            shipConstruct = ShipConstruction.LoadShip(vesselData.craftURL);
            float dryCost = 0;
            float cost    = 0;

            shipConstruct.GetShipCosts(out dryCost, out cost);
            cost = cost + dryCost;
            if (cost > Funding.Instance.Funds)
            {
                foreach (var p in FindObjectsOfType <Part>())
                {
                    if (!p.vessel)
                    {
                        Destroy(p.gameObject);
                    }
                }
                ScreenMessages.PostScreenMessage("not enought funds", 5.0f, ScreenMessageStyle.UPPER_CENTER);
                return;
            }
            craftNode = ConfigNode.Load(vesselData.craftURL);
            lcHeight  = ConfigNode.ParseVector3(craftNode.GetNode("PART").GetValue("pos")).y;
            ShipConstruction.ShipConfig = currentShip;
            vesselData.name             = shipConstruct.shipName;

            uint missionID = (uint)Guid.NewGuid().GetHashCode();
            uint launchID  = HighLogic.CurrentGame.launchID++;

            foreach (Part p in shipConstruct.parts)
            {
                p.missionID   = missionID;
                p.launchID    = launchID;
                p.flightID    = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState);
                p.temperature = 1.0;
            }
            ConfigNode  empty       = new ConfigNode();
            ProtoVessel dummyProto  = new ProtoVessel(empty, null);
            Vessel      dummyVessel = new Vessel();

            dummyVessel.parts    = shipConstruct.parts;
            dummyProto.vesselRef = dummyVessel;

            foreach (Part p in shipConstruct.parts)
            {
                dummyProto.protoPartSnapshots.Add(new ProtoPartSnapshot(p, dummyProto));
            }
            foreach (ProtoPartSnapshot p in dummyProto.protoPartSnapshots)
            {
                p.storePartRefs();
            }
            List <ConfigNode> partNodesL = new List <ConfigNode>();

            foreach (var snapShot in dummyProto.protoPartSnapshots)
            {
                ConfigNode node = new ConfigNode("PART");
                snapShot.Save(node);
                partNodesL.Add(node);
            }
            partNodes = partNodesL.ToArray();
            ConfigNode[] additionalNodes = new ConfigNode[0];
            ConfigNode   protoVesselNode = ProtoVessel.CreateVesselNode(vesselData.name, VesselType.Ship, vesselData.orbit, 0, partNodes, additionalNodes);
            ProtoVessel  protoVessel     = HighLogic.CurrentGame.AddVessel(protoVesselNode);

            vesselData.id = protoVessel.vesselRef.id;
            protoVessel.vesselRef.Load();
            Funding.Instance.AddFunds(-cost, TransactionReasons.Vessels);
            ScreenMessages.PostScreenMessage("vessel buy !", 5.0f, ScreenMessageStyle.UPPER_CENTER);
            foreach (var p in FindObjectsOfType <Part>())
            {
                if (!p.vessel)
                {
                    Destroy(p.gameObject);
                }
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Fires when a new vessel is created at the launch pad.
        /// </summary>
        /// <param name="ship">The ship being rolled out.</param>
        public void vesselRolloutEvent(ShipConstruct ship)
        {
            BeanCounter.LogFormatted_DebugOnly("------------- vesselRolloutEvent -------------");

            float dryCost, fuelCost, totalCost;

            totalCost = ship.GetShipCosts(out dryCost, out fuelCost);

            BeanCounter.LogFormatted_DebugOnly("Rollout: {0}", ship.shipName);
            BeanCounter.LogFormatted_DebugOnly("launchID: {0}", HighLogic.fetch.currentGame.launchID);

            Vessel vessel = FlightGlobals.ActiveVessel;

            BeanCounter.LogFormatted_DebugOnly("NEW VESSEL LAUNCH DETECTED: {0}", vessel.vesselName);

            BCLaunchData launch = new BCLaunchData(true);

            launch.vesselName = vessel.vesselName;
            launch.missionID  = BCUtils.GetVesselMissionID(vessel);
            launch.dryCost    = dryCost;
            launch.totalCost  = totalCost;
            launch.launchTime = vessel.launchTime;

            // TODO move this to utils?
            List <BCVesselResourceData> resources = new List <BCVesselResourceData>();
            List <BCVesselPartData>     parts     = new List <BCVesselPartData>();
            float total_resource_cost             = 0;

            // Iterate over each part so we can log the parts, calculate the vessel resources, and
            // calculate the actual cost of everything
            foreach (Part part in vessel.parts)
            {
                BCVesselPartData part_data = new BCVesselPartData();
                part_data.partName = part.partInfo.name;

                float part_full_cost            = part.partInfo.cost;
                float part_resource_cost_full   = 0;
                float part_resource_cost_actual = 0;

                foreach (PartResource res in part.Resources)
                {
                    if (res.info.unitCost == 0 || res.amount == 0)
                    {
                        // Don't need to keep track of free resources
                        // Or maybe we should, in case the cost changes due to a mod/game update?
                        continue;
                    }

                    part_resource_cost_full   += (float)(res.info.unitCost * res.maxAmount);
                    part_resource_cost_actual += (float)(res.info.unitCost * res.amount);

                    // Either create a new VesselResourceData, or add to the one we already have
                    // TODO perhaps this should be conbined in to a single static method on BCVesselResourceData?
                    BCVesselResourceData vr = resources.Find(r => r.resourceName == res.resourceName);
                    if (vr == null)
                    {
                        resources.Add(new BCVesselResourceData(res.info, res.resourceName, res.amount, res.maxAmount));
                    }
                    else
                    {
                        vr.Add(res);
                    }
                }

                float part_dry_cost = part_full_cost - part_resource_cost_full;
                part_data.baseCost    = part_dry_cost;
                part_data.moduleCosts = part.GetModuleCosts();
                part_data.status      = BCVesselPartStatus.Active;
                part_data.uid         = part.flightID;
                parts.Add(part_data);

                total_resource_cost += part_resource_cost_actual;
            }

            launch.resources    = resources;
            launch.parts        = parts;
            launch.resourceCost = total_resource_cost;
            OATBeanCounterData.data.launches.Add(launch);

            // Try to match this to the transaction
            BCTransactionData transaction =
                (from trans in OATBeanCounterData.data.transactions
                 where trans.time == HighLogic.CurrentGame.UniversalTime &&
                 trans.reason == TransactionReasons.VesselRollout
                 select trans).SingleOrDefault();

            if (transaction != null)
            {
                BeanCounter.LogFormatted_DebugOnly("Found matching transaction for this rollout: {0}", transaction.id);
                launch.transactionID = transaction.id;
                transaction.dataID   = launch.id;
            }

            BeanCounter.LogFormatted_DebugOnly("------------ /vesselRolloutEvent -------------");
        }
 public void VesselAssembled(Vessel vessel, ShipConstruct construct)
 {
     System.CurrentShipCost = new Tuple <Guid, float>(vessel.id, construct.GetShipCosts(out _, out _));
 }
        void OnVesselLaunched(ShipConstruct vVessel)
        {
            if (vVessel == null) return;
            if (EditorLogic.fetch.launchSiteName == null) return;

            PersistenceUtils.savePersistenceBackup();

            if (EditorLogic.fetch.launchSiteName == "Runway") return;
            if (EditorLogic.fetch.launchSiteName == "LaunchPad") return;
            if (EditorLogic.fetch.launchSiteName == "KSC") return;

            /* StaticObject soTemp = null;

            foreach (StaticObject soThis in KerbalKonstructs.instance.getStaticDB().getAllStatics())
            {
                if (soThis.getSetting("LaunchSiteName") == null)
                    continue;
                else
                    if ((string)soThis.getSetting("LaunchSiteName") == (string)EditorLogic.fetch.launchSiteName)
                    {
                        soTemp = soThis;
                        break;
                    }
            } */

            // Don't know why newly created launchsites don't appear without a restart of KSP still.
            // This doesn't seem to help.
            /* if (soTemp != null)
            {
                if (DebugMode) Debug.Log("KK: Got launchsite gameobject" + (string)EditorLogic.fetch.launchSiteName);

                soTemp.SetActiveRecursively(soTemp.gameObject, true);
            } */

            if (MiscUtils.CareerStrategyEnabled(HighLogic.CurrentGame))
            {
                VesselLaunched = true;
                string sitename = EditorLogic.fetch.launchSiteName;

                float dryCost = 0f;
                float fuelCost = 0f;
                float total = vVessel.GetShipCosts(out dryCost, out fuelCost);

                var cm = CurrencyModifierQuery.RunQuery(TransactionReasons.VesselRollout, total, 0f, 0f);
                total += cm.GetEffectDelta(Currency.Funds);

                double launchcost = total;
                float fRefund = 0f;
                LaunchSiteManager.getSiteLaunchRefund((string)EditorLogic.fetch.launchSiteName, out fRefund);

                if (fRefund < 1) return;

                RefundAmount = (launchcost / 100) * fRefund;
                VesselCost = launchcost - (RefundAmount);
                if (fRefund > 0)
                {
                    string sMessage = "This launch normally costs " + launchcost.ToString("#0") +
                        " but " + sitename + " provides a " + fRefund + "% refund. \n\nSo " + RefundAmount.ToString("#0") + " funds has been credited to you. \n\nEnjoy and thanks for using " +
                        sitename + ". Have a safe flight.";
                    MiscUtils.PostMessage("Launch Refund", sMessage, MessageSystemButton.MessageButtonColor.GREEN, MessageSystemButton.ButtonIcons.ALERT);
                    Funding.Instance.AddFunds(RefundAmount, TransactionReasons.Cheating);
                }
            }
        }
        protected ProtoVessel CreateProtoVessel()
        {
            ProtoVessel   protoVessel = null;
            ShipConstruct construct   = null;
            Vessel        vessel      = null;

            try
            {
                // Backup the ship config from the VAB/SPH, load the selected .craft file
                //   and restore the cached config from the VAB/SPH
                var constructBak = ShipConstruction.ShipConfig;
                construct = ShipConstruction.LoadShip(_selectedCraftFilePath);
                ShipConstruction.ShipConfig = constructBak;

                // Calculate vessel cost and mass and generate a thumbnail
                construct.GetShipCosts(out _cachedFundsCost, out _);
                construct.GetShipMass(out _cachedDryMass, out _);
                _cachedThumbnail = _thumbnailService.GetThumbnail(construct);

                // Create an emtpy Vessel and copy the parts from the loaded .craft file
                vessel       = new GameObject().AddComponent <Vessel>();
                vessel.parts = construct.parts;

                // Create an empty ProtoVessel that we'll ultimately use to create the template
                //   for the vessel to be spawned in-game later
                protoVessel = new ProtoVessel(new ConfigNode(), null)
                {
                    vesselName = construct.shipName,
                    vesselRef  = vessel
                };

                // Setup necessary Vessel and Part parameters for the template (also check for launch clamps)
                var launchId  = HighLogic.CurrentGame.launchID++;
                var missionId = (uint)Guid.NewGuid().GetHashCode();
                var rootPart  = construct.parts.First();
                _hasLaunchClamp = false;
                foreach (var part in construct.parts)
                {
                    _hasLaunchClamp |= part.HasModuleImplementing <LaunchClamp>();

                    part.flagURL     = construct.missionFlag ?? HighLogic.CurrentGame.flagURL;
                    part.flightID    = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState);
                    part.launchID    = launchId;
                    part.missionID   = missionId;
                    part.temperature = Math.Abs(part.temperature);
                    part.UpdateOrgPosAndRot(rootPart);

                    part.vessel = vessel;
                    var partSnapshot = new ProtoPartSnapshot(part, protoVessel);
                    foreach (var resource in partSnapshot.resources)
                    {
                        if (resource.resourceName != "ElectricCharge")
                        {
                            resource.amount = 0d;
                        }
                    }
                    protoVessel.protoPartSnapshots.Add(partSnapshot);
                }
                foreach (var snapshot in protoVessel.protoPartSnapshots)
                {
                    snapshot.storePartRefs();
                }

                // Cache the ProtoVessel to use as the template for spawning the vessel later
                _cachedProtoVessel = protoVessel;
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
            }
            finally
            {
                // ShipConstruction.LoadShip seems to load in all the part meshes for the vessel
                //   (presumably for use in the VAB/SPH), so we need to destroy them
                if (construct != null && construct.parts != null && construct.parts.Count > 0)
                {
                    foreach (var part in construct.parts)
                    {
                        Destroy(part.gameObject);
                    }
                }
                // Destroy the temporary Vessel we created as well
                if (vessel != null)
                {
                    Destroy(vessel.gameObject);
                }
            }

            return(protoVessel);
        }
Esempio n. 17
0
        public static float CostOfSimulation(CelestialBody body, string simulationLength, ShipConstruct ship, int SimCount, bool landed)
        {
            if (simulationLength == "" || simulationLength == "-1")
                simulationLength = "31536000000"; //1000 Earth years
            CelestialBody Kerbin = Planetarium.fetch.Home;

            double length = MagiCore.Utilities.ParseTimeString(simulationLength, false);
            length = Math.Min(length, 31536000000.0);
            if (length == 0)
                length = 31536000000.0;
            if (length < 0) //An error while parsing the value
                return -1;
            Dictionary<string, string> vars = new Dictionary<string, string>();
            vars.Add("L", length.ToString()); //Sim length in seconds
            vars.Add("M", body.Mass.ToString()); //Body mass
            vars.Add("KM", Kerbin.Mass.ToString()); //Kerbin mass
            vars.Add("A", body.atmosphere ? "1" : "0"); //Presence of atmosphere
            vars.Add("S", (body != Planetarium.fetch.Sun && body.referenceBody != Planetarium.fetch.Sun) ? "1" : "0"); //Is a moon (satellite)

            float out1, out2;
            vars.Add("m", ship.GetTotalMass().ToString()); //Vessel loaded mass
            vars.Add("C", ship.GetShipCosts(out out1, out out2).ToString()); //Vessel loaded cost

            vars.Add("s", SimCount.ToString()); //Number of times simulated this editor session

            CelestialBody Parent = body;
            if (Parent != Planetarium.fetch.Sun)
            {
                while (Parent.referenceBody != Planetarium.fetch.Sun)
                {
                    Parent = Parent.referenceBody;
                }
            }
            double orbitRatio = 1;
            if (Parent.orbit != null)
            {
                if (Parent.orbit.semiMajorAxis >= Kerbin.orbit.semiMajorAxis)
                    orbitRatio = Parent.orbit.semiMajorAxis / Kerbin.orbit.semiMajorAxis;
                else
                    orbitRatio = Kerbin.orbit.semiMajorAxis / Parent.orbit.semiMajorAxis;
            }
            vars.Add("SMA", orbitRatio.ToString());
            vars.Add("PM", Parent.Mass.ToString());

            if ((body == Kerbin) && landed)
            {
                return (float)(KCT_MathParsing.GetStandardFormulaValue("KerbinSimCost", vars));
            }
            else
            {
                return (float)(KCT_MathParsing.GetStandardFormulaValue("SimCost", vars));
            }

            /*float timeMultiplier = 13;
            if (TimeMultipliers.ContainsKey(simulationLength))
                 timeMultiplier = TimeMultipliers[simulationLength];

            if (orbitBody == Planetarium.fetch.Sun)
                return 10000 * timeMultiplier;

            float atmosphereMult = orbitBody.atmosphere ? 1.1f : 1f;
            bool isMoon = orbitBody.referenceBody != Planetarium.fetch.Sun;
            CelestialBody Parent = orbitBody;
            while (Parent.referenceBody != Planetarium.fetch.Sun)
            {
                Parent = Parent.referenceBody;
            }

            CelestialBody Kerbin = GetBodyByName("Kerbin");
            if (Kerbin == null)
                Kerbin = GetBodyByName("Earth");

            double orbitRatio = 1;
            if (Parent.orbit.semiMajorAxis >= Kerbin.orbit.semiMajorAxis)
                orbitRatio = Parent.orbit.semiMajorAxis / Kerbin.orbit.semiMajorAxis;
            else
                orbitRatio = Kerbin.orbit.semiMajorAxis / Parent.orbit.semiMajorAxis;

            double cost = Math.Pow(orbitRatio,2) * 500 * (Parent.atmosphere ? 1.1 : 1);
            if (isMoon)
                cost *= atmosphereMult * 1.1;

            cost *= timeMultiplier;
            return (float)cost;*/
        }
Esempio n. 18
0
        public KCT_BuildListVessel(ShipConstruct s, String ls, double effCost, double bP, String flagURL)
        {
            ship     = s;
            shipNode = s.SaveShip();
            shipName = s.shipName;
            //Get total ship cost
            float fuel;

            cost      = s.GetShipCosts(out emptyCost, out fuel);
            TotalMass = s.GetShipMass(true, out emptyMass, out fuel);

            HashSet <int> stages = new HashSet <int>();

            numStageParts = 0;
            stagePartCost = 0d;
            //for (int i = s.Parts.Count - 1; i >= 0; i--)
            //{
            //    Part p = s.Parts[i];

            foreach (Part p in s.Parts)
            {
                if (p.stagingOn)
                {
                    stages.Add(p.inverseStage);
                    ++numStageParts;
                    stagePartCost += p.GetModuleCosts(p.partInfo.cost, ModifierStagingSituation.CURRENT) + p.partInfo.cost;
                }
            }
            numStages = stages.Count;

            launchSite    = ls;
            effectiveCost = effCost;
            buildPoints   = bP;
            progress      = 0;
            flag          = flagURL;
            if (s.shipFacility == EditorFacility.VAB)
            {
                type = ListType.VAB;
            }
            else if (s.shipFacility == EditorFacility.SPH)
            {
                type = ListType.SPH;
            }
            else
            {
                type = ListType.None;
            }
            id = Guid.NewGuid();
            cannotEarnScience = false;

            //get the crew from the editorlogic
            DesiredManifest = new List <string>();
            if (CrewAssignmentDialog.Instance?.GetManifest()?.CrewCount > 0)
            {
                //var pcm = CrewAssignmentDialog.Instance.GetManifest().GetAllCrew(true) ?? new List<ProtoCrewMember>();
                //for (int i = pcm.Count - 1; i >= 0; i--)
                //{
                //    ProtoCrewMember crew = pcm[i];
                foreach (ProtoCrewMember crew in CrewAssignmentDialog.Instance.GetManifest().GetAllCrew(true) ?? new List <ProtoCrewMember>())
                {
                    DesiredManifest.Add(crew?.name ?? string.Empty);
                }
            }

            if (effectiveCost == default(double))
            {
                // Can only happen in older saves that didn't have Effective cost persisted as a separate field
                // This code should be safe to remove after a while.
                effectiveCost = KCT_Utilities.GetEffectiveCost(shipNode.GetNodes("PART").ToList());
            }

            integrationPoints = KCT_MathParsing.ParseIntegrationTimeFormula(this);
            integrationCost   = (float)KCT_MathParsing.ParseIntegrationCostFormula(this);
        }
        void OnVesselLaunched(ShipConstruct vVessel)
        {
            if (DebugMode) Debug.Log("KK: OnVesselLaunched");

            if (!MiscUtils.CareerStrategyEnabled(HighLogic.CurrentGame))
            {
                return;
            }
            else
            {
                if (DebugMode) Debug.Log("KK: OnVesselLaunched is Career");

                PersistenceUtils.savePersistenceBackup();
                string sitename = EditorLogic.fetch.launchSiteName;

                if (sitename == "Runway") return;
                if (sitename == "LaunchPad") return;
                if (sitename == "KSC") return;
                if (sitename == "") return;

                LaunchSite lsSite = LaunchSiteManager.getLaunchSiteByName(sitename);
                float fMissionCount = lsSite.missioncount;
                lsSite.missioncount = fMissionCount + 1;

                double dSecs = HighLogic.CurrentGame.UniversalTime;

                double hours = dSecs / 60.0 / 60.0;
                double kHours = Math.Floor(hours % 6.0);
                double kMinutes = Math.Floor((dSecs / 60.0) % 60.0);
                double kSeconds = Math.Floor(dSecs % 60.0);
                double kYears = Math.Floor(hours / 2556.5402) + 1; // Kerbin year is 2556.5402 hours
                double kDays = Math.Floor(hours % 2556.5402 / 6.0) + 1;

                string sDate =  "Y" + kYears.ToString() + " D" + kDays.ToString() + " " + " " + kHours.ToString("00") + ":" + kMinutes.ToString("00") + ":" + kSeconds.ToString("00");

                string sCraft = vVessel.shipName;
                string sWeight = vVessel.GetTotalMass().ToString();
                string sLogEntry = lsSite.missionlog + sDate + ", Launched " + sCraft + ", Mass " +sWeight + " t|";
                lsSite.missionlog = sLogEntry;

                List<LaunchSite> sites = LaunchSiteManager.getLaunchSites();
                PersistenceFile<LaunchSite>.SaveList(sites, "LAUNCHSITES", "KK");

                VesselLaunched = true;

                float dryCost = 0f;
                float fuelCost = 0f;
                float total = vVessel.GetShipCosts(out dryCost, out fuelCost);

                var cm = CurrencyModifierQuery.RunQuery(TransactionReasons.VesselRollout, total, 0f, 0f);
                total += cm.GetEffectDelta(Currency.Funds);

                double launchcost = total;
                float fRefund = 0f;
                LaunchSiteManager.getSiteLaunchRefund((string)EditorLogic.fetch.launchSiteName, out fRefund);

                if (fRefund < 1) return;

                RefundAmount = (launchcost / 100) * fRefund;
                VesselCost = launchcost - (RefundAmount);
                if (fRefund > 0)
                {
                    string sMessage = "This launch normally costs " + launchcost.ToString("#0") +
                        " but " + sitename + " provides a " + fRefund + "% refund. \n\nSo " + RefundAmount.ToString("#0") + " funds has been credited to you. \n\nEnjoy and thanks for using " +
                        sitename + ". Have a safe flight.";
                    MiscUtils.PostMessage("Launch Refund", sMessage, MessageSystemButton.MessageButtonColor.GREEN, MessageSystemButton.ButtonIcons.ALERT);
                    Funding.Instance.AddFunds(RefundAmount, TransactionReasons.Cheating);
                }
            }
        }