void GatherResources(ref Dictionary <ResourceName, double> amounts, ref Dictionary <ResourceName, double> maxAmounts) { foreach (var part in vessel.Parts) { foreach (var resource in part.Resources) { if (resource.maxAmount == 0) { continue; } var resourceID = ResourceSettings.NameToResource(resource.resourceName); if (resourceID == ResourceName.Unknown) { Debug.Log($"[KITResourceManager.GatherResources] ignoring unknown resource {resource.resourceName}"); continue; } if (amounts.ContainsKey(resourceID) == false) { amounts[resourceID] = maxAmounts[resourceID] = 0; } amounts[resourceID] += resource.amount; maxAmounts[resourceID] += resource.maxAmount; } } }
void DisperseResources(ref Dictionary <ResourceName, double> available) { foreach (var part in vessel.Parts) { foreach (var resource in part.Resources) { var resourceID = ResourceSettings.NameToResource(resource.resourceName); if (resourceID == ResourceName.Unknown) { Debug.Log($"[KITResourceManager.DisperseResources] ignoring unknown resource {resource.resourceName}"); continue; } if (available.ContainsKey(resourceID) == false) { return; // Shouldn't happen } if (available[resourceID] == 0) { return; } var tmp = Math.Min(available[resourceID], resource.maxAmount); available[resourceID] -= tmp; resource.amount = tmp; } } }
private bool CheckClientVersion(int majorVersion, int buildVersion, string appVersion, string resourceSha, bool androidClient) { if (majorVersion != LogicVersion.MAJOR_VERSION || buildVersion != LogicVersion.BUILD_VERSION || (appVersion != null && !EnvironmentSettings.IsSupportedAppVersion(appVersion))) { LoginFailedMessage loginFailedMessage = new LoginFailedMessage(); loginFailedMessage.SetErrorCode(LoginFailedMessage.ErrorCode.CLIENT_VERSION); loginFailedMessage.SetUpdateUrl(ResourceSettings.GetAppStoreUrl(androidClient)); this.SendMessage(loginFailedMessage); return(false); } if (resourceSha != ResourceManager.FINGERPRINT_SHA) { LoginFailedMessage loginFailedMessage = new LoginFailedMessage(); loginFailedMessage.SetErrorCode(LoginFailedMessage.ErrorCode.DATA_VERSION); loginFailedMessage.SetContentUrl(ResourceSettings.GetContentUrl()); loginFailedMessage.SetContentUrlList(ResourceSettings.ContentUrlList); loginFailedMessage.SetCompressedFingerprint(ResourceManager.COMPRESSED_FINGERPRINT_DATA); this.SendMessage(loginFailedMessage); return(false); } return(true); }
// todo? live update from trade menu pre-confirm void UpdateAmounts() { var foundParts = CountAll(Find.CurrentMap, neededParts.Keys, null, false, true); var missingParts = new Dictionary <ThingDef, int>(); foreach (var neededPart in neededParts) { missingParts[neededPart.Key] = Math.Max(neededPart.Value - foundParts.TryGetValue(neededPart.Key), 0); } var neededShallowResources = new Dictionary <ThingDef, int>(); foreach (var missingPart in missingParts) { foreach (var neededShallowResource in missingPart.Key.costList) // of just missing parts { neededShallowResources[neededShallowResource.thingDef] = neededShallowResources.TryGetValue(neededShallowResource.thingDef) + missingPart.Value * neededShallowResource.count; } } var lookedInFrames = missingParts.Where(x => x.Value > 0).Select(x => x.Key.frameDef).ToList(); var foundShallowResources = CountAll(Find.CurrentMap, neededShallowResources.Keys, lookedInFrames, false, false); // base on neededShallowResources so we have ALL keys together var neededResources = new Dictionary <ThingDef, int>(neededShallowResources); foreach (var neededShallowResource in neededShallowResources) { var ingredientCounts = IngredientCountsFor(ResourceSettings.RecipeFor(neededShallowResource.Key)); if (ingredientCounts == null) { continue; } var missingShallowResourceCount = Math.Max(neededShallowResource.Value - foundShallowResources[neededShallowResource.Key], 0); foreach (var ingredientCount in ingredientCounts) // of just missing shallow resources { neededResources[ingredientCount.thingDef] = neededShallowResources.TryGetValue(ingredientCount.thingDef) + missingShallowResourceCount * ingredientCount.count; } } var newDefsFromIngredients = neededResources.Keys.Except(neededShallowResources.Keys); var foundDeepResources = CountAll(Find.CurrentMap, newDefsFromIngredients, lookedInFrames, false, false); var foundResources = foundShallowResources.Concat(foundDeepResources).ToDictionary(x => x.Key, x => x.Value); var missingResources = neededResources.ToDictionary(cost => cost.Key, cost => Math.Max(cost.Value - foundResources[cost.Key], 0)); resourceAmounts = missingResources; //Debug.WriteLine($"Needed parts: {neededParts.ToStringFullContents()}"); //Debug.WriteLine($"Found parts: {foundParts.ToStringFullContents()}"); //Debug.WriteLine($"Missing parts: {missingParts.ToStringFullContents()}"); //Debug.WriteLine($"Included frame containers: {lookedInFrames.ToStringSafeEnumerable()}"); //Debug.WriteLine($"Needed shallow resources: {neededShallowResources.ToStringFullContents()}"); //Debug.WriteLine($"Needed resources: {neededResources.ToStringFullContents()}"); //Debug.WriteLine($"Found resources: {foundResources.ToStringFullContents()}"); //Debug.WriteLine($"Missing resources: {missingResources.ToStringFullContents()}"); }
protected ResourceConfiguration() { const string baseDir = "Data/Crafting"; Ores = ZhConfig.DeserializeJsonConfig <ResourceSettings <OreEntry> >($"{baseDir}/ores.json"); Sand = ZhConfig.DeserializeJsonConfig <ResourceSettings <OreEntry> >($"{baseDir}/sand.json"); Clay = ZhConfig.DeserializeJsonConfig <ResourceSettings <OreEntry> >($"{baseDir}/clay.json"); Logs = ZhConfig.DeserializeJsonConfig <ResourceSettings <LogEntry> >($"{baseDir}/logs.json"); Hides = ZhConfig.DeserializeJsonConfig <ResourceSettings <HideEntry> >($"{baseDir}/hides.json"); Fish = ZhConfig.DeserializeJsonConfig <ResourceSettings <FishEntry> >($"{baseDir}/fish.json"); }
/// <summary> /// Use to update a database record /// </summary> /// <param name="view">Resource Settings</param> /// <returns>ResourceSettings</returns> internal virtual ResourceSettings ToEntity(ResourceSettings view = null) { if (view == null) { view = new ResourceSettings(); } view.Status = Status; return(view); }
internal ResourceSettingsVm(ResourceSettings view = null) { if (view == null) { return; } _id = view.Id; Status = view.Status; }
/// <summary> /// Called by the IKITMod to consume resources present on a vessel. It automatically converts the wanted amount by the appropriate value to /// give you a per-second resource consumption. /// </summary> /// <param name="resource">Resource to consume</param> /// <param name="wanted">How much you want</param> /// <returns>How much you got</returns> double IResourceManager.ConsumeResource(ResourceName resource, double wanted) { ResourceSettings.ValidateResource(resource); if (!inExecuteKITModules) { Debug.Log("[KITResourceManager.ConsumeResource] don't do this."); return(0); } if (myCheatOptions.InfiniteElectricity && resource == ResourceName.ElectricCharge) { return(wanted); } if (currentResources.ContainsKey(resource) == false) { currentResources[resource] = 0; } double obtainedAmount = 0; double modifiedAmount = wanted * fixedDeltaTime; var tmp = Math.Min(currentResources[resource], modifiedAmount); obtainedAmount += tmp; currentResources[resource] -= tmp; if (obtainedAmount >= modifiedAmount) { return(wanted); } // XXX - todo. At this stage, we might want to try requesting more than we need to refill the resources on hand. // Some % of total capacity or something like that? Might reduce some future calls // Convert to seconds obtainedAmount = wanted * (obtainedAmount / modifiedAmount); obtainedAmount = CallVariableSuppliers(resource, obtainedAmount, wanted); //return obtainedAmount; // is it close enough to being fully requested? (accounting for precision issues) if (modifiedAmount * fudgeFactor <= obtainedAmount) { return(wanted); } return(wanted * (obtainedAmount / modifiedAmount)); }
public static byte[] DownloadAsset(string resourceSha, string path) { try { using (WebClient client = ServerHttpClient.CreateWebClient()) { return(client.DownloadData(string.Format("{0}/{1}/{2}", ResourceSettings.GetContentUrl(), resourceSha, path))); } } catch (Exception) { Logging.Warning(string.Format("ServerHttpClient: file {0} doesn't exist", path)); } return(null); }
private static DecayConfiguration ParseConfig(ConfigNode node) { DecayConfiguration ret = new DecayConfiguration(); string tmpStr = ""; if (node.TryGetValue("decayProduct", ref tmpStr) == false) { Debug.Log($"[VesselDecay.ParseConfig] - resource configuration {node.name} is invalid. Error getting decayProduct"); return(ret); } ret.decayProduct = ResourceSettings.NameToResource(tmpStr); if (ret.decayProduct == ResourceName.Unknown) { Debug.Log($"[VesselDecay.ParseConfig] - resource configuration {node.name} is invalid. Unable to convert decayProduct to a resource identifer"); return(ret); } if (!PartResourceLibrary.Instance.resourceDefinitions.Contains(tmpStr)) { Debug.Log($"[VesselDecay.ParseConfig] - resource configuration {node.name} is invalid. {tmpStr} is an undefined resource"); return(ret); } ret.densityRatio = PartResourceLibrary.Instance.GetDefinition(node.name).density / PartResourceLibrary.Instance.GetDefinition(tmpStr).density; if (node.TryGetValue("decayConstant", ref ret.decayConstant) == false) { Debug.Log($"[VesselDecay.ParseConfig] - resource configuration {node.name} is invalid. Error getting decayConstant"); return(ret); } if (!PartResourceLibrary.Instance.resourceDefinitions.Contains(node.name)) { Debug.Log($"[VesselDecay.ParseConfig] missing resource definition for {node.name}"); return(ret); } ret.resourceID = ResourceSettings.NameToResource(node.name); if (ret.resourceID == ResourceName.Unknown) { Debug.Log($"[VesselDecay.ParseConfig] missing resource definition for either {ret.decayProduct} or {node.name}"); return(ret); } ret.valid = true; return(ret); }
private CoreStateModel GetCoreState() { lock (m_Lock) { IEnumerable <IDependentActivity <int, int> > activities = Activities.Select(x => (IDependentActivity <int, int>)x.CloneObject()); return(new CoreStateModel { ArrowGraphSettings = ArrowGraphSettings.CloneObject(), ResourceSettings = ResourceSettings.CloneObject(), DependentActivities = m_Mapper.Map <IEnumerable <IDependentActivity <int, int> >, IEnumerable <DependentActivityModel> >(activities), ProjectStart = ProjectStart, UseBusinessDays = UseBusinessDays, ShowDates = ShowDates, }); } }
public MainWindow() { BuildingsSettings.Load("../../Game/Settings/BuildingsSettings.xml"); ResourceSettings.Load("../../Game/Settings/ResourceSettings.xml"); MaterialSettings.Load("../../Game/Settings/MaterialSettings.xml"); InitializeComponent(); initComboBuild(); initMaterialList(); this.KeyDown += Arrows; this.MouseWheel += Zoom; if (System.IO.File.Exists("../../Mapa.xml")) { loadMap("../../Mapa.xml"); } // Canv.Key // Canv.key }
public override async Task <HttpResponseMessage> SendAsync(string url, ResourceSettings resource, Dictionary <string, string> tokens) { var headers = base.ReplaceTokens(resource.Headers, tokens); var parameters = base.ReplaceTokens(resource.Parameters, tokens); url = base.ReplaceUrlParameters(url, parameters); var request = new HttpRequestMessage { RequestUri = new Uri(url), Method = new HttpMethod(resource.Method) }; foreach (var header in headers) { request.Headers.Add(header.Key, header.Value); } return(await Client.SendAsync(request)); }
public HttpResponseMessage Settings() { try { var settings = new ResourceSettings { Categories = this.GetCategories(), Regions = null }; return(this.Request.CreateResponse(HttpStatusCode.OK, settings)); } catch (ApiNotFoundException e) { return(this.Request.CreateResponse(HttpStatusCode.BadRequest, e.Message)); } catch (Exception e) { return(this.Request.CreateResponse(HttpStatusCode.InternalServerError, e.Message)); } }
/// <summary> /// Called by the IKITMod to produce resources on a vessel.It automatically converts the amount by the appropriate value to /// give a per-second resource production. /// </summary> /// <param name="resource">Resource to produce</param> /// <param name="amount">Amount you are providing</param> void IResourceManager.ProduceResource(ResourceName resource, double amount) { ResourceSettings.ValidateResource(resource); //Debug.Log($"ProduceResource {resource} - {amount}"); if (!inExecuteKITModules) { Debug.Log("[KITResourceManager.ProduceResource] don't do this."); return; } if (resource == ResourceName.WasteHeat && myCheatOptions.IgnoreMaxTemperature) { return; } if (currentResources.ContainsKey(resource) == false) { currentResources[resource] = 0; } currentResources[resource] += amount * fixedDeltaTime; }
public TrolleyCalculatorService(IApiClient apiClient, IOptions <ResourceSettings> resourceSettings) { _apiClient = apiClient; _resourceSettings = resourceSettings.Value; }
public override async Task <HttpResponseMessage> SendAsync(ApplicationSettings application, ResourceSettings resource) { var url = $"{application.BaseUrl}{resource.Url}"; var tokens = application.ConvertToTokenDictionary(); return(await this.SendAsync(url, resource, tokens)); }
public ProductService(IApiClient apiClient, IShoppingHistoryService shoppingHistoryService, IOptions <ResourceSettings> resourceSettings) { _apiClient = apiClient; _shoppingHistoryService = shoppingHistoryService; _resourceSettings = resourceSettings.Value; }
/// <summary> /// Get the resource settings (custom actions for CKAN resource types) /// </summary> /// <returns></returns> public static ResourceSettings GetResourceSettings() { ResourceSettings settings = new ResourceSettings(); foreach (var key in ConfigurationManager.AppSettings.AllKeys) { if (key.Contains("ResourceType")) { // Get or create the resource type string type = key.Split(char.Parse("."))[1].ToLower(); string property = key.Split(char.Parse("."))[2]; ResourceType resourceType; if (settings.Types.ContainsKey(type)) { resourceType = settings.Types[type]; } else { resourceType = new ResourceType(); settings.Types.Add(type, resourceType); } // Check for the title if (property == "Title") { resourceType.Title = ConfigurationManager.AppSettings[key]; } else if (property == "Actions") { // Add the actions string value = ConfigurationManager.AppSettings[key]; value = value.Replace(Environment.NewLine, ""); foreach (var actionSetting in value.Split(char.Parse("|"))) { ResourceAction action = new ResourceAction(); foreach (var parameterSetting in actionSetting.Split(char.Parse(";"))) { string parameter = parameterSetting.Trim(); int equalsIndex = parameter.IndexOf("="); var parameterKey = parameter.Substring(0, equalsIndex); var parameterValue = parameter.Substring(equalsIndex + 1); if (parameterKey == "action") { action.Action = parameterValue; } else if (parameterKey == "url") { action.UrlTemplate = parameterValue; } else if (parameterKey == "title") { action.Title = parameterValue; } } resourceType.Actions.Add(action); } } } } return(settings); }
/// <summary> /// 資源設定を構文解析する /// </summary> /// <param name="lexer">字句解析器</param> /// <returns>資源設定</returns> private static ResourceSettings ParseFree(TextLexer lexer) { // = Token token = lexer.GetToken(); if (token.Type != TokenType.Equal) { Log.InvalidToken(LogCategory, token, lexer); return null; } // { token = lexer.GetToken(); if (token.Type != TokenType.OpenBrace) { Log.InvalidToken(LogCategory, token, lexer); return null; } ResourceSettings free = new ResourceSettings(); while (true) { token = lexer.GetToken(); // ファイルの終端 if (token == null) { break; } // } (セクション終端) if (token.Type == TokenType.CloseBrace) { break; } // 無効なトークン if (token.Type != TokenType.Identifier) { Log.InvalidToken(LogCategory, token, lexer); lexer.SkipLine(); continue; } string keyword = token.Value as string; if (string.IsNullOrEmpty(keyword)) { continue; } keyword = keyword.ToLower(); // ic if (keyword.Equals("ic")) { double? d = ParseDouble(lexer); if (!d.HasValue) { Log.InvalidClause(LogCategory, "ic", lexer); continue; } // 工業力 free.Ic = (double) d; continue; } // manpower if (keyword.Equals("manpower")) { double? d = ParseDouble(lexer); if (!d.HasValue) { Log.InvalidClause(LogCategory, "manpower", lexer); continue; } // 人的資源 free.Manpower = (double) d; continue; } // energy if (keyword.Equals("energy")) { double? d = ParseDouble(lexer); if (!d.HasValue) { Log.InvalidClause(LogCategory, "energy", lexer); continue; } // エネルギー free.Energy = (double) d; continue; } // metal if (keyword.Equals("metal")) { double? d = ParseDouble(lexer); if (!d.HasValue) { Log.InvalidClause(LogCategory, "metal", lexer); continue; } // 金属 free.Metal = (double) d; continue; } // rare_materials if (keyword.Equals("rare_materials")) { double? d = ParseDouble(lexer); if (!d.HasValue) { Log.InvalidClause(LogCategory, "rare_materials", lexer); continue; } // 希少資源 free.RareMaterials = (double) d; continue; } // oil if (keyword.Equals("oil")) { double? d = ParseDouble(lexer); if (!d.HasValue) { Log.InvalidClause(LogCategory, "oil", lexer); continue; } // 石油 free.Oil = (double) d; continue; } // supplies if (keyword.Equals("supplies")) { double? d = ParseDouble(lexer); if (!d.HasValue) { Log.InvalidClause(LogCategory, "supplies", lexer); continue; } // 物資 free.Supplies = (double) d; continue; } // money if (keyword.Equals("money")) { double? d = ParseDouble(lexer); if (!d.HasValue) { Log.InvalidClause(LogCategory, "money", lexer); continue; } // 資金 free.Money = (double) d; continue; } // transport if (keyword.Equals("transport")) { int? n = ParseInt(lexer); if (!n.HasValue) { Log.InvalidClause(LogCategory, "transport", lexer); continue; } // 輸送船団 free.Transports = (int) n; continue; } // escort if (keyword.Equals("escort")) { int? n = ParseInt(lexer); if (!n.HasValue) { Log.InvalidClause(LogCategory, "escort", lexer); continue; } // 護衛艦 free.Escorts = (int) n; continue; } // 無効なトークン Log.InvalidToken(LogCategory, token, lexer); lexer.SkipLine(); } return free; }
public static void Init(int type, string[] args) { AppDomain.CurrentDomain.UnhandledException += ServerCore.OnUnhandledExceptionThrown; ServerCore.Type = type; ServerCore.Id = 0; ServerCore.ConfigurationServer = "http://127.0.0.1/supercell/"; if (args.Length > 0) { if (args.Length % 2 == 0) { for (int i = 0; i < args.Length; i += 2) { string name = args[i]; string value = args[i + 1]; switch (name) { case "-conf": if (value.Length > 0) { if (value.StartsWith("http://") || value.StartsWith("https://")) { if (!value.EndsWith("/")) { value += "/"; } ServerCore.ConfigurationServer = value; } else { Logging.Warning("ServerCore.init: invalid server url: " + value); } } else { Logging.Warning("ServerCore.init server url is empty"); } break; case "-id": ServerCore.Id = int.Parse(value); break; } } } else { Logging.Warning("ServerCore.init invalid args length"); } } ServerCore.Random = new LogicRandom((int)DateTime.UtcNow.Ticks); Directory.SetCurrentDirectory(AppContext.BaseDirectory); Logging.Init(); EnvironmentSettings.Init(); ResourceSettings.Init(); GamePlaySettings.Init(); ResourceManager.Init(); ServerRequestManager.Init(); ServerManager.Init(); ServerCore.Socket = ServerManager.GetSocket(ServerCore.Type, ServerCore.Id); }
public abstract Task <HttpResponseMessage> SendAsync(string url, ResourceSettings resource, Dictionary <string, string> tokens);
public abstract Task <HttpResponseMessage> SendAsync(ApplicationSettings application, ResourceSettings resource);
public S3ImageService(IOptions <ResourceSettings> resourceSettings, ILogger <S3ImageService> logger) { _resourceSettings = resourceSettings.Value; _logger = logger; }
public ShoppingHistoryService(IApiClient apiClient, IOptions <ResourceSettings> resourceSettings) { _apiClient = apiClient; _resourceSettings = resourceSettings.Value; }
private void BindResourceSetting(DataBindingSource bindingSource, string frequencyName, string abundanceName, ResourceSettings setting) { bindingSource.AddBinding(frequencyName, () => setting.Frequency, val => setting.Frequency = Convert.ToSingle(val)); bindingSource.AddBinding(abundanceName, () => setting.Abundance, val => setting.Abundance = Convert.ToSingle(val)); }
public override async Task <HttpResponseMessage> SendAsync(ApplicationSettings application, ResourceSettings resource) { var url = $"{application.BaseUrl}{resource.Url}"; var plugins = new List <IPlugin>(); plugins.Add(application); if (resource.Paging != null) { plugins.Add(resource.Paging); } var tokens = plugins.ConvertToTokenDictionary(); return(await this.SendAsync(url, resource, tokens)); }