/// <summary>
        /// Adds a new ParameterFactory to handle PARAMETER nodes with the given type.
        /// </summary>
        /// <param name="factoryType">Type of factory to register.</param>
        /// <param name="typeName">The name of the factory.</param>
        public static void Register(Type factoryType, string typeName)
        {
            LoggingUtil.LogDebug(typeof(ParameterFactory), "Registering parameter factory class " +
                                 factoryType.FullName + " for handling PARAMETER nodes with type = " + typeName + ".");

            // Make sure we can instantiate it (this will also run any static initializers)
            Activator.CreateInstance(factoryType);

            // Check for duplicates
            Type existingType = null;

            if (factories.TryGetValue(typeName, out existingType))
            {
                // Give priority to non-Contract Configurator types
                if (existingType.Assembly == typeof(ParameterFactory).Assembly)
                {
                    factories[typeName] = factoryType;
                }
                // If neither are the Contract Configurator type, throw an error
                else if (factoryType.Assembly != typeof(ParameterFactory).Assembly)
                {
                    LoggingUtil.LogError(typeof(ParameterFactory), "Cannot register " + factoryType.FullName + "[" + factoryType.Module +
                                         "] to handle type " + typeName + ": already handled by " +
                                         existingType.FullName + "[" +
                                         existingType.Module + "]");
                }
            }
            else
            {
                // Add it to our list
                factories.Add(typeName, factoryType);
            }
        }
        /// <summary>
        /// Registers all the ContractRequirement classes.
        /// </summary>
        void RegisterContractRequirements()
        {
            LoggingUtil.LogDebug(this, "Start Registering ContractRequirements");

            // Register each type
            foreach (Type subclass in GetAllTypes <ContractRequirement>().Where(t => !t.IsAbstract))
            {
                string name = subclass.Name;
                if (name.EndsWith("Requirement"))
                {
                    name = name.Remove(name.Length - 11, 11);
                }

                try
                {
                    ContractRequirement.Register(subclass, name);
                }
                catch (Exception e)
                {
                    LoggingUtil.LogError(this, "Error registering contract requirement " + subclass.Name);
                    LoggingUtil.LogException(e);
                }
            }

            LoggingUtil.LogInfo(this, "Finished Registering ContractRequirements");
        }
        /// <summary>
        /// Registers all the BehaviourFactory classes.
        /// </summary>
        void RegisterBehaviourFactories()
        {
            LoggingUtil.LogDebug(this, "Start Registering BehaviourFactories");

            // Register each type with the behaviour factory
            foreach (Type subclass in GetAllTypes <BehaviourFactory>().Where(t => !t.IsAbstract))
            {
                string name = subclass.Name;
                if (name.EndsWith("Factory"))
                {
                    name = name.Remove(name.Length - 7, 7);
                }

                try
                {
                    BehaviourFactory.Register(subclass, name);
                }
                catch (Exception e)
                {
                    LoggingUtil.LogError(this, "Error registering behaviour factory " + subclass.Name);
                    LoggingUtil.LogException(e);
                }
            }

            LoggingUtil.LogInfo(this, "Finished Registering BehaviourFactories");
        }
Beispiel #4
0
        public static void SetContractState(Type contractType, bool enabled)
        {
            if (ContractSystem.ContractTypes == null || ContractSystem.Instance == null)
            {
                Instance.StartCoroutine(Instance.SetContractStateDeferred(contractType, enabled));
            }
            else
            {
                if (!enabled && ContractSystem.ContractTypes.Contains(contractType))
                {
                    LoggingUtil.LogDebug(typeof(ContractDisabler), "Disabling ContractType: " + contractType.FullName + " (" + contractType.Module + ")");
                    do
                    {
                        ContractSystem.ContractTypes.Remove(contractType);
                    } while (ContractSystem.ContractTypes.Contains(contractType));

                    // Remove Offered and active contracts
                    foreach (Contract contract in ContractSystem.Instance.Contracts.Where(c => c != null && c.GetType() == contractType &&
                                                                                          (c.ContractState == Contract.State.Offered || c.ContractState == Contract.State.Active)))
                    {
                        contract.Withdraw();
                    }
                }
                else if (enabled && !ContractSystem.ContractTypes.Contains(contractType))
                {
                    LoggingUtil.LogDebug(typeof(ContractDisabler), "Enabling ContractType: " + contractType.FullName + " (" + contractType.Module + ")");
                    ContractSystem.ContractTypes.Add(contractType);
                }
            }
        }
 public override bool RequirementMet(ConfiguredContract contract)
 {
     if (!expression && contract.ContractState == Contract.State.Offered)
     {
         LoggingUtil.LogDebug(this, "Requirement not met for offered contract; ignoring requirement failure.");
         return(true);
     }
     return(expression);
 }
Beispiel #6
0
        protected virtual void OnVesselWasModified(Vessel vessel)
        {
            LoggingUtil.LogDebug(this, "OnVesselWasModified: " + vessel.id);
            vessel.GetHashes().Count();

            // Check for a vessel creation after a part joint break
            if (HighLogic.LoadedScene != GameScenes.FLIGHT || lastBreak == null || vessel == lastBreak)
            {
                LoggingUtil.LogVerbose(this, "    returning, wrong scene or wrong vessel...");
                return;
            }

            IEnumerable <uint> otherVesselHashes = lastBreak.GetHashes();
            IEnumerable <uint> vesselHashes      = vessel.GetHashes();

            // OnVesselWasModified gets called twice, on the first call the vessels are still
            // connected.  Check for that case.
            if (vesselModifiedCallCount++ == 0)
            {
                LoggingUtil.LogVerbose(this, "    first call check");
                // The second call will be for the original vessel.  Swap over to check that one.
                lastBreak = vessel;
                return;
            }

            // Get the keys we will be looking at
            List <string> vesselKeys      = GetAssociatedKeys(vessel).ToList();
            List <string> otherVesselKeys = GetAssociatedKeys(lastBreak).ToList();

            // Check the lists and see if we need to do a switch
            foreach (string key in vesselKeys)
            {
                // Check if we need to switch over to the newly created vessel
                VesselInfo vi = vessels[key];
                if (otherVesselHashes.Contains(vi.hash))
                {
                    LoggingUtil.LogDebug(this, "Moving association for '" + key + "' from " + vi.id + " to " + lastBreak.id);
                    vi.id = lastBreak.id;
                    OnVesselAssociation.Fire(new GameEvents.HostTargetAction <Vessel, string>(lastBreak, key));
                }
            }
            foreach (string key in otherVesselKeys)
            {
                // Check if we need to switch over to the newly created vessel
                VesselInfo vi = vessels[key];
                if (vesselHashes.Contains(vi.hash))
                {
                    LoggingUtil.LogDebug(this, "Moving association for '" + key + "' from " + vi.id + " to " + vessel.id);
                    vi.id = vessel.id;
                    OnVesselAssociation.Fire(new GameEvents.HostTargetAction <Vessel, string>(vessel, key));
                }
            }

            lastBreak = null;
        }
        /// <summary>
        /// Loads all the contact configuration group nodes.
        /// </summary>
        private IEnumerator <YieldInstruction> LoadGroupConfig()
        {
            // Load all the contract groups
            LoggingUtil.LogDebug(this, "Loading CONTRACT_GROUP nodes.");
            ConfigNode[] contractGroups = GameDatabase.Instance.GetConfigNodes("CONTRACT_GROUP");

            foreach (ConfigNode groupConfig in contractGroups)
            {
                // Create the group
                string name = groupConfig.GetValue("name");
                LoggingUtil.LogInfo(this, "Loading CONTRACT_GROUP: '" + name + "'");
                ContractGroup contractGroup = null;
                try
                {
                    contractGroup = new ContractGroup(name);
                }
                catch (ArgumentException)
                {
                    LoggingUtil.LogError(this, "Couldn't load CONTRACT_GROUP '" + name + "' due to a duplicate name.");
                }

                // Peform the actual load
                if (contractGroup != null)
                {
                    bool success = false;
                    try
                    {
                        ConfigNodeUtil.ClearCache(true);
                        success = contractGroup.Load(groupConfig);
                    }
                    catch (Exception e)
                    {
                        Exception wrapper = new Exception("Error loading CONTRACT_GROUP '" + name + "'", e);
                        LoggingUtil.LogException(wrapper);
                    }
                    finally
                    {
                        if (!success)
                        {
                            ContractGroup.contractGroups.Remove(name);
                        }
                    }
                }
            }

            if (!reloading)
            {
                yield return(new WaitForEndOfFrame());
            }

            // Emit settings for the menu
            SettingsBuilder.EmitSettings();

            yield break;
        }
Beispiel #8
0
        /// <summary>
        /// Disables standard contract types as requested by contract packs.
        /// </summary>
        /// <returns>True if the disabling is done.</returns>
        public static bool DisableContracts()
        {
            if (contractsDisabled)
            {
                return(true);
            }

            // Don't do anything if the contract system has not yet loaded
            if (ContractSystem.ContractTypes == null)
            {
                return(false);
            }

            LoggingUtil.LogDebug(typeof(ContractDisabler), "Disabling contract types...");
            ConfigNode[] nodes = GameDatabase.Instance.GetConfigNodes("CONTRACT_CONFIGURATOR");

            int disabledCounter = 0;

            // Start disabling via legacy method
            Dictionary <string, Type> contractsToDisable = new Dictionary <string, Type>();

            foreach (ConfigNode node in nodes)
            {
                foreach (string contractType in node.GetValues("disabledContractType"))
                {
                    LoggingUtil.LogWarning(typeof(ContractDisabler), "Disabling contract " + contractType +
                                           " via legacy method.  Recommend using the disableContractType attribute of the CONTRACT_GROUP node instead.");

                    if (SetContractToDisabled(contractType, null))
                    {
                        disabledCounter++;
                    }
                }
            }

            // Disable via new method
            foreach (ContractGroup contractGroup in ContractGroup.AllGroups.Where(g => g != null && g.parent == null))
            {
                foreach (string contractType in contractGroup.disabledContractType)
                {
                    if (SetContractToDisabled(contractType, contractGroup))
                    {
                        disabledCounter++;
                    }
                }
            }

            LoggingUtil.LogInfo(typeof(ContractDisabler), "Disabled " + disabledCounter + " ContractTypes.");

            contractsDisabled = true;
            return(true);
        }
Beispiel #9
0
        void Awake()
        {
            DontDestroyOnLoad(this);
            Instance = this;

            // Do a version check
            Assembly dtvAssembly = Util.Version.VerifyAssemblyVersion("DraftTwitchViewers", "2.3.1", true);

            if (dtvAssembly == null)
            {
                LoggingUtil.LogDebug(this, "Unable to find DraftTwitchViewers assembly.");
                Destroy(this);
                return;
            }
            LoggingUtil.LogDebug(this, "Found DraftTwitchViewers assembly.");

            Type draftManager = dtvAssembly.GetTypes().Where(t => t.Name.Contains("ScenarioDraftManager")).FirstOrDefault();

            if (draftManager == null)
            {
                LoggingUtil.LogError(this, "Couldn't get ScenarioDraftManager from DraftTwitchViewers!");
                Destroy(this);
                return;
            }

            draftMethod = draftManager.GetMethods(BindingFlags.Public | BindingFlags.Static).
                          Where(mi => mi.Name == "DraftKerbal").FirstOrDefault();
            if (draftMethod == null)
            {
                LoggingUtil.LogError(this, "Couldn't get DraftKerbal method from DraftTwitchViewers!");
                Destroy(this);
                return;
            }

            saveMethod = draftManager.GetMethods(BindingFlags.Public | BindingFlags.Static).
                         Where(mi => mi.Name == "SaveSupressedDraft").FirstOrDefault();
            if (saveMethod == null)
            {
                LoggingUtil.LogError(this, "Couldn't get SaveSupressedDraft method from DraftTwitchViewers!");
                Destroy(this);
                return;
            }

            GameEvents.Contract.onAccepted.Add(new EventData <Contract> .OnEvent(OnContractAccepted));
            ContractPreLoader.OnInitializeValues.Add(new EventVoid.OnEvent(OnPreLoaderInitializeValues));
            ContractPreLoader.OnInitializeFail.Add(new EventVoid.OnEvent(OnPreLoaderInitializeFail));
        }
        /*
         * Adds a new ContractRequirement to handle REQUIREMENT nodes with the given type.
         */
        public static void Register(Type crType, string typeName)
        {
            LoggingUtil.LogDebug(typeof(ContractRequirement), "Registering ContractRequirement class " +
                                 crType.FullName + " for handling REQUIREMENT nodes with type = " + typeName + ".");

            if (requirementTypes.ContainsKey(typeName))
            {
                LoggingUtil.LogError(typeof(ContractRequirement), "Cannot register " + crType.FullName + "[" + crType.Module +
                                     "] to handle type " + typeName + ": already handled by " +
                                     requirementTypes[typeName].FullName + "[" +
                                     requirementTypes[typeName].Module + "]");
            }
            else
            {
                requirementTypes.Add(typeName, crType);
            }
        }
Beispiel #11
0
        /// <summary>
        /// Registers all the ContractRequirement classes.
        /// </summary>
        void RegisterContractRequirements()
        {
            LoggingUtil.LogDebug(this.GetType(), "Start Registering ContractRequirements");

            // Register each type with the parameter factory
            foreach (Type subclass in GetAllTypes <ContractRequirement>())
            {
                string name = subclass.Name;
                if (name.EndsWith("Requirement"))
                {
                    name = name.Remove(name.Length - 11, 11);
                }
                ContractRequirement.Register(subclass, name);
            }

            LoggingUtil.LogInfo(this.GetType(), "Finished Registering ContractRequirements");
        }
Beispiel #12
0
        /// <summary>
        /// Registers all the BehaviourFactory classes.
        /// </summary>
        void RegisterBehaviourFactories()
        {
            LoggingUtil.LogDebug(this.GetType(), "Start Registering BehaviourFactories");

            // Register each type with the behaviour factory
            foreach (Type subclass in GetAllTypes <BehaviourFactory>())
            {
                string name = subclass.Name;
                if (name.EndsWith("Factory"))
                {
                    name = name.Remove(name.Length - 7, 7);
                }
                BehaviourFactory.Register(subclass, name);
            }

            LoggingUtil.LogInfo(this.GetType(), "Finished Registering BehaviourFactories");
        }
Beispiel #13
0
        /*
         * Adds a new BehaviourFactory to handle Behaviour nodes with the given type.
         */
        public static void Register(Type factoryType, string typeName)
        {
            LoggingUtil.LogDebug(typeof(BehaviourFactory), "Registering behaviour factory class " +
                                 factoryType.FullName + " for handling BEHAVIOUR nodes with type = " + typeName + ".");

            if (factories.ContainsKey(typeName))
            {
                LoggingUtil.LogError(typeof(BehaviourFactory), "Cannot register " + factoryType.FullName + "[" + factoryType.Module +
                                     "] to handle type " + typeName + ": already handled by " +
                                     factories[typeName].FullName + "[" +
                                     factories[typeName].Module + "]");
            }
            else
            {
                factories.Add(typeName, factoryType);
            }
        }
Beispiel #14
0
 /*
  * Attempts to parse a value from the config node.
  */
 public static bool ParseValue <T>(ConfigNode configNode, string key, ref T value, IContractConfiguratorFactory obj)
 {
     try
     {
         value = ParseValue <T>(configNode, key);
         return(value != null);
     }
     catch (Exception e)
     {
         LoggingUtil.LogError(obj, obj.ErrorPrefix(configNode) + ": Error parsing " + key + ": " + configNode.id + e.Message);
         LoggingUtil.LogDebug(obj, e.StackTrace);
         return(false);
     }
     finally
     {
         AddFoundKey(configNode, key);
     }
 }
Beispiel #15
0
        /// <summary>
        /// Adds a new ContractRequirement to handle REQUIREMENT nodes with the given type.
        /// </summary>
        /// <param name="crType">ContractRequirement type</param>
        /// <param name="typeName">Name to associate to the type</param>
        public static void Register(Type crType, string typeName)
        {
            LoggingUtil.LogDebug(typeof(ContractRequirement), "Registering ContractRequirement class {0} for handling REQUIREMENT nodes with type = {1}.", crType.FullName, typeName);

            if (requirementTypes.ContainsKey(typeName))
            {
                LoggingUtil.LogError(typeof(ContractRequirement), "Cannot register {0}[{1}] to handle type {2}: already handled by {3}[{4}]",
                                     crType.FullName, crType.Module, typeName, requirementTypes[typeName].FullName, requirementTypes[typeName].Module);
            }
            else
            {
                // Make sure we can instantiate it (this will also run any static initializers)
                Activator.CreateInstance(crType);

                // Add it to our list
                requirementTypes.Add(typeName, crType);
            }
        }
        /// <summary>
        /// Adds a new BehaviourFactory to handle Behaviour nodes with the given type.
        /// </summary>
        /// <param name="factoryType">Type of the factory</param>
        /// <param name="typeName">Name to associate with the given type</param>
        public static void Register(Type factoryType, string typeName)
        {
            LoggingUtil.LogDebug(typeof(BehaviourFactory), "Registering behaviour factory class {0} for handling BEHAVIOUR nodes with type = {1}.", factoryType.FullName, typeName);

            if (factories.ContainsKey(typeName))
            {
                LoggingUtil.LogError(typeof(BehaviourFactory), "Cannot register {0}[{1}] to handle type {2}: already handled by {3}[{4}]",
                                     factoryType.FullName, factoryType.Module, typeName, factories[typeName].FullName, factories[typeName].Module);
            }
            else
            {
                // Make sure we can instantiate it (this will also run any static initializers)
                Activator.CreateInstance(factoryType);

                // Add it to our list
                factories.Add(typeName, factoryType);
            }
        }
        public static void OnSuccess(Dictionary <string, string> dict)
        {
            Instance.routinesRunning--;
            if (!dict.ContainsKey("name"))
            {
                return;
            }

            string name = dict["name"];

            LoggingUtil.LogDebug(typeof(DraftTwitchViewers), "DraftTwitchViewers Success: {0}", name);

            // Queue the name if it is new
            if (Instance.IsUnique(name))
            {
                Instance.nameQueue.Enqueue(name);
                Instance.names.Add(name);
            }
        }
        /// <summary>
        /// Adds a new ParameterFactory to handle PARAMETER nodes with the given type.
        /// </summary>
        /// <param name="factoryType">Type of factory to register.</param>
        /// <param name="typeName">The name of the factory.</param>
        public static void Register(Type factoryType, string typeName)
        {
            LoggingUtil.LogDebug(typeof(ParameterFactory), "Registering parameter factory class " +
                                 factoryType.FullName + " for handling PARAMETER nodes with type = " + typeName + ".");

            if (factories.ContainsKey(typeName))
            {
                LoggingUtil.LogError(typeof(ParameterFactory), "Cannot register " + factoryType.FullName + "[" + factoryType.Module +
                                     "] to handle type " + typeName + ": already handled by " +
                                     factories[typeName].FullName + "[" +
                                     factories[typeName].Module + "]");
            }
            else
            {
                // Make sure we can instantiate it (this will also run any static initializers)
                Activator.CreateInstance(factoryType);

                // Add it to our list
                factories.Add(typeName, factoryType);
            }
        }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            // Get the count of finished contracts
            int    finished     = 0;
            double lastFinished = 0.0;

            // Finished contracts - Contract Configurator style
            if (ccType != null)
            {
                IEnumerable <ConfiguredContract> completedContract = ConfiguredContract.CompletedContracts.
                                                                     Where(c => c.contractType != null && c.contractType.name.Equals(ccType));
                finished = completedContract.Count();
                if (finished > 0)
                {
                    lastFinished = completedContract.OrderByDescending <ConfiguredContract, double>(c => c.DateFinished).First().DateFinished;
                }
            }
            // Finished contracts - stock style
            else if (contractClass != null)
            {
                // Call the GetCompletedContracts with our type, and get the count
                Contract[] completedContract = (Contract[])typeof(ContractSystem).GetMethod("GetCompletedContracts").MakeGenericMethod(contractClass).Invoke(ContractSystem.Instance, null);
                finished = completedContract.Count();
                if (finished > 0)
                {
                    lastFinished = completedContract.OrderByDescending <Contract, double>(c => c.DateFinished).First().DateFinished;
                }
            }

            // Check cooldown
            if (cooldownDuration.Value > 0.0 && finished > 0 && lastFinished + cooldownDuration.Value > Planetarium.GetUniversalTime())
            {
                LoggingUtil.LogDebug(this, "Returning false due to cooldown for " + contractType.name);
                return(false);
            }

            // Return based on the min/max counts configured
            return((finished >= minCount) && (finished <= maxCount));
        }
Beispiel #20
0
 /*
  * Attempts to parse a value from the config node.  Returns a default value if not found.
  * Validates return values using the given function.
  */
 public static bool ParseValue <T>(ConfigNode configNode, string key, ref T value, IContractConfiguratorFactory obj, T defaultValue, Func <T, bool> validation)
 {
     if (ParseValue <T>(configNode, key, ref value, obj, defaultValue))
     {
         try
         {
             if (!validation.Invoke(value))
             {
                 // In general, the validation function should throw an exception and give a much better message
                 LoggingUtil.LogError(obj, obj.ErrorPrefix(configNode) + ": The value supplied for " + key + " (" + value + ") is invalid.");
                 return(false);
             }
         }
         catch (Exception e)
         {
             LoggingUtil.LogError(obj, obj.ErrorPrefix(configNode) + ": The value supplied for " + key + " (" + value + ") is invalid: " + e.Message);
             LoggingUtil.LogDebug(obj, e.StackTrace);
             return(false);
         }
         return(true);
     }
     return(false);
 }
Beispiel #21
0
        /// <summary>
        /// Performs adjustments to the contract type list.  Specifically, disables contract types
        /// as per configuration files and adds addtional ConfiguredContract instances based on the
        /// number on contract types.
        /// </summary>
        /// <returns>Whether the changes took place</returns>
        bool AdjustContractTypes()
        {
            // Don't do anything if the contract system has not yet loaded
            if (ContractSystem.ContractTypes == null)
            {
                return(false);
            }

            LoggingUtil.LogDebug(this.GetType(), "Loading CONTRACT_CONFIGURATOR nodes.");
            ConfigNode[] nodes = GameDatabase.Instance.GetConfigNodes("CONTRACT_CONFIGURATOR");

            // Build a unique list of contract types to disable, in case multiple mods try to
            // disable the same ones.
            Dictionary <string, Type> contractsToDisable = new Dictionary <string, Type>();

            foreach (ConfigNode node in nodes)
            {
                foreach (string contractType in node.GetValues("disabledContractType"))
                {
                    // No type for now
                    contractsToDisable[contractType] = null;
                }
            }

            // Map the string to a type
            foreach (Type subclass in GetAllTypes <Contract>())
            {
                string name = subclass.Name;
                if (contractsToDisable.ContainsKey(name))
                {
                    contractsToDisable[name] = subclass;
                }
            }

            // Start disabling!
            int disabledCounter = 0;

            foreach (KeyValuePair <string, Type> p in contractsToDisable)
            {
                // Didn't find a type
                if (p.Value == null)
                {
                    LoggingUtil.LogWarning(this.GetType(), "Couldn't find ContractType '" + p.Key + "' to disable.");
                }
                else
                {
                    LoggingUtil.LogDebug(this.GetType(), "Disabling ContractType: " + p.Value.FullName + " (" + p.Value.Module + ")");
                    ContractSystem.ContractTypes.Remove(p.Value);
                    disabledCounter++;
                }
            }

            LoggingUtil.LogInfo(this.GetType(), "Disabled " + disabledCounter + " ContractTypes.");

            // Now add the ConfiguredContract type
            int count = (int)(ContractType.AllValidContractTypes.Count() / 3.0 + 0.5);

            for (int i = 0; i < count; i++)
            {
                ContractSystem.ContractTypes.Add(typeof(ConfiguredContract));
            }

            LoggingUtil.LogInfo(this.GetType(), "Finished Adjusting ContractTypes");

            return(true);
        }
Beispiel #22
0
        void Update()
        {
            // Give the contract system a maximum of 5 seconds to start up.  Need to do this because the OnContractsLoaded event isn't fired
            // on a brand new save
            if (contractsLoadCheckTime < 0)
            {
                contractsLoadCheckTime = Time.realtimeSinceStartup;
            }

            // Wait for startup of contract system
            if (ContractSystem.Instance == null || (!contractsLoaded && contractsLoadCheckTime < Time.realtimeSinceStartup + 5.0 && MissionControl.Instance == null))
            {
                return;
            }

            if (contractEnumerator == null)
            {
                contractEnumerator = ContractEnumerator().GetEnumerator();
            }

            // Loop through the enumerator until we run out of time, hit the end or generate a contract
            float start = UnityEngine.Time.realtimeSinceStartup;
            int   count = 0;

            while (UnityEngine.Time.realtimeSinceStartup - start < MAX_TIME && lastGenerationFailure + GLOBAL_FAILURE_WAIT_TIME < Time.realtimeSinceStartup)
            {
                count++;
                if (!contractEnumerator.MoveNext())
                {
                    // We ran through the entire enumerator, mark the failure
                    LoggingUtil.LogVerbose(this, "Contract generation failure");
                    lastGenerationFailure = UnityEngine.Time.realtimeSinceStartup + (float)(rand.NextDouble() * (RANDOM_MAX - RANDOM_MIN) + RANDOM_MIN);
                    contractEnumerator    = null;
                    break;
                }

                ConfiguredContract contract = contractEnumerator.Current;
                if (contract != null)
                {
                    // If the contract is auto-accept, add it immediately
                    if (contract.contractType.autoAccept)
                    {
                        ContractSystem.Instance.Contracts.Add(contract);
                        contract.Accept();
                    }
                    else
                    {
                        contract.preLoaded = true;
                        contracts.Add(contract);
                    }

                    contractEnumerator = null;
                    break;
                }
            }

            if (UnityEngine.Time.realtimeSinceStartup - start > 0.1)
            {
                LoggingUtil.LogDebug(this, "Contract attribute took too long ({0} seconds) to generate: {1}", (UnityEngine.Time.realtimeSinceStartup - start), lastKey);
            }

            // Call update on offered contracts to check expiry, etc - do this infrequently
            if (UnityEngine.Time.frameCount % 20 == 0 && contracts.Count > 0)
            {
                int index = (UnityEngine.Time.frameCount / 20) % contracts.Count;
                contracts[index].Update();
            }
        }
        /// <summary>
        /// Loads all the contact type nodes and creates ContractType objects.
        /// </summary>
        private IEnumerator <YieldInstruction> LoadContractTypeConfig()
        {
            LoggingUtil.LogDebug(this, "Loading CONTRACT_TYPE nodes.");
            ConfigNode[] contractConfigs = GameDatabase.Instance.GetConfigNodes("CONTRACT_TYPE");
            totalContracts = contractConfigs.Count();

            // First pass - create all the ContractType objects
            foreach (ConfigNode contractConfig in contractConfigs)
            {
                // Create the initial contract type
                LoggingUtil.LogVerbose(this, "Pre-load for node: '" + contractConfig.GetValue("name") + "'");
                try
                {
                    ContractType contractType = new ContractType(contractConfig.GetValue("name"));
                }
                catch (ArgumentException)
                {
                    LoggingUtil.LogError(this, "Couldn't load CONTRACT_TYPE '" + contractConfig.GetValue("name") + "' due to a duplicate name.");
                }
            }

            // Second pass - do the actual loading of details
            foreach (ConfigNode contractConfig in contractConfigs)
            {
                attemptedContracts++;
                if (reloading)
                {
                    yield return(new WaitForEndOfFrame());
                }

                // Fetch the contractType
                string       name         = contractConfig.GetValue("name");
                ContractType contractType = ContractType.GetContractType(name);
                if (contractType != null && !contractType.loaded)
                {
                    // Perform the load
                    try
                    {
                        contractType.Load(contractConfig);
                        if (contractType.enabled)
                        {
                            successContracts++;
                        }
                    }
                    catch (Exception e)
                    {
                        LoggingUtil.LogException(e);
                    }
                }
            }

            LoggingUtil.LogInfo(this, "Loaded " + successContracts + " out of " + totalContracts + " CONTRACT_TYPE nodes.");

            // Check for empty groups and warn
            foreach (ContractGroup group in ContractGroup.contractGroups.Values.Where(g => g != null))
            {
                group.CheckEmpty();
            }

            // Load other things
            MissionControlUI.GroupContainer.LoadConfig();

            if (!reloading && LoggingUtil.logLevel == LoggingUtil.LogLevel.DEBUG || LoggingUtil.logLevel == LoggingUtil.LogLevel.VERBOSE)
            {
                ScreenMessages.PostScreenMessage("Contract Configurator: Loaded " + successContracts + " out of " + totalContracts
                                                 + " contracts successfully.", 5, ScreenMessageStyle.UPPER_CENTER);
            }
        }
Beispiel #24
0
 internal static void LogFormatted_DebugOnly(String Message, params Object[] strParams)
 {
     LoggingUtil.LogDebug(typeof(RBWrapper), Message, strParams);
 }
Beispiel #25
0
        protected override bool Generate()
        {
            // MeetsRequirement gets called first and sets the contract type, but check it and
            // select the contract type just in case.
            if (contractType == null)
            {
                if (!SelectContractType())
                {
                    return(false);
                }
            }

            LoggingUtil.LogDebug(this.GetType(), "Generating contract: " + contractType);

            // Set the agent
            if (contractType.agent != null)
            {
                agent = contractType.agent;
            }

            // Set the contract expiry
            if (contractType.minExpiry == 0.0f)
            {
                SetExpiry();
            }
            else
            {
                SetExpiry(contractType.minExpiry, contractType.maxExpiry);
            }

            // Set the contract deadline
            if (contractType.deadline == 0.0f)
            {
                deadlineType = Contract.DeadlineType.None;
            }
            else
            {
                SetDeadlineDays(contractType.deadline, contractType.targetBody);
            }

            // Set rewards
            SetScience(contractType.rewardScience, contractType.targetBody);
            SetReputation(contractType.rewardReputation, contractType.failureReputation, contractType.targetBody);
            SetFunds(contractType.advanceFunds, contractType.rewardFunds, contractType.failureFunds, contractType.targetBody);

            // Generate behaviours
            behaviours = new List <ContractBehaviour>();
            contractType.GenerateBehaviours(this);

            // Generate parameters
            try
            {
                contractType.GenerateParameters(this);
            }
            catch (Exception e)
            {
                Debug.LogException(new Exception("Failed generating parameters for " + contractType, e));
                return(false);
            }

            LoggingUtil.LogInfo(this.GetType(), "Generated contract: " + contractType);
            return(true);
        }
Beispiel #26
0
        /// <summary>
        /// Loads all the contact configuration nodes and creates ContractType objects.
        /// </summary>
        private IEnumerator <YieldInstruction> LoadContractConfig()
        {
            // Load all the contract groups
            LoggingUtil.LogDebug(this.GetType(), "Loading CONTRACT_GROUP nodes.");
            ConfigNode[] contractGroups = GameDatabase.Instance.GetConfigNodes("CONTRACT_GROUP");

            foreach (ConfigNode groupConfig in contractGroups)
            {
                // Create the group
                string name = groupConfig.GetValue("name");
                LoggingUtil.LogInfo(this.GetType(), "Loading CONTRACT_GROUP: '" + name + "'");
                ContractGroup contractGroup = null;
                try
                {
                    contractGroup = new ContractGroup(name);
                }
                catch (ArgumentException)
                {
                    LoggingUtil.LogError(this.GetType(), "Couldn't load CONTRACT_GROUP '" + name + "' due to a duplicate name.");
                }

                // Peform the actual load
                if (contractGroup != null)
                {
                    bool success = false;
                    try
                    {
                        success = contractGroup.Load(groupConfig);
                    }
                    catch (Exception e)
                    {
                        Exception wrapper = new Exception("Error loading CONTRACT_GROUP '" + name + "'", e);
                        LoggingUtil.LogException(wrapper);
                    }
                    finally
                    {
                        if (!success)
                        {
                            ContractGroup.contractGroups.Remove(name);
                        }
                    }
                }
            }

            LoggingUtil.LogDebug(this.GetType(), "Loading CONTRACT_TYPE nodes.");
            ConfigNode[] contractConfigs = GameDatabase.Instance.GetConfigNodes("CONTRACT_TYPE");
            totalContracts = contractConfigs.Count();

            // First pass - create all the ContractType objects
            foreach (ConfigNode contractConfig in contractConfigs)
            {
                // Create the initial contract type
                LoggingUtil.LogVerbose(this.GetType(), "Pre-load for node: '" + contractConfig.GetValue("name") + "'");
                try
                {
                    ContractType contractType = new ContractType(contractConfig.GetValue("name"));
                }
                catch (ArgumentException)
                {
                    LoggingUtil.LogError(this.GetType(), "Couldn't load CONTRACT_TYPE '" + contractConfig.GetValue("name") + "' due to a duplicate name.");
                }
            }

            // Second pass - do the actual loading of details
            foreach (ConfigNode contractConfig in contractConfigs)
            {
                attemptedContracts++;
                yield return(new WaitForEndOfFrame());

                // Fetch the contractType
                string       name         = contractConfig.GetValue("name");
                ContractType contractType = ContractType.GetContractType(name);
                if (contractType != null)
                {
                    LoggingUtil.LogDebug(this.GetType(), "Loading CONTRACT_TYPE: '" + name + "'");
                    // Perform the load
                    try
                    {
                        contractType.Load(contractConfig);
                        if (contractType.enabled)
                        {
                            successContracts++;
                        }
                    }
                    catch (Exception e)
                    {
                        Exception wrapper = new Exception("Error loading CONTRACT_TYPE '" + name + "'", e);
                        LoggingUtil.LogException(wrapper);
                    }
                }
            }

            LoggingUtil.LogInfo(this.GetType(), "Loaded " + successContracts + " out of " + totalContracts + " CONTRACT_TYPE nodes.");

            if (!reloading && LoggingUtil.logLevel == LoggingUtil.LogLevel.DEBUG || LoggingUtil.logLevel == LoggingUtil.LogLevel.VERBOSE)
            {
                ScreenMessages.PostScreenMessage("Contract Configurator: Loaded " + successContracts + " out of " + totalContracts
                                                 + " contracts successfully.", 5, ScreenMessageStyle.UPPER_CENTER);
            }
        }
Beispiel #27
0
        /// <summary>
        /// Loads debugging configurations.
        /// </summary>
        ///
        public static void LoadDebuggingConfig()
        {
            UnityEngine.Debug.Log("[INFO] ContractConfigurator.LoggingUtil: Loading DebuggingConfig node.");
            // Don't know why .GetConfigNode("CC_DEBUGGING") returns null, using .GetConfigNodes("CC_DEBUGGING") works fine.
            ConfigNode[] debuggingConfigs = GameDatabase.Instance.GetConfigNodes("CC_DEBUGGING");

            if (debuggingConfigs.Length > 0)
            {
                try
                {
                    // Fetch config
                    ConfigNode debuggingConfig = debuggingConfigs[0];

                    // Set LogLevel
                    if (debuggingConfig.HasValue("logLevel"))
                    {
                        LoggingUtil.logLevel = (LoggingUtil.LogLevel)Enum.Parse(typeof(LoggingUtil.LogLevel), debuggingConfig.GetValue("logLevel"));
                        LoggingUtil.LogInfo(typeof(LoggingUtil), "Set LogLevel = " + LoggingUtil.logLevel);
                    }

                    // Fetch specific loglevels for given types
                    foreach (ConfigNode levelExceptionNode in debuggingConfig.GetNodes("ADD_LOGLEVEL_EXCEPTION"))
                    {
                        if (levelExceptionNode.HasValue("type") && levelExceptionNode.HasValue("logLevel"))
                        {
                            // Fetch full type name - just search and find the matching one while
                            // ignoring namespace
                            string typeName = levelExceptionNode.GetValue("type");
                            Type   type     = null;
                            foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
                            {
                                try
                                {
                                    foreach (Type t in a.GetTypes())
                                    {
                                        if (t.Name == typeName || t.Name.StartsWith(typeName + '`'))
                                        {
                                            type = t;
                                            break;
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    UnityEngine.Debug.LogWarning("[WARNING] Error loading types from assembly " + a.FullName + ": " + e.Message);
                                }
                            }

                            if (type != null)
                            {
                                LoggingUtil.LogLevel logLevel = (LoggingUtil.LogLevel)Enum.Parse(typeof(LoggingUtil.LogLevel), levelExceptionNode.GetValue("logLevel"));
                                LoggingUtil.AddSpecificLogLevel(type, logLevel);
                                LoggingUtil.LogDebug(typeof(LoggingUtil), "Added log level override (" + type.Name + " => " + logLevel + ")");
                            }
                            else
                            {
                                UnityEngine.Debug.LogWarning("[WARNING] ContractConfigurator.LoggingUtil: Couldn't find Type with name: '" + typeName + "'");
                            }
                        }
                        else
                        {
                            UnityEngine.Debug.LogWarning("[WARNING] ContractConfigurator.LoggingUtil: Couldn't load specific LogLevel node, type or logLevel not given!");
                        }
                    }

                    LoggingUtil.LogInfo(typeof(LoggingUtil), "Debugging config loaded!");
                }
                catch (Exception e)
                {
                    LoggingUtil.ClearSpecificLogLevel();
                    LoggingUtil.logLevel = LoggingUtil.LogLevel.INFO;

                    LoggingUtil.LogWarning(typeof(LoggingUtil), "Debugging Config failed to load! Message: '" + e.Message + "' Set LogLevel to INFO and cleaned specific LogLevels");
                }
            }
            else
            {
                LoggingUtil.logLevel = LoggingUtil.LogLevel.INFO;
                LoggingUtil.LogWarning(typeof(LoggingUtil), "No debugging config found! LogLevel set to INFO");
            }
        }
Beispiel #28
0
        /// <summary>
        /// Tests whether a contract can be offered.
        /// </summary>
        /// <param name="contract">The contract</param>
        /// <returns>Whether the contract can be offered.</returns>
        public bool MeetRequirements(ConfiguredContract contract)
        {
            // Hash check
            if (contract.ContractState == Contract.State.Offered && contract.hash != hash)
            {
                LoggingUtil.LogDebug(this, "Cancelling offered contract of type " + name + ", contract definition changed.");
                return(false);
            }

            // Check prestige
            if (prestige.Count > 0 && !prestige.Contains(contract.Prestige))
            {
                LoggingUtil.LogVerbose(this, "Didn't generate contract type " + name + ", wrong prestige level.");
                return(false);
            }

            // Checks for maxSimultaneous/maxCompletions
            if (maxSimultaneous != 0 || maxCompletions != 0)
            {
                // Get the count of active contracts - excluding ours
                int activeContracts = ContractSystem.Instance.GetCurrentContracts <ConfiguredContract>().
                                      Count(c => c.contractType != null && c.contractType.name == name);
                if (contract.ContractState == Contract.State.Offered || contract.ContractState == Contract.State.Active)
                {
                    activeContracts--;
                }

                // Check if we're breaching the active limit
                if (maxSimultaneous != 0 && activeContracts >= maxSimultaneous)
                {
                    LoggingUtil.LogVerbose(this, "Didn't generate contract type " + name + ", too many active contracts.");
                    return(false);
                }

                // Check if we're breaching the completed limit
                if (maxCompletions != 0)
                {
                    int finishedContracts = ContractSystem.Instance.GetCompletedContracts <ConfiguredContract>().
                                            Count(c => c.contractType != null && c.contractType.name == name);
                    if (finishedContracts + activeContracts >= maxCompletions)
                    {
                        LoggingUtil.LogVerbose(this, "Didn't generate contract type " + name + ", too many completed/active/offered contracts.");
                        return(false);
                    }
                }
            }

            // Check the group values
            if (group != null)
            {
                // Check the group active limit
                int activeContracts = ContractSystem.Instance.GetCurrentContracts <ConfiguredContract>().Count(c => c.contractType != null && c.contractType.group == group);
                if (contract.ContractState == Contract.State.Offered || contract.ContractState == Contract.State.Active)
                {
                    activeContracts--;
                }

                if (group.maxSimultaneous != 0 && activeContracts >= group.maxSimultaneous)
                {
                    LoggingUtil.LogVerbose(this, "Didn't generate contract type " + name + ", too many active contracts in group.");
                    return(false);
                }

                // Check the group completed limit
                if (group.maxCompletions != 0)
                {
                    int finishedContracts = ContractSystem.Instance.GetCompletedContracts <ConfiguredContract>().Count(c => c.contractType != null && c.contractType.group == group);
                    if (finishedContracts + activeContracts >= maxCompletions)
                    {
                        LoggingUtil.LogVerbose(this, "Didn't generate contract type " + name + ", too many completed contracts in group.");
                        return(false);
                    }
                }
            }

            // Check special values are not null
            if (contract.ContractState != Contract.State.Active)
            {
                foreach (KeyValuePair <string, bool> pair in dataValues)
                {
                    // Only check if it is a required value
                    if (pair.Value)
                    {
                        string name = pair.Key;

                        object o = dataNode[name];
                        if (o == null)
                        {
                            LoggingUtil.LogVerbose(this, "Didn't generate contract type " + this.name + ", '" + name + "' was null.");
                            return(false);
                        }
                        else if (o == typeof(List <>))
                        {
                            PropertyInfo prop  = o.GetType().GetProperty("Count");
                            int          count = (int)prop.GetValue(o, null);
                            if (count == 0)
                            {
                                LoggingUtil.LogVerbose(this, "Didn't generate contract type " + this.name + ", '" + name + "' had zero count.");
                                return(false);
                            }
                        }
                        else if (o == typeof(Vessel))
                        {
                            Vessel v = (Vessel)o;

                            if (v.state == Vessel.State.DEAD)
                            {
                                LoggingUtil.LogVerbose(this, "Didn't generate contract type " + this.name + ", vessel '" + v.vesselName + "' is dead.");
                                return(false);
                            }
                        }
                    }
                }
            }

            // Check the captured requirements
            return(ContractRequirement.RequirementsMet(contract, this, requirements));
        }
Beispiel #29
0
        public bool Initialize(ContractType contractType)
        {
            LoggingUtil.LogLevel origLogLevel = LoggingUtil.logLevel;
            try
            {
                this.contractType = contractType;
                if (contractType.trace)
                {
                    LoggingUtil.logLevel = LoggingUtil.LogLevel.VERBOSE;
                }

                LoggingUtil.LogDebug(this, "Initializing contract: " + contractType);

                // Set stuff from contract type
                subType    = contractType.name;
                hash       = contractType.hash;
                AutoAccept = contractType.autoAccept;

                // Set the contract expiry
                if (contractType.maxExpiry == 0.0f)
                {
                    LoggingUtil.LogDebug(this, contractType.name + ": Setting expirty to none");
                    SetExpiry();
                    expiryType = DeadlineType.None;
                }
                else
                {
                    SetExpiry(contractType.minExpiry, contractType.maxExpiry);
                    // Force set the expiry, in stock this is normally done on Contract.Offer()
                    dateExpire = GameTime + TimeExpiry;
                }

                // Set the contract deadline
                if (contractType.deadline == 0.0f)
                {
                    deadlineType = Contract.DeadlineType.None;
                }
                else
                {
                    SetDeadlineDays(contractType.deadline, null);
                }

                // Set rewards
                SetScience(contractType.rewardScience, contractType.targetBody);
                SetReputation(contractType.rewardReputation, contractType.failureReputation, contractType.targetBody);
                SetFunds(contractType.advanceFunds, contractType.rewardFunds, contractType.advanceFunds + contractType.failureFunds, contractType.targetBody);

                // Copy text from contract type
                title            = contractType.title;
                synopsis         = contractType.synopsis;
                completedMessage = contractType.completedMessage;
                notes            = contractType.notes;

                // Set the agent
                if (contractType.agent != null)
                {
                    agent = contractType.agent;
                }
                else
                {
                    agent = AgentList.Instance.GetSuitableAgentForContract(this);
                }

                // Set description
                if (string.IsNullOrEmpty(contractType.description) && agent != null)
                {
                    // Generate the contract description
                    description = TextGen.GenerateBackStories("ConfiguredContract", agent.Name, contractType.topic, contractType.subject, random.Next(), true, true, true);
                }
                else
                {
                    description = contractType.description;
                }

                // Generate behaviours
                behaviours = new List <ContractBehaviour>();
                if (!contractType.GenerateBehaviours(this))
                {
                    return(false);
                }

                // Generate parameters
                bool paramsGenerated = contractType.GenerateParameters(this);
                bodiesLoaded = false;
                contractType.contractBodies = ContractBodies;
                if (!paramsGenerated)
                {
                    return(false);
                }

                // Do a very late research bodies check
                try
                {
                    contractType.ResearchBodiesCheck(this);
                }
                catch (ContractRequirementException)
                {
                    return(false);
                }

                // Copy in the requirement nodes
                requirements = new List <ContractRequirement>();
                foreach (ContractRequirement requirement in contractType.Requirements)
                {
                    requirements.Add(requirement);
                }

                LoggingUtil.LogDebug(this, "Initialized contract: " + contractType);
                return(true);
            }
            catch (Exception e)
            {
                LoggingUtil.LogError(this, "Error initializing contract " + contractType);
                LoggingUtil.LogException(e);
                ExceptionLogWindow.DisplayFatalException(ExceptionLogWindow.ExceptionSituation.CONTRACT_GENERATION, e,
                                                         contractType == null ? "unknown" : contractType.FullName);

                return(false);
            }
            finally
            {
                LoggingUtil.logLevel = origLogLevel;
            }
        }
Beispiel #30
0
        protected override bool Generate()
        {
            // MeetsRequirement gets called first and sets the contract type, but check it and
            // select the contract type just in case.
            if (contractType == null)
            {
                if (!SelectContractType())
                {
                    return(false);
                }
            }

            LoggingUtil.LogDebug(this.GetType(), "Generating contract: " + contractType);

            hash = contractType.hash;

            // Set the agent
            if (contractType.agent != null)
            {
                agent = contractType.agent;
            }

            // Set the contract expiry
            if (contractType.maxExpiry == 0.0f)
            {
                SetExpiry();
                expiryType = DeadlineType.None;
            }
            else
            {
                SetExpiry(contractType.minExpiry, contractType.maxExpiry);
            }

            // Set the contract deadline
            if (contractType.deadline == 0.0f)
            {
                deadlineType = Contract.DeadlineType.None;
            }
            else
            {
                SetDeadlineDays(contractType.deadline, contractType.targetBody);
            }

            // Set rewards
            SetScience(contractType.rewardScience, contractType.targetBody);
            SetReputation(contractType.rewardReputation, contractType.failureReputation, contractType.targetBody);
            SetFunds(contractType.advanceFunds, contractType.rewardFunds, contractType.failureFunds, contractType.targetBody);

            // Copy text from contract type
            title            = contractType.title;
            synopsis         = contractType.synopsis;
            completedMessage = contractType.completedMessage;
            notes            = contractType.notes;

            // Set description
            if (string.IsNullOrEmpty(contractType.description))
            {
                if (agent == null)
                {
                    agent = AgentList.Instance.GetSuitableAgentForContract(this);
                }

                // Generate the contract description
                description = TextGen.GenerateBackStories(agent.Name, agent.GetMindsetString(),
                                                          contractType.topic, contractType.subject, contractType.motivation, MissionSeed);
            }
            else
            {
                description = contractType.description;
            }

            // Generate behaviours
            behaviours = new List <ContractBehaviour>();
            if (!contractType.GenerateBehaviours(this))
            {
                return(false);
            }

            // Generate parameters
            try
            {
                if (!contractType.GenerateParameters(this))
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                LoggingUtil.LogException(new Exception("Failed generating parameters for " + contractType, e));
                return(false);
            }

            LoggingUtil.LogInfo(this.GetType(), "Generated contract: " + contractType);
            return(true);
        }