private void fillTemplateIdentifierMapping(BuildingPresets buildingPresets) { _templateIdentifierMapping.Clear(); foreach (var curBuilding in buildingPresets.Buildings) { if (string.IsNullOrWhiteSpace(curBuilding.Identifier)) { continue; } var templateName = curBuilding.Template; if (string.IsNullOrWhiteSpace(templateName)) { templateName = NO_TEMPLATE_NAME; } if (!_templateIdentifierMapping.ContainsKey(templateName)) { _templateIdentifierMapping.Add(templateName, new List <string> { curBuilding.Identifier }); } else { _templateIdentifierMapping[templateName].Add(curBuilding.Identifier); } } }
public void SaveSettings_IsCalled_ShouldSaveIsPavedStreet(bool expectedIsPavedStreet) { // Arrange var appSettings = new Mock <IAppSettings>(); appSettings.SetupAllProperties(); var presets = new BuildingPresets { Buildings = new List <BuildingInfo>() }; var canvas = new Mock <IAnnoCanvas>(); canvas.SetupGet(x => x.BuildingPresets).Returns(() => presets); var viewModel = GetViewModel(null, appSettings.Object, annoCanvasToUse: canvas.Object); viewModel.BuildingSettingsViewModel.IsPavedStreet = expectedIsPavedStreet; // Act viewModel.SaveSettings(); // Assert Assert.Equal(expectedIsPavedStreet, appSettings.Object.IsPavedStreet); appSettings.Verify(x => x.Save(), Times.AtLeastOnce); }
private void LoadPresetData(object param) { //IsBusy = true; StatusMessage = string.Empty; BuildingPresets buildingPresets = null; try { buildingPresets = SerializationHelper.LoadFromFile <BuildingPresets>(PresetsVM.SelectedFile); } catch (Exception ex) { var message = $"Error parsing {nameof(BuildingPresets)}."; Trace.WriteLine($"{message}{Environment.NewLine}{ex}"); MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); StatusMessage = $"{message} -> Maybe wrong selected file?"; return; } PresetsVersion = buildingPresets.Version; fillAvailableTemplates(buildingPresets); fillAvailableIdentifiers(buildingPresets); fillTemplateIdentifierMapping(buildingPresets); AvailableColorSchemes.Clear(); ColorPresets colorPresets = null; try { ColorPresetsLoader loader = new ColorPresetsLoader(); colorPresets = loader.Load(ColorsVM.SelectedFile); } catch (Exception ex) { var message = $"Error parsing {nameof(ColorPresets)}."; Trace.WriteLine($"{message}{Environment.NewLine}{ex}"); MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); StatusMessage = $"{message} -> Maybe wrong selected file?"; return; } foreach (var curScheme in colorPresets.AvailableSchemes) { AvailableColorSchemes.Add(new ColorSchemeViewModel(curScheme)); } //var defaultScheme = loader.LoadDefaultScheme(vmColors.SelectedFile); ColorPresetsVersion = colorPresets.Version; ColorPresetsVersionUpdated = ColorPresetsVersion; SelectedColorScheme = AvailableColorSchemes.First(); //IsBusy = false; }
private void WindowLoaded(object sender, RoutedEventArgs e) { // add icons to the combobox comboBoxIcon.Items.Clear(); _noIconItem = new IconImage("None"); comboBoxIcon.Items.Add(_noIconItem); foreach (System.Collections.Generic.KeyValuePair <string, IconImage> icon in annoCanvas.Icons) { comboBoxIcon.Items.Add(icon.Value); } comboBoxIcon.SelectedIndex = 0; // check for updates on startup MenuItemVersion.Header = "Version: " + Constants.Version; MenuItemFileVersion.Header = "File version: " + Constants.FileVersion; CheckForUpdates(false); // load color presets colorPicker.StandardColors.Clear(); //This is currently disabled //try //{ // ColorPresets colorPresets = DataIO.LoadFromFile<ColorPresets>(Path.Combine(App.ApplicationPath, Constants.ColorPresetsFile)); // foreach (ColorScheme colorScheme in colorPresets.ColorSchemes) // { // foreach (ColorInfo colorInfo in colorScheme.ColorInfos) // { // colorPicker.StandardColors.Add(new ColorItem(colorInfo.Color, string.Format("{0} ({1})", colorInfo.ColorTarget, colorScheme.Name))); // } // } //} //catch (Exception ex) //{ // MessageBox.Show(ex.Message, "Loading of the color presets failed"); //} // load presets treeViewPresets.Items.Clear(); // manually add a road tile preset treeViewPresets.Items.Add(new AnnoObject { Label = "Road tile", Size = new Size(1, 1), Radius = 0, Road = true }); treeViewPresets.Items.Add(new AnnoObject { Label = "Borderless road tile", Size = new Size(1, 1), Radius = 0, Borderless = true, Road = true }); BuildingPresets presets = annoCanvas.BuildingPresets; if (presets != null) { presets.AddToTree(treeViewPresets); GroupBoxPresets.Header = string.Format("Building presets - loaded v{0}", presets.Version); MenuItemPresetsVersion.Header = "Presets version: " + presets.Version; } else { GroupBoxPresets.Header = "Building presets - load failed"; } // load file given by argument if (!string.IsNullOrEmpty(App.FilenameArgument)) { annoCanvas.OpenFile(App.FilenameArgument); } }
public async Task UpdateStatisticsAsync(UpdateMode mode, List <LayoutObject> placedObjects, List <LayoutObject> selectedObjects, BuildingPresets buildingPresets) { if (!placedObjects.Any()) { AreStatisticsAvailable = false; return; } AreStatisticsAvailable = true; var calculateStatisticsTask = Task.Run(() => _statisticsCalculationHelper.CalculateStatistics(placedObjects.Select(_ => _.WrappedAnnoObject))); if (mode != UpdateMode.NoBuildingList && ShowBuildingList) { var groupedBuildings = placedObjects.GroupBy(_ => _.Identifier); var groupedSelectedBuildings = selectedObjects.Count > 0 ? selectedObjects.GroupBy(_ => _.Identifier) : null; var buildingsTask = Task.Run(() => GetStatisticBuildings(groupedBuildings, buildingPresets)); var selectedBuildingsTask = Task.Run(() => GetStatisticBuildings(groupedSelectedBuildings, buildingPresets)); SelectedBuildings = await selectedBuildingsTask; Buildings = await buildingsTask; } var calculatedStatistics = await calculateStatisticsTask; UsedArea = string.Format("{0}x{1}", calculatedStatistics.UsedAreaX, calculatedStatistics.UsedAreaY); UsedTiles = calculatedStatistics.UsedTiles; MinTiles = calculatedStatistics.MinTiles; Efficiency = string.Format("{0}%", calculatedStatistics.Efficiency); }
public void LoadItems_BuildingsHaveSpecialFaction_ShouldNotLoadBuildings(string factionToSet) { // Arrange var viewModel = new PresetsTreeViewModel(_mockedTreeLocalization); var buildings = new List <BuildingInfo> { new BuildingInfo { Header = "(A4) Anno 1404", Faction = factionToSet } }; var buildingPresets = new BuildingPresets(); buildingPresets.Buildings = buildings; // Act viewModel.LoadItems(buildingPresets); // Assert //there are always 2 road items Assert.Equal(2, viewModel.Items.Count); }
public void UpdateStatistics(List <AnnoObject> placedObjects, List <AnnoObject> selectedObjects, BuildingPresets buildingPresets) { if (!placedObjects.Any()) { AreStatisticsAvailable = false; return; } AreStatisticsAvailable = true; var calculatedStatistics = _statisticsCalculationHelper.CalculateStatistics(placedObjects); UsedArea = string.Format("{0}x{1}", calculatedStatistics.UsedAreaX, calculatedStatistics.UsedAreaY); UsedTiles = calculatedStatistics.UsedTiles; MinTiles = calculatedStatistics.MinTiles; Efficiency = string.Format("{0}%", calculatedStatistics.Efficiency); if (ShowBuildingList) { var groupedBuildings = placedObjects.GroupBy(_ => _.Identifier); var groupedSelectedBuildings = selectedObjects.Count > 0 ? selectedObjects.GroupBy(_ => _.Identifier) : null; Buildings = GetStatisticBuildings(groupedBuildings, buildingPresets); SelectedBuildings = GetStatisticBuildings(groupedSelectedBuildings, buildingPresets); } else { } }
public void SetCondensedTreeState_SavedTreeStateIsCompatible_ShouldSetTreeState() { // Arrange var buildingPresetsVersion = "1.0"; var buildingPresets = new BuildingPresets(); buildingPresets.Buildings = new List <BuildingInfo>(); buildingPresets.Version = buildingPresetsVersion; var viewModel = new PresetsTreeViewModel(_mockedTreeLocalization); viewModel.LoadItems(buildingPresets); var(items, expectedState) = GetTreeAndState(expandLastMainNode: false); viewModel.Items.Clear(); foreach (var curItem in items) { viewModel.Items.Add(curItem); } var savedTreeState = new Dictionary <int, bool> { { 4, true }, { 5, false } }; // Act viewModel.SetCondensedTreeState(savedTreeState, buildingPresetsVersion); // Assert var currentState = viewModel.GetCondensedTreeState(); Assert.Equal(savedTreeState, currentState); }
/// <summary> /// Load a subset of current presets. Is only called once. /// </summary> /// <returns>A subset of the current presets.</returns> private static BuildingPresets InitSubsetFromPresetsFile() { var loader = new BuildingPresetsLoader(); string basePath = AppDomain.CurrentDomain.BaseDirectory; var buildingPresets = loader.Load(Path.Combine(basePath, CoreConstants.PresetsFiles.BuildingPresetsFile)); var buildings_1404 = buildingPresets.Buildings.Where(x => x.Header.StartsWith("(A4")).OrderByDescending(x => x.GetOrderParameter()).Take(10).ToList(); var buildings_2070 = buildingPresets.Buildings.Where(x => x.Header.StartsWith("(A5")).OrderByDescending(x => x.GetOrderParameter()).Take(10).ToList(); var buildings_2205 = buildingPresets.Buildings.Where(x => x.Header.StartsWith("(A6")).OrderByDescending(x => x.GetOrderParameter()).Take(10).ToList(); var buildings_1800 = buildingPresets.Buildings.Where(x => x.Header.StartsWith("(A7")).OrderByDescending(x => x.GetOrderParameter()).Take(10).ToList(); var filteredBuildings = new List <BuildingInfo>(); filteredBuildings.AddRange(buildings_1404); filteredBuildings.AddRange(buildings_2070); filteredBuildings.AddRange(buildings_2205); filteredBuildings.AddRange(buildings_1800); var presets = new BuildingPresets { Version = buildingPresets.Version, Buildings = filteredBuildings }; return(presets); }
public void LoadItems_BuildingsHaveFaction_ShouldLoadBuildings() { // Arrange var viewModel = new PresetsTreeViewModel(_mockedTreeLocalization); var buildings = new List <BuildingInfo> { new BuildingInfo { Header = "(A4) Anno 1404", Faction = "Workers", Identifier = "A4_house"//required for GetOrderParameter } }; var buildingPresets = new BuildingPresets(); buildingPresets.Buildings = buildings; // Act viewModel.LoadItems(buildingPresets); // Assert //first 2 items always the road items Assert.Single((viewModel.Items[2] as GameHeaderTreeItem).Children); Assert.Equal(buildings[0].Faction, (viewModel.Items[2] as GameHeaderTreeItem).Children[0].Header); }
private void fillAvailableIdentifiers(BuildingPresets buildingPresets) { AvailableIdentifiers.Clear(); var allIdentifiers = new Dictionary <string, int>(); foreach (var curBuilding in buildingPresets.Buildings) { if (string.IsNullOrWhiteSpace(curBuilding.Identifier)) { continue; } if (!allIdentifiers.ContainsKey(curBuilding.Identifier)) { allIdentifiers.Add(curBuilding.Identifier, 1); } else { allIdentifiers[curBuilding.Identifier] = ++allIdentifiers[curBuilding.Identifier]; } } var identifierListOrderedByOccurrence = allIdentifiers.OrderByDescending(x => x.Value).ToList(); var identifierNameList = allIdentifiers.OrderBy(x => x.Key).Select(x => x.Key).ToList(); foreach (var curIdentifierName in identifierNameList) { AvailableIdentifiers.Add(curIdentifierName); } }
static PresetsTreeViewModelTests() { _subsetFromPresetsFile = InitSubsetFromPresetsFile(); _subsetForFiltering = InitSubsetForFiltering(); var mockedLocalizationHelper = new Mock <ILocalizationHelper>(); mockedLocalizationHelper.Setup(x => x.GetLocalization(It.IsAny <string>())).Returns <string>(x => x); mockedLocalizationHelper.Setup(x => x.GetLocalization(It.IsAny <string>(), It.IsAny <string>())).Returns((string value, string langauge) => value); _mockedTreeLocalization = mockedLocalizationHelper.Object; }
public void LoadItems_VersionOfBuildingPresetsIsSet_ShouldRaisePropertyChangedEvent() { // Arrange var viewModel = new PresetsTreeViewModel(_mockedTreeLocalization); var buildingPresets = new BuildingPresets(); buildingPresets.Buildings = new List <BuildingInfo>(); // Act/Assert Assert.PropertyChanged(viewModel, nameof(viewModel.BuildingPresetsVersion), () => viewModel.LoadItems(buildingPresets)); }
public BuildingPresets Load(string pathToBuildingPresetsFile) { BuildingPresets result = null; try { result = SerializationHelper.LoadFromFile <BuildingPresets>(pathToBuildingPresetsFile); } catch (Exception ex) { Trace.WriteLine($"Error loading the buildings.{Environment.NewLine}{ex}"); throw; } return(result); }
public void LoadItems_BuildingPresetsPassed_ShouldSetVersionOfBuildingPresets(string versionToSet) { // Arrange var viewModel = new PresetsTreeViewModel(_mockedTreeLocalization); var buildingPresets = new BuildingPresets(); buildingPresets.Buildings = new List <BuildingInfo>(); buildingPresets.Version = versionToSet; // Act viewModel.LoadItems(buildingPresets); // Assert Assert.Equal(versionToSet, viewModel.BuildingPresetsVersion); }
public BuildingPresets Load(string pathToBuildingPresetsFile) { BuildingPresets result = null; try { result = SerializationHelper.LoadFromFile <BuildingPresets>(pathToBuildingPresetsFile); } catch (Exception ex) { logger.Error(ex, "Error loading the buildings."); throw; } return(result); }
public string StartExport(string layoutName, LayoutFile layout, BuildingPresets buildingPresets, WikiBuildingInfoPresets wikiBuildingInfoPresets, bool exportUnsupportedTags) { //https://anno1800.fandom.com/wiki/Template:Production_layout //https://anno1800.fandom.com/wiki/Template:Production_layout/doc //https://anno1800.fandom.com/wiki/Category:Template_documentation //https://anno1800.fandom.com/wiki/Testing_page //TODO warn user when layout contains more than 15 building types because template only supports 1-15 //template only supports 1-8 for "Production x Type" and "Production x per minute" //TODO warn user (or exit) when layout contains buildings other than Anno 1800 var calculatedStatistics = _statisticsCalculationHelper.CalculateStatistics(layout.Objects); var exportString = new StringBuilder(900);//best guess on minimal layout exportString.Append(TEMPLATE_START) .AppendLine(HEADER_PRODUCTION_LAYOUT) .Append(TEMPLATE_LINE_START).Append(HEADER_ICON).AppendLine(TEMPLATE_ENTRY_DELIMITER) .Append(TEMPLATE_LINE_START).Append(HEADER_LAYOUT_NAME).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(layoutName) .Append(TEMPLATE_LINE_START).Append(HEADER_LAYOUT_IMAGE).AppendLine(TEMPLATE_ENTRY_DELIMITER); //add buildings exportString = addBuildingInfo(exportString, layout.Objects, buildingPresets, wikiBuildingInfoPresets); exportString.Append(TEMPLATE_LINE_START).Append(HEADER_LAYOUT_DESCRIPTION).AppendLine(TEMPLATE_ENTRY_DELIMITER) .Append(TEMPLATE_LINE_START).Append(HEADER_SIZE).Append(TEMPLATE_ENTRY_DELIMITER).Append(calculatedStatistics.UsedAreaWidth.ToString()).Append(TEMPLATE_SIZE_ENTRY_DELIMITER).AppendLine(calculatedStatistics.UsedAreaHeight.ToString()) .Append(TEMPLATE_LINE_START).Append(HEADER_TILES).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(calculatedStatistics.UsedTiles.ToString()) .Append(TEMPLATE_LINE_START).Append(HEADER_AUTHOR).AppendLine(TEMPLATE_ENTRY_DELIMITER) .Append(TEMPLATE_LINE_START).Append(HEADER_SOURCE).AppendLine(TEMPLATE_ENTRY_DELIMITER); exportString = addProductionInfo(exportString, layout.Objects, buildingPresets, wikiBuildingInfoPresets); exportString = addConstructionInfo(exportString, layout.Objects, buildingPresets, wikiBuildingInfoPresets); exportString = addBalance(exportString, layout.Objects, buildingPresets, wikiBuildingInfoPresets); exportString = addWorkforceInfo(exportString, layout.Objects, buildingPresets, wikiBuildingInfoPresets); exportString = addInfluence(exportString, layout.Objects, buildingPresets, wikiBuildingInfoPresets); exportString = addAttractiveness(exportString, layout.Objects, buildingPresets, wikiBuildingInfoPresets); if (exportUnsupportedTags) { exportString = addUnsupportedEntries(exportString); } exportString.Append(TEMPLATE_END); return(exportString.ToString()); }
public void LoadItems_BuildingPresetsContainsNoBuildings_ShouldLoadTwoRoadItems() { // Arrange var viewModel = new PresetsTreeViewModel(_mockedTreeLocalization); var buildingPresets = new BuildingPresets(); buildingPresets.Buildings = new List <BuildingInfo>(); // Act viewModel.LoadItems(buildingPresets); // Assert Assert.Equal(2, viewModel.Items.Count); Assert.True(viewModel.Items[0].AnnoObject.Road); Assert.True(viewModel.Items[1].AnnoObject.Road); }
public BuildingPresets Load(string pathToBuildingPresetsFile) { BuildingPresets result = null; try { result = SerializationHelper.LoadFromFile <BuildingPresets>(pathToBuildingPresetsFile); if (result != null) { logger.Debug($"Loaded building presets version: {result.Version}"); } } catch (Exception ex) { logger.Error(ex, "Error loading the buildings."); throw; } return(result); }
public static void Main(string[] args) { // prepare localizations var localizations = GetLocalizations(); // prepare icon mapping var iconsDocument = new XmlDocument(); iconsDocument.Load("data/config/icons.xml"); var iconNodes = iconsDocument.SelectNodes("/Icons/i").Cast <XmlNode>(); // write icon name mapping Console.WriteLine("Writing icon name mapping to icons.json"); WriteIconNameMapping(iconNodes, localizations); // parse buildings var buildings = new List <BuildingInfo>(); // find buildings in assets.xml Console.WriteLine(); Console.WriteLine("Parsing assets.xml:"); ParseAssetsFile("data/config/assets.xml", "/AssetList/Groups/Group/Groups/Group", buildings, iconNodes, localizations); // find buildings in addon_01_assets.xml Console.WriteLine(); Console.WriteLine("Parsing addon_01_assets.xml:"); ParseAssetsFile("data/config/addon_01_assets.xml", "/Group/Groups/Group", buildings, iconNodes, localizations); // serialize presets to json file var presets = new BuildingPresets { Version = "0.5", Buildings = buildings }; Console.WriteLine("Writing buildings to presets.json"); DataIO.SaveToFile(presets, "presets.json"); // wait for keypress before exiting Console.WriteLine(); Console.WriteLine("DONE - press enter to exit"); Console.ReadLine(); }
private string getBuildingName(string buildingIdentifier, BuildingPresets buildingPresets, WikiBuildingInfoPresets wikiBuildingInfoPresets) { var result = MAPPING_NOT_FOUND + buildingIdentifier; var foundFandomNameMapping = FandomeNamePresets.Names.FirstOrDefault(x => x.Identifiers.Contains(buildingIdentifier)); if (foundFandomNameMapping != null) { result = foundFandomNameMapping.FandomName; } else { //try to get by wiki info var foundWikiBuildingInfo = getWikiBuildingInfo(buildingIdentifier, buildingPresets, wikiBuildingInfoPresets); if (!string.IsNullOrWhiteSpace(foundWikiBuildingInfo?.Icon)) { result = Path.GetFileNameWithoutExtension(foundWikiBuildingInfo.Icon); } } return(result); }
public void LoadItems_ViewModelHasItems_ShouldClearItemsBeforeLoad() { // Arrange var viewModel = new PresetsTreeViewModel(_mockedTreeLocalization); var itemsToAdd = Enumerable.Repeat(new GenericTreeItem(null), 10); foreach (var curItem in itemsToAdd) { viewModel.Items.Add(curItem); } var buildingPresets = new BuildingPresets(); buildingPresets.Buildings = new List <BuildingInfo>(); // Act viewModel.LoadItems(buildingPresets); // Assert Assert.Equal(2, viewModel.Items.Count); }
public async Task UpdateStatisticsAsync(UpdateMode mode, IList <LayoutObject> placedObjects, ICollection <LayoutObject> selectedObjects, BuildingPresets buildingPresets) { if (placedObjects.Count == 0) { AreStatisticsAvailable = false; return; } AreStatisticsAvailable = true; var calculateStatisticsTask = Task.Run(() => _statisticsCalculationHelper.CalculateStatistics(placedObjects.Select(_ => _.WrappedAnnoObject))); if (mode != UpdateMode.NoBuildingList && ShowBuildingList) { var groupedPlacedBuildings = placedObjects.GroupBy(_ => _.Identifier).ToList(); IEnumerable <IGrouping <string, LayoutObject> > groupedSelectedBuildings = null; if (selectedObjects != null && selectedObjects.Count > 0) { groupedSelectedBuildings = selectedObjects.Where(_ => _ != null).GroupBy(_ => _.Identifier).ToList(); } var buildingsTask = Task.Run(() => GetStatisticBuildings(groupedPlacedBuildings, buildingPresets)); var selectedBuildingsTask = Task.Run(() => GetStatisticBuildings(groupedSelectedBuildings, buildingPresets)); SelectedBuildings = await selectedBuildingsTask; Buildings = await buildingsTask; } var calculatedStatistics = await calculateStatisticsTask; UsedArea = string.Format("{0}x{1}", calculatedStatistics.UsedAreaWidth, calculatedStatistics.UsedAreaHeight); UsedTiles = calculatedStatistics.UsedTiles; MinTiles = calculatedStatistics.MinTiles; Efficiency = string.Format("{0}%", calculatedStatistics.Efficiency); }
public void SetCondensedTreeState_LastPresetsVersionIsDifferent_ShouldNotSetAnyStateAndNotThrow() { // Arrange var buildingPresetsVersion = "1.0"; var buildingPresets = new BuildingPresets(); buildingPresets.Buildings = new List <BuildingInfo>(); buildingPresets.Version = buildingPresetsVersion; var viewModel = new PresetsTreeViewModel(_mockedTreeLocalization, _mockedCommons); viewModel.LoadItems(buildingPresets); var(items, expectedState) = GetTreeAndState(); viewModel.Items = new ObservableCollection <GenericTreeItem>(items); // Act viewModel.SetCondensedTreeState(new Dictionary <int, bool>(), "2.0"); // Assert Assert.Equal(expectedState, viewModel.GetCondensedTreeState()); }
public void SetCondensedTreeState_SavedTreeStateIsNull_ShouldNotSetAnyStateAndNotThrow() { // Arrange var buildingPresetsVersion = "1.0"; var buildingPresets = new BuildingPresets(); buildingPresets.Buildings = new List <BuildingInfo>(); buildingPresets.Version = buildingPresetsVersion; var viewModel = new PresetsTreeViewModel(_mockedTreeLocalization); viewModel.LoadItems(buildingPresets); var(items, expectedState) = GetTreeAndState(); viewModel.Items = new ObservableCollection <GenericTreeItem>(items); // Act viewModel.SetCondensedTreeState(null, buildingPresetsVersion); // Assert Assert.Equal(expectedState, viewModel.GetCondensedTreeState()); }
private WikiBuildingInfo getWikiBuildingInfo(string buildingIdentifier, BuildingPresets buildingPresets, WikiBuildingInfoPresets wikiBuildingInfoPresets) { WikiBuildingInfo result = null; var foundPresetBuilding = buildingPresets.Buildings.FirstOrDefault(x => x.Identifier.Equals(buildingIdentifier, StringComparison.OrdinalIgnoreCase)); var buildingName = foundPresetBuilding?.Localization["eng"]; var buildingFaction = foundPresetBuilding?.Faction; var buildingRegion = WorldRegion.OldWorld; if (buildingFaction?.Contains("Obreros") == true || buildingFaction?.Contains("Jornaleros") == true) { buildingRegion = WorldRegion.NewWorld; } if (string.IsNullOrWhiteSpace(buildingName)) { //TODO error? logger.Warn($"found no building name for identifier: {buildingIdentifier}"); return(result); } //try to find by name result = wikiBuildingInfoPresets.Infos.FirstOrDefault(x => x.Name.Equals(buildingName, StringComparison.OrdinalIgnoreCase) && x.Region == buildingRegion); if (result == null) { //Is it a farm with field info? (e.g. "Potato Farm - (72)") var matchFieldCount = regexFieldCount.Match(buildingName); if (matchFieldCount.Success) { //strip field info and search again var strippedBuildingName = buildingName.Replace(matchFieldCount.Value, string.Empty).Trim(); result = wikiBuildingInfoPresets.Infos.FirstOrDefault(x => x.Name.Equals(strippedBuildingName, StringComparison.OrdinalIgnoreCase) && x.Region == buildingRegion); } } return(result); }
public void UpdateStatistics(List <AnnoObject> placedObjects, List <AnnoObject> selectedObjects, BuildingPresets buildingPresets) { if (!placedObjects.Any()) { AreStatisticsAvailable = false; return; } AreStatisticsAvailable = true; // calculate bouding box var boxX = placedObjects.Max(_ => _.Position.X + _.Size.Width) - placedObjects.Min(_ => _.Position.X); var boxY = placedObjects.Max(_ => _.Position.Y + _.Size.Height) - placedObjects.Min(_ => _.Position.Y); // calculate area of all buildings var minTiles = placedObjects.Where(_ => !_.Road).Sum(_ => _.Size.Width * _.Size.Height); UsedArea = string.Format("{0}x{1}", boxX, boxY); UsedTiles = boxX * boxY; MinTiles = minTiles; Efficiency = string.Format("{0}%", Math.Round(minTiles / boxX / boxY * 100)); if (ShowBuildingList) { var groupedBuildings = placedObjects.GroupBy(_ => _.Identifier); var groupedSelectedBuildings = selectedObjects.Count > 0 ? selectedObjects.GroupBy(_ => _.Identifier) : null; Buildings = GetStatisticBuildings(groupedBuildings, buildingPresets); SelectedBuildings = GetStatisticBuildings(groupedSelectedBuildings, buildingPresets); } else { } }
public void LoadItems_BuildingsHaveHeader_ShouldSetCorrectGameVersion(string headerToSet, CoreConstants.GameVersion expectedGameVersion) { // Arrange var viewModel = new PresetsTreeViewModel(_mockedTreeLocalization); var buildings = new List <BuildingInfo> { new BuildingInfo { Header = headerToSet } }; var buildingPresets = new BuildingPresets(); buildingPresets.Buildings = buildings; // Act viewModel.LoadItems(buildingPresets); // Assert //first 2 items always the road items Assert.Equal(expectedGameVersion, (viewModel.Items[2] as GameHeaderTreeItem).GameVersion); }
private async Task GenerateTemplate(object param) { try { IsBusy = true; StatusMessage = string.Empty; var buildingPresetsTask = Task.Run(() => { //load building presets BuildingPresets localBuildingPresets = null; try { var loader = new BuildingPresetsLoader(); localBuildingPresets = loader.Load(PresetsVM.SelectedFile); if (localBuildingPresets == null || localBuildingPresets.Buildings == null) { throw new ArgumentException(); } } catch (Exception ex) { var message = $"Error parsing {nameof(BuildingPresets)}."; logger.Error(ex, message); MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); StatusMessage = $"{message} -> Maybe wrong selected file?"; return(null); } PresetsVersion = localBuildingPresets.Version; return(localBuildingPresets); }); var wikiBuildingInfoPresetsTask = Task.Run(() => { //load wiki buildng info WikiBuildingInfoPresets localWikiBuildingInfoPresets = null; try { var loader = new WikiBuildingInfoPresetsLoader(); localWikiBuildingInfoPresets = loader.Load(WikiBuildingsInfoVM.SelectedFile); } catch (Exception ex) { var message = $"Error parsing {nameof(WikiBuildingInfoPresets)}."; logger.Error(ex, message); MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); StatusMessage = $"{message} -> Maybe wrong selected file?"; return(null); } WikiBuildingInfoPresetsVersion = localWikiBuildingInfoPresets.Version.ToString(); return(localWikiBuildingInfoPresets); }); var layoutTask = Task.Run(() => { //load layout List <AnnoObject> localLayout = null; try { ILayoutLoader loader = new LayoutLoader(); localLayout = loader.LoadLayout(LayoutVM.SelectedFile); } catch (Exception ex) { var message = "Error parsing layout file."; logger.Error(ex, message); MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); StatusMessage = $"{message} -> Maybe wrong selected file?"; return(null); } LayoutName = Path.GetFileName(LayoutVM.SelectedFile); return(localLayout); }); await Task.WhenAll(buildingPresetsTask, wikiBuildingInfoPresetsTask, layoutTask); var buildingPresets = buildingPresetsTask.Result; var wikiBuildingInfoPresets = wikiBuildingInfoPresetsTask.Result; var layout = layoutTask.Result; if (buildingPresets == null || wikiBuildingInfoPresets == null || layout == null) { return; } var layoutNameForTemplate = Path.GetFileNameWithoutExtension(LayoutVM.SelectedFile).Replace("_", " "); await Task.Run(() => { var exporter = new FandomExporter(); Template = exporter.StartExport(layoutNameForTemplate, layout, buildingPresets, wikiBuildingInfoPresets, true); }); StatusMessage = "Template successfully generated."; } catch (Exception ex) { var message = "Error generating template."; logger.Error(ex, message); MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); StatusMessage = $"{message} -> Details in log file."; } finally { IsBusy = false; } }
private static BuildingPresets InitSubsetForFiltering() { var locFireStation = new SerializableDictionary <string>(); locFireStation.Dict.Add("eng", "Fire Station"); var locPoliceStation = new SerializableDictionary <string>(); locPoliceStation.Dict.Add("eng", "Police Station"); var locBakery = new SerializableDictionary <string>(); locBakery.Dict.Add("eng", "Bakery"); var locRiceFarm = new SerializableDictionary <string>(); locRiceFarm.Dict.Add("eng", "Rice Farm"); var locRiceField = new SerializableDictionary <string>(); locRiceField.Dict.Add("eng", "Rice Field"); var buildings = new List <BuildingInfo> { //Fire Station new BuildingInfo { Header = "(A4) Anno 1404", Faction = "Public", Group = "Special", Identifier = "FireStation", Template = "SimpleBuilding", Localization = locFireStation }, //Police Station new BuildingInfo { Header = "(A5) Anno 2070", Faction = "Others", Group = "Special", Identifier = "police_station", Template = "SupportBuilding", Localization = locPoliceStation }, new BuildingInfo { Header = "(A6) Anno 2205", Faction = "(1) Earth", Group = "Public Buildings", Identifier = "metro police", Template = "CityInstitutionBuilding", Localization = locPoliceStation }, new BuildingInfo { Header = "(A7) Anno 1800", Faction = "(2) Workers", Group = "Public Buildings", Identifier = "Institution_01 (Police)", Template = "CityInstitutionBuilding", Localization = locPoliceStation }, //Bakery new BuildingInfo { Header = "(A4) Anno 1404", Faction = "Production", Group = "Factory", Identifier = "Bakery", Template = "FactoryBuilding", Localization = locBakery }, new BuildingInfo { Header = "(A7) Anno 1800", Faction = "(2) Workers", Group = "Production Buildings", Identifier = "Food_01 (Bread Maker)", Template = "FactoryBuilding7", Localization = locBakery }, //Rice new BuildingInfo { Header = "(A6) Anno 2205", Faction = "Facilities", Group = "Agriculture", Identifier = "production agriculture earth facility 01", Template = "FactoryBuilding", Localization = locRiceFarm }, new BuildingInfo { Header = "(A6) Anno 2205", Faction = "Facility Modules", Group = "Agriculture", Identifier = "production agriculture earth facility module 01 tier 01", Template = "BuildingModule", Localization = locRiceField } }; var presets = new BuildingPresets { Version = "0.1", Buildings = buildings }; return(presets); }