Exemplo n.º 1
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));
        }
Exemplo n.º 2
0
        void Update()
        {
            // Load all the contract configurator configuration
            if (HighLogic.LoadedScene == GameScenes.MAINMENU && !loaded)
            {
                LoggingUtil.LoadDebuggingConfig();
                RegisterParameterFactories();
                RegisterBehaviourFactories();
                RegisterContractRequirements();
                LoadContractConfig();
                loaded = true;
            }
            // Try to disable the contract types
            else if ((HighLogic.LoadedScene == GameScenes.SPACECENTER) && !contractTypesAdjusted)
            {
                if (AdjustContractTypes())
                {
                    contractTypesAdjusted = true;
                }
            }

            // Alt-F9 shows the contract configurator window
            if (GameSettings.MODIFIER_KEY.GetKey() && Input.GetKeyDown(KeyCode.F10))
            {
                showGUI = !showGUI;
            }

            // Check if the ContractsApp has just become visible, and fire off an update event
            if (!contractsAppVisible &&
                ContractsApp.Instance != null &&
                ContractsApp.Instance.appLauncherButton != null &&
                ContractsApp.Instance.cascadingList.cascadingList != null &&
                ContractsApp.Instance.cascadingList.cascadingList.gameObject.activeInHierarchy)
            {
                contractsAppVisible = true;

                // Fire off an event for each contract
                for (int i = 0; i < ContractSystem.Instance.Contracts.Count; i++)
                {
                    Contract contract = ContractSystem.Instance.Contracts[i];
                    if (contract.ContractState == Contract.State.Active && contract.GetType() == typeof(ConfiguredContract))
                    {
                        GameEvents.Contract.onParameterChange.Fire(contract, contract.GetParameter(0));
                    }
                }
            }
        }
Exemplo n.º 3
0
        public static string KerbalName(string defaultName)
        {
            LoggingUtil.LogVerbose(typeof(DraftTwitchViewers), "KerbalName()");

            if (Instance != null && Instance.nameQueue.Any() && HighLogic.LoadedScene != GameScenes.MAINMENU)
            {
                string name = Instance.nameQueue.Dequeue();
                Instance.recentNames.Enqueue(name);

                LoggingUtil.LogVerbose(typeof(DraftTwitchViewers), "    " + name);
                return(name);
            }
            else
            {
                return(defaultName);
            }
        }
Exemplo n.º 4
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");
        }
Exemplo n.º 5
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);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Performs validation to check if the given config node has values that were not expected.
        /// </summary>
        /// <param name="configNode">The ConfigNode to check.</param>
        /// <param name="obj">IContractConfiguratorFactory object for error reporting</param>
        /// <returns>Always true, but logs a warning if unexpected keys were found</returns>
        public static bool ValidateUnexpectedValues(ConfigNode configNode, IContractConfiguratorFactory obj)
        {
            bool valid = true;

            if (!keysFound.ContainsKey(configNode))
            {
                obj.hasWarnings = true;
                LoggingUtil.LogWarning(obj.GetType(), obj.ErrorPrefix() +
                                       ": did not attempt to load values for ConfigNode!");
                return(false);
            }

            Dictionary <string, int> found = keysFound[configNode];

            foreach (ConfigNode.Value pair in configNode.values)
            {
                if (!found.ContainsKey(pair.name))
                {
                    obj.hasWarnings = true;
                    LoggingUtil.LogWarning(obj.GetType(), obj.ErrorPrefix() +
                                           ": unexpected attribute '" + pair.name + "' found, ignored.");
                }
            }

            foreach (ConfigNode child in configNode.nodes)
            {
                // Exceptions
                if (child.name == "PARAMETER" && (obj is ContractType || obj is ParameterFactory) ||
                    child.name == "REQUIREMENT" && (obj is ContractType || obj is ParameterFactory || obj is ContractRequirement) ||
                    child.name == "BEHAVIOUR" && (obj is ContractType) ||
                    child.name == "ORBIT" && (obj is Behaviour.OrbitGeneratorFactory || obj is Behaviour.SpawnVesselFactory || obj is Behaviour.SpawnKerbalFactory))
                {
                    continue;
                }

                if (!found.ContainsKey(child.name))
                {
                    obj.hasWarnings = true;
                    LoggingUtil.LogWarning(obj.GetType(), obj.ErrorPrefix() +
                                           ": unexpected child node '" + child.name + "' found, ignored.");
                }
            }


            return(valid);
        }
        /*
         * 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);
            }
        }
Exemplo n.º 8
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");
        }
        public override bool Load(ConfigNode configNode)
        {
            // Load base class
            bool valid = base.Load(configNode);

            if (configNode.HasValue("vesselKey"))
            {
                LoggingUtil.LogWarning(this, "The 'vesselKey' attribute is obsolete as of Contract Configurator 0.7.5.  It will be removed in 1.0.0 in favour of the vessel attribute.");
                valid &= ConfigNodeUtil.ParseValue <VesselIdentifier>(configNode, "vesselKey", x => vesselKey = x, this);
            }
            else
            {
                valid &= ConfigNodeUtil.ParseValue <VesselIdentifier>(configNode, "vessel", x => vesselKey = x, this);
            }

            return(valid);
        }
        public override bool Load(ConfigNode configNode)
        {
            // Load base class
            bool valid = base.Load(configNode);

            // Get type
            string contractType = null;

            valid &= ConfigNodeUtil.ParseValue <string>(configNode, "contractType", x => contractType = x, this);
            if (valid)
            {
                if (ContractType.GetContractType(contractType) != null)
                {
                    ccType = contractType;
                }
                else
                {
                    ccType = null;

                    // Search for the correct type
                    var classes =
                        from assembly in AppDomain.CurrentDomain.GetAssemblies()
                        from type in assembly.GetTypes()
                        where type.IsSubclassOf(typeof(Contract)) && type.Name.Equals(contractType)
                        select type;

                    if (classes.Count() < 1)
                    {
                        valid = false;
                        LoggingUtil.LogError(this.GetType(), "contractType '" + contractType +
                                             "' must either be a Contract sub-class or ContractConfigurator contract type");
                    }
                    else
                    {
                        contractClass = classes.First();
                    }
                }
            }

            valid &= ConfigNodeUtil.ParseValue <uint>(configNode, "minCount", x => minCount = x, this, 1);
            valid &= ConfigNodeUtil.ParseValue <uint>(configNode, "maxCount", x => maxCount = x, this, UInt32.MaxValue);
            valid &= ConfigNodeUtil.ParseValue <Duration>(configNode, "cooldownDuration", x => cooldownDuration = x, this, new Duration(0.0));

            return(valid);
        }
Exemplo n.º 11
0
        protected virtual void OnVesselDestroy(Vessel vessel)
        {
            LoggingUtil.LogVerbose(this, "OnVesselDestroy " + vessel.id);

            if (HighLogic.LoadedScene != GameScenes.FLIGHT)
            {
                LoggingUtil.LogVerbose(this, "   returning, not in flight scene");
                return;
            }

            // Try to change any associations over if this is due to a docking event
            foreach (string key in GetAssociatedKeys(vessel).ToList())
            {
                LoggingUtil.LogVerbose(this, "    checking key " + key);

                // Check if we need to switch over to the newly created vessel
                VesselInfo vi        = vessels[key];
                Vessel     newVessel = FlightGlobals.Vessels.Find(v => {
                    if (v != null && v != vessel)
                    {
                        LoggingUtil.LogVerbose(this, "    loading protovessel for " + v.vesselName);

                        // If the vessel is loaded, refresh the protovessel.  We do this to support
                        // grappling - when a new vessel is grappled the protovessel information
                        // doesn't get properly updated.
                        if (v.loaded)
                        {
                            v.protoVessel = new ProtoVessel(v);
                        }

                        return(v.GetHashes().Contains(vi.hash));
                    }
                    return(false);
                });

                if (newVessel != null)
                {
                    vi.id = newVessel.id;
                }
                else
                {
                    AssociateVessel(key, null);
                }
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Method for generating ContractParameter objects.  This will call the Generate() method
        /// on the sub-class, load all common parameters and load child parameters.
        /// </summary>
        /// <param name="contract">Contract to generate for</param>
        /// <param name="contractParamHost">Parent object for the ContractParameter</param>
        /// <returns>Generated ContractParameter</returns>
        public virtual ContractParameter Generate(ConfiguredContract contract, IContractParameterHost contractParamHost)
        {
            // First check any requirements
            if (!ContractRequirement.RequirementsMet(contract, contract.contractType, requirements))
            {
                LoggingUtil.LogVerbose(typeof(ParameterFactory), "Returning null for " + contract.contractType.name + "." + name + ": requirements not met.");
                return(null);
            }

            // Generate a parameter using the sub-class logic
            ContractParameter parameter = Generate(contract);

            if (parameter == null)
            {
                throw new Exception(GetType().FullName + ".Generate() returned a null ContractParameter!");
            }

            // Add ContractParameter to the host
            contractParamHost.AddParameter(parameter);

            // Set the funds/science/reputation parameters
            parameter.SetFunds(rewardFunds, failureFunds, targetBody);
            parameter.SetReputation(rewardReputation, failureReputation, targetBody);
            parameter.SetScience(rewardScience, targetBody);

            // Set other flags
            parameter.Optional = optional;
            if (disableOnStateChange != null)
            {
                parameter.DisableOnStateChange = (bool)disableOnStateChange;
            }
            parameter.ID = name;

            // Special stuff for contract configurator parameters
            ContractConfiguratorParameter ccParam = parameter as ContractConfiguratorParameter;

            if (ccParam != null)
            {
                ccParam.completeInSequence = completeInSequence;
                ccParam.notes        = notes;
                ccParam.hideChildren = hideChildren;
            }

            return(parameter);
        }
Exemplo n.º 13
0
        protected override void OnLoad(ConfigNode node)
        {
            try
            {
                subType          = node.GetValue("subtype");
                contractType     = string.IsNullOrEmpty(subType) ? null : ContractType.GetContractType(subType);
                title            = ConfigNodeUtil.ParseValue <string>(node, "title", contractType != null ? contractType.title : subType);
                description      = ConfigNodeUtil.ParseValue <string>(node, "description", contractType != null ? contractType.description : "");
                synopsis         = ConfigNodeUtil.ParseValue <string>(node, "synopsis", contractType != null ? contractType.synopsis : "");
                completedMessage = ConfigNodeUtil.ParseValue <string>(node, "completedMessage", contractType != null ? contractType.completedMessage : "");
                notes            = ConfigNodeUtil.ParseValue <string>(node, "notes", contractType != null ? contractType.notes : "");
                hash             = ConfigNodeUtil.ParseValue <int>(node, "hash", contractType != null ? contractType.hash : 0);

                foreach (ConfigNode child in node.GetNodes("BEHAVIOUR"))
                {
                    ContractBehaviour behaviour = ContractBehaviour.LoadBehaviour(child, this);
                    behaviours.Add(behaviour);
                }

                // If the contract type is null, then it likely means that it was uninstalled
                if (contractType == null)
                {
                    LoggingUtil.LogWarning(this, "Error loading contract for contract type '" + subType +
                                           "'.  The contract type either failed to load or was uninstalled.");
                    try
                    {
                        SetState(State.Failed);
                    }
                    catch { }
                    return;
                }
            }
            catch (Exception e)
            {
                LoggingUtil.LogError(this, "Error loading contract from persistance file!");
                LoggingUtil.LogException(e);
                ExceptionLogWindow.DisplayFatalException(ExceptionLogWindow.ExceptionSituation.CONTRACT_LOAD, e, this);

                try
                {
                    SetState(State.Failed);
                }
                catch { }
            }
        }
Exemplo n.º 14
0
        public static void SetContractToDisabled(string contract, ContractGroup group)
        {
            Type contractType = contractTypes.Where(t => t.Name == contract).FirstOrDefault();

            if (contractType == null)
            {
                LoggingUtil.LogWarning(typeof(ContractDisabler), "Couldn't find ContractType '" + contract + "' to disable.");
            }

            if (!contractDetails.ContainsKey(contractType))
            {
                contractDetails[contractType] = new ContractDetails(contractType);
            }
            ContractDetails details = contractDetails[contractType];

            details.disablingGroups.AddUnique(group);
            SetContractState(contractType, false);
        }
        public override void OnSave(ConfigNode node)
        {
            try
            {
                base.OnSave(node);

                foreach (ScienceSubject s in trackedSubjects)
                {
                    node.AddValue("subject", s.id);
                }
            }
            catch (Exception e)
            {
                LoggingUtil.LogError(this, "Error saving ScienceReporter to persistance file!");
                LoggingUtil.LogException(e);
                ExceptionLogWindow.DisplayFatalException(ExceptionLogWindow.ExceptionSituation.SCENARIO_MODULE_SAVE, e, "ScienceReporter");
            }
        }
        /// <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);
            }
        }
Exemplo n.º 17
0
 public override void OnSave(ConfigNode node)
 {
     try
     {
         foreach (ConfiguredContract contract in contracts.Where(c => c.ContractState == Contract.State.Offered))
         {
             ConfigNode child = new ConfigNode("CONTRACT");
             node.AddNode(child);
             contract.Save(child);
         }
     }
     catch (Exception e)
     {
         LoggingUtil.LogError(this, "Error saving ContractPreLoader to persistance file!");
         LoggingUtil.LogException(e);
         ExceptionLogWindow.DisplayFatalException(ExceptionLogWindow.ExceptionSituation.SCENARIO_MODULE_SAVE, e, "ContractPreLoader");
     }
 }
Exemplo n.º 18
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);
            }
        }
Exemplo n.º 19
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);
     }
 }
Exemplo n.º 20
0
 public override bool MeetRequirements()
 {
     // No ContractType chosen
     if (contractType == null)
     {
         return(SelectContractType());
     }
     else
     {
         // ContractType already chosen, check if still meets requirements.
         bool meets = contractType.MeetRequirements(this);
         if (ContractState == State.Active && !meets)
         {
             LoggingUtil.LogWarning(this, "Removed contract '" + title + "', as it no longer meets the requirements.");
         }
         return(meets);
     }
 }
Exemplo n.º 21
0
        /// <summary>
        /// Creates a permanent link between the given vessel and key.
        /// </summary>
        /// <param name="key">The key to create an association with.</param>
        /// <param name="vessel">The vessel that will be associated with the key</param>
        public void AssociateVessel(string key, Vessel vessel)
        {
            // Already associated!
            if (vessel != null && vessels.ContainsKey(key) && vessels[key].id == vessel.id)
            {
                return;
            }
            else if (vessel == null && !vessels.ContainsKey(key))
            {
                return;
            }

            if (vessel != null)
            {
                LoggingUtil.LogVerbose(this, "Associating vessel " + vessel.id + " with key '" + key + "'.");
            }
            else
            {
                LoggingUtil.LogVerbose(this, "Disassociating key '" + key + "'.");
            }

            // First remove whatever was there
            if (vessels.ContainsKey(key))
            {
                Guid   oldVesselId = vessels[key].id;
                Vessel oldVessel   = FlightGlobals.Vessels.Find(v => v != null && v.id == oldVesselId);
                vessels.Remove(key);

                if (oldVessel != null)
                {
                    LoggingUtil.LogVerbose(this, "Firing OnVesselDisassociation.");
                    OnVesselDisassociation.Fire(new GameEvents.HostTargetAction <Vessel, string>(oldVessel, key));
                }
            }

            // Add the new vessel
            if (vessel != null)
            {
                vessels[key] = new VesselInfo(vessel);
                LoggingUtil.LogVerbose(this, "Firing OnVesselAssociation.");
                OnVesselAssociation.Fire(new GameEvents.HostTargetAction <Vessel, string>(vessel, key));
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Checks if all the given ContractRequirement meet the requirement.
        /// </summary>
        /// <param name="contract">Contract to check</param>
        /// <param name="contractType">Contract type of the contract (in case the contract type has not yet been assigned).</param>
        /// <param name="contractRequirements">The list of requirements to check</param>
        /// <returns>Whether the requirement is met or not.</returns>
        public static bool RequirementsMet(ConfiguredContract contract, ContractType contractType, IEnumerable <ContractRequirement> contractRequirements)
        {
            bool allReqMet = true;

            try
            {
                LoggingUtil.LogVerbose(typeof(ContractRequirement), "Checking requirements for contract '{0}'", contractType.name);
                foreach (ContractRequirement requirement in contractRequirements)
                {
                    if (requirement.enabled)
                    {
                        if (requirement.checkOnActiveContract || contract == null || contract.ContractState != Contract.State.Active)
                        {
                            allReqMet = allReqMet && requirement.CheckRequirement(contract);

                            if (!allReqMet)
                            {
                                LoggingUtil.Log(contract != null && contract.ContractState == Contract.State.Active ? LoggingUtil.LogLevel.INFO :
                                                contract != null && contract.ContractState == Contract.State.Offered ? LoggingUtil.LogLevel.DEBUG : LoggingUtil.LogLevel.VERBOSE,
                                                requirement.GetType(), "Contract {0}: requirement {1} was not met.", contractType.name, requirement.name);
                                break;
                            }
                        }
                    }
                }

                // Force fail the contract if a requirement becomes unmet
                if (contract != null && contract.ContractState == Contract.State.Active && !allReqMet)
                {
                    // Fail the contract - unfortunately, the player won't know why. :(
                    contract.Fail();

                    // Force the stock contracts window to refresh
                    GameEvents.Contract.onContractsLoaded.Fire();
                }
            }
            catch (Exception e)
            {
                LoggingUtil.LogException(new Exception("ContractConfigurator: Exception checking requirements!", e));
                return(false);
            }
            return(allReqMet);
        }
        /*
         * Loads a behaviour from a ConfigNode.
         */
        public static ContractBehaviour LoadBehaviour(ConfigNode configNode, ConfiguredContract contract)
        {
            // Determine the type
            string typeName = configNode.GetValue("type");
            Type   type     = Type.GetType(typeName);

            if (type == null)
            {
                LoggingUtil.LogError(typeof(ContractBehaviour), "No ContractBehaviour with type = '" + typeName + "'.");
                return(null);
            }

            // Instantiate and load
            ContractBehaviour behaviour = (ContractBehaviour)Activator.CreateInstance(type);

            behaviour.contract = contract;
            behaviour.Load(configNode);
            return(behaviour);
        }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            IEnumerable <UpgradeableFacility> facilities = UnityEngine.Object.FindObjectsOfType <UpgradeableFacility>().
                                                           Where <UpgradeableFacility>(f => f.name == facility);

            if (facilities.Count() > 0)
            {
                UpgradeableFacility upgradeableFacility = facilities.First <UpgradeableFacility>();

                int level = upgradeableFacility.FacilityLevel;
                return(level >= minLevel && level <= maxLevel);
            }
            else
            {
                // Should only get here if the facility name entered was bad
                LoggingUtil.LogError(this, "Coudn't read find facility with name '" + facility + "'!");
                return(false);
            }
        }
Exemplo n.º 25
0
        public static void OnSuccess(Dictionary <string, string> dict)
        {
            Instance.routinesRunning--;
            if (!dict.ContainsKey("name"))
            {
                return;
            }

            string name = dict["name"];

            LoggingUtil.LogVerbose(typeof(DraftTwitchViewers), "DraftTwitchViewers Success: " + name);

            // Queue the name if it is new
            if (Instance.IsUnique(name))
            {
                Instance.nameQueue.Enqueue(name);
                Instance.names.Add(name);
            }
        }
        /// <summary>
        /// Reverses the localization of a string and gets the parameters out (as strings)
        /// </summary>
        /// <param name="input">Input string</param>
        /// <param name="localizationTag">Localization tag to use to reverse localization.</param>
        /// <returns></returns>
        public static IList <string> UnLocalizeString(string input, string localizationTag)
        {
            LoggingUtil.LogVerbose(typeof(LocalizationUtil), "UnLocalizeString('{0}', '{1}')", input, localizationTag);
            unlocalizedStringStorage.Clear();

            int inputPos   = 0;
            int currentPos = 0;
            int paramIndex = localizationTag.IndexOf("<<", currentPos);
            int len        = localizationTag.Length;

            while (paramIndex >= 0 && paramIndex < len)
            {
                // Fast forward the input to the same location.
                inputPos += paramIndex - currentPos;

                //<<1>> <<2>>
                // Get the location of the *next* parameter
                currentPos = paramIndex + 5;
                paramIndex = localizationTag.IndexOf("<<", currentPos);
                if (paramIndex == -1)
                {
                    paramIndex = len;
                }

                // Get the next literal part of the localization tag
                string searchValue = localizationTag.Substring(currentPos, paramIndex - currentPos);
                int    index       = (currentPos == paramIndex) ? input.Length : input.IndexOf(searchValue, inputPos);
                if (index == -1)
                {
                    LoggingUtil.LogError(typeof(LocalizationUtil), "Couldn't unlocalize string '{0}'", input);
                    return(unlocalizedStringStorage.AsReadOnly());
                }

                // Get the parameter and fast forward past it
                string parameterValue = input.Substring(inputPos, index - inputPos);
                inputPos = index;
                LoggingUtil.LogVerbose(typeof(LocalizationUtil), "   adding parameter '{0}'", parameterValue);
                unlocalizedStringStorage.Add(parameterValue);
            }

            return(unlocalizedStringStorage.AsReadOnly());
        }
        protected virtual void OnVesselDestroy(Vessel vessel)
        {
            LoggingUtil.LogVerbose(this, "OnVesselDestroy " + vessel.id);

            // Try to change any associations over if this is due to a docking event
            foreach (string key in GetAssociatedKeys(vessel).ToList())
            {
                // Check if we need to switch over to the newly created vessel
                VesselInfo vi        = vessels[key];
                Vessel     newVessel = FlightGlobals.Vessels.Find(v => v != vessel && v.GetHashes().Contains(vi.hash));
                if (newVessel != null)
                {
                    vi.id = newVessel.id;
                }
                else
                {
                    AssociateVessel(key, null);
                }
            }
        }
        public override bool LoadFromConfig(ConfigNode configNode)
        {
            // Before loading, verify the SCANsat version
            if (!SCANsatUtil.VerifySCANsatVersion())
            {
                return(false);
            }

            // Load base class
            bool valid = base.LoadFromConfig(configNode);

            // Do not check the requirement on active contracts.  Otherwise when they scan the
            // contract is invalidated, which is usually not what's meant.
            checkOnActiveContract = false;

            valid &= ConfigNodeUtil.ParseValue <string>(configNode, "scanType", x => scanType = x, this, "Anomaly", SCANsatUtil.ValidateSCANname);
            valid &= ConfigNodeUtil.ParseValue <double>(configNode, "latitude", x => latitude = x, this, 0.0);
            valid &= ConfigNodeUtil.ParseValue <double>(configNode, "longitude", x => longitude = x, this, 0.0);

            valid &= ConfigNodeUtil.MutuallyExclusive(configNode, new string[] { "latitude", "longitude" }, new string[] { "pqsCity" }, this);
            valid &= ValidateTargetBody(configNode);

            string pqsName = null;

            valid &= ConfigNodeUtil.ParseValue <string>(configNode, "pqsCity", x => pqsName = x, this, (string)null);
            if (pqsName != null)
            {
                try
                {
                    pqsCity = targetBody.GetComponentsInChildren <PQSCity>(true).Where(pqs => pqs.name == pqsName).First();
                }
                catch (Exception e)
                {
                    LoggingUtil.LogError(this, "Couldn't load PQSCity with name '" + pqsCity + "'");
                    LoggingUtil.LogException(e);
                    valid = false;
                }
            }

            return(valid);
        }
        /// <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);
            }
        }
Exemplo n.º 30
0
        void OnContractDecline(Contract c)
        {
            LoggingUtil.LogVerbose(this, "OnContractDecline");

            // Reset generation failures for just this contract type
            ConfiguredContract cc = c as ConfiguredContract;

            if (cc != null)
            {
                if (cc.preLoaded)
                {
                    contracts.Remove(cc);
                }
                if (cc.contractType != null)
                {
                    lastGenerationFailure = -100.0;
                    cc.contractType.failedGenerationAttempts = 0;
                    cc.contractType.lastGenerationFailure    = -100.0;
                }
            }
        }