Exemple #1
0
        private static IEnumerator parseProgressTree()
        {
            loaded = false;

            int timer = 0;

            while (ProgressTracking.Instance == null && timer < 500)
            {
                timer++;
                yield return(null);
            }

            if (timer >= 500)
            {
                Debug.Log("[Progress Tracking Parser] Progress Parser Timed Out");
                loaded = false;
                yield break;
            }

            while (timer < 10)
            {
                timer++;
                yield return(null);
            }

            bodySubTrees.Clear();
            standardNodes.Clear();
            intervalNodes.Clear();
            pointsOfInterest.Clear();

            loadIntervalNodes();
            loadStandardNodes();
            loadPOINodes();

            for (int i = 0; i < ProgressTracking.Instance.celestialBodyNodes.Length; i++)
            {
                CelestialBodySubtree b = ProgressTracking.Instance.celestialBodyNodes[i];

                loadNextBodyNode(b);
            }

            updateCompletionRecord();

            loaded = true;

            onProgressParsed.Fire();

            Debug.Log("[Progress Tracking Parser] Progress Nodes Loaded...");
        }
Exemple #2
0
        protected virtual bool perfomBiomeAnalysys()
        {
            //We need at least one crewmember in the lab.
            if (this.part.protoModuleCrew.Count == 0)
            {
                ScreenMessages.PostScreenMessage(kNoCrew, kMessageDuration, ScreenMessageStyle.UPPER_CENTER);
                return(false);
            }

            //We need at least one scientist in the lab.
            float scienceBonus = getBiomeAnalysisBonus();

            //We can run the analysis, add the science bonus
            if (scienceBonus > 0.0f)
            {
                if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER || HighLogic.CurrentGame.Mode == Game.Modes.SCIENCE_SANDBOX)
                {
                    ScreenMessages.PostScreenMessage(string.Format(kScienceGenerated, scienceBonus), kMessageDuration, ScreenMessageStyle.UPPER_CENTER);
                    ResearchAndDevelopment.Instance.AddScience(scienceBonus, TransactionReasons.RnDs);
                }
            }

            //Run the analysis
            biomeScanner.RunAnalysis();
            rebuildAbundanceSummary();
            geoLabView.abundanceSummary = this.abundanceSummary;
            onBiomeUnlocked.Fire();
            return(true);
        }
Exemple #3
0
        private void EatSnacks()
        {
            try
            {
                double snackDeficit;
                int    crewCount = 0;

                //Post the before snack time event
                onBeforeSnackTime.Fire();

                //Consume snacks for loaded vessels
                //Debug.Log("Loaded vessles count: " + FlightGlobals.VesselsLoaded.Count);
                foreach (Vessel vessel in FlightGlobals.Vessels)
                {
                    snackDeficit = 0;

                    //Skip the vessel if it has unowned crew
                    if (SnackConsumer.hasUnownedCrew(vessel))
                    {
                        Debug.Log("Skipping " + vessel.vesselName + " due to unowned crew");
                        continue;
                    }

                    //Consume snacks and get the deficit if any.
                    if (vessel.loaded)
                    {
                        crewCount = vessel.GetCrewCount();
                    }
                    else
                    {
                        crewCount = vessel.protoVessel.GetVesselCrew().Count;
                    }

                    if (crewCount > 0)
                    {
                        //Consume snacks and get the deficit (if any)
                        snackDeficit = consumer.ConsumeAndGetDeficit(vessel);

                        //Apply penalties if we have a deficit
                        if (snackDeficit > 0)
                        {
                            applyPenalties(snackDeficit, vessel);
                        }

                        //Make sure to remove all penalties, the kerbals are all fed.
                        else
                        {
                            removePenalties(vessel);
                        }
                    }
                }

                //Post the snack time event
                onSnackTime.Fire();
            }
            catch (Exception ex)
            {
                Debug.Log("Snacks - EatSnacks: " + ex.Message + ex.StackTrace);
            }
        }
        private IEnumerator CheckActionGroupEditor()
        {
            while (EditorLogic.fetch == null)
            {
                yield return(null);
            }
            EditorLogic editor = EditorLogic.fetch;

            while (editor != null)
            {
                //FIXME check for events
                if (editor.editorScreen == EditorScreen.Actions)
                {
                    if (!ActionGroupMode)
                    {
                        HideGUI();
                        OnActionGroupEditorOpened.Fire();
                    }
                    var age = EditorActionGroups.Instance;
                    if (selected_part)
                    {
                        if (!age.SelectionContains(selected_part))
                        {
                            selected_part = null;
                            HideGUI();
                        }
                    }
                    else if (age.HasSelectedParts())
                    {
                        selected_part = age.GetSelectedParts()[0];
                        var container = selected_part.FindContainer();
                        if (container)
                        {
                            ShowGUI(container);
                        }
                    }
                    ActionGroupMode = true;
                }
                else
                {
                    if (ActionGroupMode)
                    {
                        HideGUI();
                        OnActionGroupEditorClosed.Fire();
                    }
                    ActionGroupMode = false;
                }
                yield return(null);
            }
        }
        public void onVesselGoOffRails(Vessel v)
        {
            if (v.situation == Vessel.Situations.LANDED ||
                (stabilizeInPrelaunch && v.situation == Vessel.Situations.PRELAUNCH))
            {
                Log.info("off rails: {0}: alt: {1}; radar alt: {2}; alt: {3}", v.name, v.altitude, v.radarAltitude, v.protoVessel.altitude);
                if (v.isEVA && !stabilizeKerbals)                   // Kerbals are usually ok
                {
                    return;
                }
                if (v.packed)                   // no physics, leave it alone
                {
                    return;
                }
                if (checkExcludes(v))                    // don't touch particular vessels
                {
                    return;
                }

                // missionTime seems to be not very reliable - doesn't work if the vessel wasn't touched after launch
                Log.detail("mission time: {0}", v.missionTime);
                if (v.missionTime < 3)
                {
                    Log.detail("checking if we're inside the hangar");
                    if (checkIfInsideHangar(v))
                    {
                        return;
                    }
                }

                if (count == 0)
                {
                    onWorldStabilizationStartEvent.Fire();
                }

                vesselTimer [v.id] = stabilizationTimer;
                bounds [v.id]      = new VesselBounds(v);
                if (drawPoints)
                {
                    initLR(v, bounds [v.id]);
                }
                count++;

                // Scheduling moving up at fixed update to allow other modules to fully initialize
                initialAltitude[v.id] = v.altitude;
                vesselsToMoveUp.Add(v);
            }
        }
Exemple #6
0
        public void AddPassengersToActiveVessel()
        {
            LoggingUtil.LogVerbose(this, "AddPassengersToActiveVessel");

            // Check the active vessel
            Vessel v = FlightGlobals.ActiveVessel;

            if (v == null || !HighLogic.LoadedSceneIsFlight)
            {
                return;
            }

            foreach (ProtoCrewMember crewMember in passengers.Keys.ToList())
            {
                // Find a seat for the crew
                Part part = v.parts.Find(p => p.protoModuleCrew.Count < p.CrewCapacity);

                // Add the crew member
                bool success = false;
                if (part != null)
                {
                    // Add them to the part
                    success = part.AddCrewmember(crewMember);
                    if (success)
                    {
                        crewMember.type        = ProtoCrewMember.KerbalType.Tourist;
                        passengers[crewMember] = true;
                        GameEvents.onCrewBoardVessel.Fire(new GameEvents.FromToAction <Part, Part>(part, part));
                        GameEvents.onCrewTransferred.Fire(new GameEvents.HostedFromToAction <ProtoCrewMember, Part>(crewMember, part, part));
                    }
                }

                if (!success)
                {
                    LoggingUtil.LogError(this, "Unable to add crew to vessel named '" + v.name + "'.  Perhaps there's no room?");
                    break;
                }
            }

            // This will force the crew members to appear
            v.SpawnCrew();

            // Update the parameters and force a re-check to update their state
            onPassengersLoaded.Fire();
        }
Exemple #7
0
        void FixedUpdate()
        {
            if (HighLogic.LoadedScene != GameScenes.SPACECENTER &&
                HighLogic.LoadedScene != GameScenes.FLIGHT &&
                HighLogic.LoadedScene != GameScenes.TRACKSTATION)
            {
                return;
            }
            try
            {
                double currentTime = Planetarium.GetUniversalTime();

                if (currentTime > nextSnackTime)
                {
                    //Setup next snacking time.
                    if (SnacksProperties.EnableRandomSnacking)
                    {
                        System.Random rand = new System.Random();
                        nextSnackTime = rand.NextDouble() * snackFrequency + currentTime;
                    }
                    else
                    {
                        nextSnackTime = snackFrequency + currentTime;
                    }

                    Debug.Log("Snack time!  Next Snack Time!:" + nextSnackTime);

                    //Eat snacks!
                    EatSnacks();

                    //Update the snapshot
                    SnackSnapshot.Instance().RebuildSnapshot();

                    //Fire snack tick event
                    onSnackTick.Fire();
                }
            }
            catch (Exception ex)
            {
                Debug.Log("[Snacks] - FixedUpdate: " + ex.Message + ex.StackTrace);
            }
        }
        public void FixedUpdate()
        {
            if (count == 0)
            {
                return;
            }

            foreach (Vessel v in FlightGlobals.VesselsLoaded)
            {
                if (vesselTimer.ContainsKey(v.id) && vesselTimer[v.id] > 0)
                {
                    stabilize(v);

                    vesselTimer [v.id]--;
                    if (vesselTimer [v.id] == 0)
                    {
                        count--;
                        Log.detail("Stopping stabilizing {0}", v.name);

                        if (count == 0)
                        {
                            if (displayMessage)
                            {
                                ScreenMessages.PostScreenMessage("World has been stabilized");
                                Log.info("World has been stabilized");
                            }
                            onWorldStabilizedEvent.Fire();
                        }
                    }
                }
            }

//			KAS Harpoons are out of order in KAS 1.0
            if (!KASAPI.isNewKsp)
            {
                foreach (Rigidbody rb in KASAPI.harpoonsToHold)
                {
                    KASAPI.holdHarpoon(rb);
                }
            }
        }
        public void TakeSelfie()
        {
            ScreenMessages.PostScreenMessage("Selfie...!");
            smile      = true;
            selfieTime = DateTime.Now;
            foreach (Tourist t in tourists.Values)
            {
                t.generateEmotion();
            }

            //FlightGlobals.ActiveVessel.evaController.part.Events ["TakeSelfie"].active = false;
            GameEvents.onHideUI.Fire();
            Log.detail("Selfie...!");

            /*FlightCamera camera = FlightCamera.fetch;
             * savedCameraPosition = camera.transform.position;
             * savedCameraRotation = camera.transform.rotation;
             * savedCameraTarget = camera.Target;
             * camera.SetTargetNone ();*/

            selfieListeners.Fire();
        }
        private IEnumerator CheckActionGroupEditor()
        {
            while (EditorLogic.fetch == null)
            {
                yield return(null);
            }
            EditorLogic editor = EditorLogic.fetch;

            while (EditorLogic.fetch != null)
            {
                if (editor.editorScreen == EditorScreen.Actions)
                {
                    if (!ActionGroupMode)
                    {
                        Debug.Log("TankWindow.CheckActionGroupEditor() hiding tank window (!AGM)");
                        HideGUI();
                        OnActionGroupEditorOpened.Fire();
                    }
                    var age = EditorActionGroups.Instance;
                    if (tank_module && !age.GetSelectedParts().Contains(tank_module.part))
                    {
                        Debug.Log("TankWindow.CheckActionGroupEditor() hiding tank window (selected part does not contain this module)");
                        HideGUI();
                    }
                    ActionGroupMode = true;
                }
                else
                {
                    if (ActionGroupMode)
                    {
                        Debug.Log("TankWindow.CheckActionGroupEditor() hiding tank window (editorScreen == Actions && AGM)");
                        HideGUI();
                        OnActionGroupEditorClosed.Fire();
                    }
                    ActionGroupMode = false;
                }
                yield return(null);
            }
        }
        private IEnumerator <YieldInstruction> CheckActionGroupEditor()
        {
            while (EditorLogic.fetch == null)
            {
                yield return(null);
            }
            EditorLogic editor = EditorLogic.fetch;

            while (EditorLogic.fetch != null)
            {
                if (editor.editorScreen == EditorScreen.Actions)
                {
                    if (!ActionGroupMode)
                    {
                        HideGUI();
                        OnActionGroupEditorOpened.Fire();
                    }
                    EditorActionGroups age = EditorActionGroups.Instance;
                    if (missile_module && !age.GetSelectedParts().Contains(missile_module.part))
                    {
                        HideGUI();
                    }
                    ActionGroupMode = true;
                }
                else
                {
                    if (ActionGroupMode)
                    {
                        HideGUI();
                        OnActionGroupEditorClosed.Fire();
                    }
                    ActionGroupMode = false;
                }
                yield return(null);
            }
        }
Exemple #12
0
        private IEnumerable <ConfiguredContract> GenerateContract(ContractType contractType)
        {
            // Set the desired prestige
            int t1, t2, t3;

            ContractSystem.GetContractCounts(Reputation.CurrentRep, 1000, out t1, out t2, out t3);
            if (contractType.prestige.Any())
            {
                if (!contractType.prestige.Contains(Contract.ContractPrestige.Trivial))
                {
                    t1 = 0;
                }
                if (!contractType.prestige.Contains(Contract.ContractPrestige.Significant))
                {
                    t2 = 0;
                }
                if (!contractType.prestige.Contains(Contract.ContractPrestige.Exceptional))
                {
                    t3 = 0;
                }
            }
            int selection = rand.Next(0, t1 + t2 + t3);

            Contract.ContractPrestige prestige = selection < t1 ? Contract.ContractPrestige.Trivial : selection < (t1 + t2) ? Contract.ContractPrestige.Significant : Contract.ContractPrestige.Exceptional;

            // Generate the template
            ConfiguredContract templateContract = Contract.Generate(typeof(ConfiguredContract), prestige, rand.Next(), Contract.State.Withdrawn) as ConfiguredContract;

            // First, check the basic requirements
            if (!contractType.MeetBasicRequirements(templateContract))
            {
                LoggingUtil.LogVerbose(this, "{0} was not generated: basic requirements not met.", contractType.name);
                if (++contractType.failedGenerationAttempts >= contractType.maxConsecutiveGenerationFailures)
                {
                    contractType.lastGenerationFailure = Time.realtimeSinceStartup;
                }

                yield return(null);

                yield break;
            }

            // Try to refresh non-deterministic values before we check extended requirements
            OnInitializeValues.Fire();
            LoggingUtil.LogLevel origLogLevel = LoggingUtil.logLevel;
            LoggingUtil.LogLevel newLogLevel  = contractType.trace ? LoggingUtil.LogLevel.VERBOSE : LoggingUtil.logLevel;
            try
            {
                // Set up for loop
                LoggingUtil.logLevel = newLogLevel;
                ConfiguredContract.currentContract = templateContract;

                // Set up the iterator to refresh non-deterministic values
                IEnumerable <string> iter = ConfigNodeUtil.UpdateNonDeterministicValuesIterator(contractType.dataNode);
                for (ContractGroup g = contractType.group; g != null; g = g.parent)
                {
                    iter = ConfigNodeUtil.UpdateNonDeterministicValuesIterator(g.dataNode).Concat(iter);
                }

                // Update the actual values
                LoggingUtil.LogVerbose(this, "Refresh non-deterministic values for CONTRACT_TYPE = {0}", contractType.name);
                foreach (string val in iter)
                {
                    lastKey = contractType.name + "[" + val + "]";

                    // Clear temp stuff
                    LoggingUtil.logLevel = origLogLevel;
                    ConfiguredContract.currentContract = null;

                    if (val == null)
                    {
                        LoggingUtil.LogVerbose(this, "{0} was not generated: non-deterministic expression failure.", contractType.name);
                        if (++contractType.failedGenerationAttempts >= contractType.maxConsecutiveGenerationFailures)
                        {
                            contractType.lastGenerationFailure = Time.realtimeSinceStartup;
                        }

                        OnInitializeFail.Fire();
                        yield return(null);

                        yield break;
                    }
                    else
                    {
                        // Quick pause
                        yield return(null);
                    }

                    // Re set up
                    LoggingUtil.logLevel = newLogLevel;
                    ConfiguredContract.currentContract = templateContract;
                }
            }
            finally
            {
                LoggingUtil.logLevel = origLogLevel;
                ConfiguredContract.currentContract = null;
            }

            // Store unique data
            foreach (string key in contractType.uniquenessChecks.Keys)
            {
                if (contractType.dataNode.GetType(key) == typeof(Vessel))
                {
                    Vessel v = contractType.dataNode[key] as Vessel;
                    templateContract.uniqueData[key] = v != null ? (object)v.id : null;
                }
                else
                {
                    templateContract.uniqueData[key] = contractType.dataNode[key];
                }
            }
            templateContract.targetBody = contractType.targetBody;

            // Check the requirements for our selection
            if (contractType.MeetExtendedRequirements(templateContract, contractType) && templateContract.Initialize(contractType))
            {
                templateContract.ContractState = Contract.State.Offered;
                yield return(templateContract);
            }
            // Failure, add a pause in before finishing
            else
            {
                LoggingUtil.LogVerbose(this, "{0} was not generated: requirement not met.", contractType.name);
                if (++contractType.failedGenerationAttempts >= contractType.maxConsecutiveGenerationFailures)
                {
                    contractType.lastGenerationFailure = Time.realtimeSinceStartup;
                }

                OnInitializeFail.Fire();
                yield return(null);
            }
        }
        public static IEnumerator loadContracts()
        {
            if (HighLogic.CurrentGame.Mode != Game.Modes.CAREER)
            {
                yield break;
            }

            loaded = false;

            int i = 0;

            //Agency modifiers don't seem to work unless I wait a few frames before loading contracts
            while (i < 5)
            {
                i++;
                yield return(null);
            }

            Debug.Log("[Contract Parser] Loading All Contracts...");

            activeContracts.Clear();
            offeredContracts.Clear();
            completedContracts.Clear();
            failedContracts.Clear();
            declinedContracts.Clear();

            for (int j = 0; j < ContractSystem.Instance.Contracts.Count; j++)
            {
                Contract c = ContractSystem.Instance.Contracts[j];

                if (c == null)
                {
                    Debug.Log("[Contract Parser] Error in loading null contract from master list");
                    continue;
                }

                contractContainer cc = new contractContainer(c);

                if (cc.Root == null)
                {
                    Debug.Log(string.Format("[Contract Parser] Error while loading contract of type {0}; skipping", c.GetType().Name));
                    continue;
                }

                switch (cc.Root.ContractState)
                {
                case Contract.State.Active:
                    addActiveContract(cc);
                    continue;

                case Contract.State.Offered:
                    addOfferedContract(cc);
                    continue;

                case Contract.State.Completed:
                    addCompletedContract(cc);
                    continue;

                case Contract.State.Cancelled:
                case Contract.State.DeadlineExpired:
                case Contract.State.Failed:
                    addFailedContract(cc);
                    continue;

                default:
                    continue;
                }
            }

            for (int j = 0; j < ContractSystem.Instance.ContractsFinished.Count; j++)
            {
                Contract c = ContractSystem.Instance.ContractsFinished[j];

                if (c == null)
                {
                    Debug.Log("[Contract Parser] Error in loading contract from finished list");
                    continue;
                }

                contractContainer cc = new contractContainer(c);

                if (cc.Root == null)
                {
                    Debug.Log(string.Format("[Contract Parser] Error while loading finished contract of type {0}; skipping", c.GetType().Name));
                    continue;
                }

                switch (cc.Root.ContractState)
                {
                case Contract.State.Active:
                    addActiveContract(cc);
                    continue;

                case Contract.State.Offered:
                    addOfferedContract(cc);
                    continue;

                case Contract.State.Completed:
                    addCompletedContract(cc);
                    continue;

                case Contract.State.Cancelled:
                case Contract.State.DeadlineExpired:
                case Contract.State.Failed:
                    addFailedContract(cc);
                    continue;

                default:
                    continue;
                }
            }

            if (contractReflection.CCLoaded)
            {
                RefreshCCOfferedContracts();
            }

            loaded = true;

            onContractsParsed.Fire();

            Debug.Log("[Contract Parser] Finished Loading All Contracts");
        }