Ejemplo n.º 1
0
 public BelongsTo(String parentKeyColumnName, String childKeyColumnName, LoadMethods loadMethod, SaveMethods saveMethod)
 {
     ParentKeyColumnName = parentKeyColumnName;
     ChildKeyColumnName  = childKeyColumnName;
     LoadMethod          = loadMethod;
     SaveMethod          = saveMethod;
 }
Ejemplo n.º 2
0
        public CountryTagsLoad(string folderPath)
        {
            Tags  = new List <string>();
            Paths = new List <string>();

            foreach (var filePath in Directory.EnumerateFiles(folderPath, "*.txt"))
            {
                foreach (var rawCommonLine in File.ReadLines(filePath))
                {
                    if (LoadMethods.CommentDetector(rawCommonLine, out var line))
                    {
                        continue;
                    }

                    var tag        = Regex.Match(line, @"^.+?(?=\=)").Value.Trim();
                    var targetFile = Regex.Match(line, "(?<=\").+(?=\")").Value.Trim();

                    if (!File.Exists(Path.Combine(Application.streamingAssetsPath, "Common", targetFile)))
                    {
                        Debug.Log("Not found: " + targetFile);
                    }

                    Tags.Add(tag);
                    Paths.Add(targetFile);
                }
            }
        }
Ejemplo n.º 3
0
        public static AdjacenciesOutput Main()
        {
            var validConnections = new List <int2>();
            var impassables      = new List <int2>();

            foreach (var rawLine in File.ReadLines(Path.Combine(Application.streamingAssetsPath, "Map/adjacencies.csv"))
                     )
            {
                if (LoadMethods.CommentDetector(rawLine, out var line))
                {
                    continue;
                }

                var subStringed = line.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                if (subStringed.Length < 3)
                {
                    throw new Exception("Adjacencies file not following format! " + line);
                }

                // From;To;Type;Through;Data;Comment
                var checker = int.TryParse(subStringed[0], out var provFrom);
                checker = int.TryParse(subStringed[1], out var provTo) && checker;

                if (!checker)
                {
                    throw new Exception("Error in parsing adjancencies! " + line);
                }

                // TODO: Make crossing type relevant.

                if (!Enum.TryParse(subStringed[2], true, out CrossingTypes crossingType))
                {
                    throw new Exception("Unknown crossing! " + line);
                }

                switch (crossingType)
                {
                case CrossingTypes.Sea:
                case CrossingTypes.Land:
                    validConnections.Add(new int2(provFrom, provTo));
                    break;

                case CrossingTypes.Impassable:
                    impassables.Add(new int2(provFrom, provTo));
                    break;

                case CrossingTypes.Canal:
                    break;
                }
            }

            return(new AdjacenciesOutput
            {
                validConnections = validConnections,
                impassables = impassables
            });
        }
Ejemplo n.º 4
0
        private void InstantiateNames(Transform targetHeader, NativeArray <float2> centers,
                                      NativeArray <float> angles, IReadOnlyList <string> strSource, NativeArray <float> longest, bool countryScale,
                                      out bool toggle)
        {
            // Setting header to proper location at bottom left corner of texture.
            // Default scaling is 1 / 100 of the actual texture size. Hardcoded I know. Dividing by 2 because origin is at center of texture.
            targetHeader.localPosition = new Vector3(-_mapComponent.ColorSize.x / 100f / 2f,
                                                     -_mapComponent.ColorSize.y / 100f / 2f, -9);

            for (var i = 0; i < centers.Length; i++)
            {
                var newText       = Instantiate(textPrefab, targetHeader);
                var textTransform = newText.GetComponent <RectTransform>();
                textTransform.localPosition = new Vector3(centers[i].x / 100,
                                                          centers[i].y / 100);
                textTransform.rotation = Quaternion.AngleAxis(angles[i], Vector3.forward);

                var tmp = newText.GetComponent <TextMeshPro>();
                tmp.text = LoadMethods.NameCleaning(strSource[i]);
                textTransform.sizeDelta = new Vector2(tmp.preferredWidth, 2.02f);

                // Default scale: 0.0075. Hardcoded because it's the only one that looks nice.
                var scale = longest[i] / tmp.preferredWidth;
                tmp.name = scale.ToString(CultureInfo.InvariantCulture);

                if (!countryScale && scale > 50 || tmp.preferredWidth < 0.01)
                {
                    Destroy(newText);
                    continue;
                }

                // Trial and error
                if (countryScale)
                {
                    scale *= scale < 10  // Countries
                        ? 0.01f
                        : scale < 20     // Countries
                            ? 0.0075f
                            : scale < 30 // Countries
                                ? 0.006f
                                : 0.004f;
                }
                else
                {
                    scale *= scale < 3 // Provinces
                        ? 0.0078f
                        : scale < 5
                            ? 0.0062f
                            : 0.0035f;
                }

                textTransform.localScale = new Vector3(scale, scale, 1);
            }

            toggle = true;
        }
Ejemplo n.º 5
0
        public void Generate(string definitionsPath, string usedPath)
        {
            Names     = new List <string>();
            Colors    = new List <Color32>();
            IDIndices = new List <int>();

            // Adding clear polar and default regions
            Names.Add("Default");
            Colors.Add(new Color32(0, 0, 0, 0));
            IDIndices.Add(0);

            var secondPass = File.Exists(usedPath);
            var usedCheck  = new HashSet <Color32>();

            if (secondPass)
            {
                var usedRaw = JsonConvert.DeserializeObject <Color32[]>(File.ReadAllText(usedPath));
                foreach (var usedColor in usedRaw)
                {
                    usedCheck.Add(usedColor);
                }

                Debug.Log($"Second pass detected. Size of used provinces: {usedRaw.Length}.");
            }

            foreach (var rawLine in File.ReadLines(definitionsPath, Encoding.GetEncoding(1252)))
            {
                if (LoadMethods.CommentDetector(rawLine, out var line))
                {
                    continue;
                }

                var subStringed = line.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                if (subStringed.Length < 5)
                {
                    throw new Exception("Definitions file not following format! " + line);
                }
                // Num;R;G;B;Name;x
                int.TryParse(subStringed[0], out var provNum);
                byte.TryParse(subStringed[1], out var red);
                byte.TryParse(subStringed[2], out var green);
                byte.TryParse(subStringed[3], out var blue);
                var foundColor = new Color32(red, green, blue, 255);

                if (secondPass && !usedCheck.Contains(foundColor))
                {
                    continue;
                }

                Names.Add(subStringed[4].Trim());
                Colors.Add(foundColor);
                IDIndices.Add(provNum);
            }

            Debug.Log(IDIndices.Count);
        }
Ejemplo n.º 6
0
        public void Generate(string filePath, List <string> areaNames, DistinctColorList distinctColorList)
        {
            const string monsoonPattern = @"\s*?monsoon\s*?=\s*?{.*?}\s*?";
            const string blockPattern   =
                @"(?<regionName>(?<=\}|^)\s*?\w+?)\s*?\=\s*?\{\s*?areas\s*?\=\s*?\{(?<areas>.*?(?=\}\s*?\}))";

            Names         = new List <string>();
            AreaToRegions = new int[areaNames.Count];
            RegionColors  = new List <Color32>();

            var rawFile = File.ReadAllText(filePath);

            // Triplicate remover.
            LoadMethods.EntireAllInOneRemover(ref rawFile);

            var areaLookup = new Dictionary <string, int>(areaNames.Count);

            for (var index = 0; index < areaNames.Count; index++)
            {
                areaLookup[areaNames[index]] = index;
            }

            // Not using monsoon data, removing them all.
            rawFile = Regex.Replace(rawFile, monsoonPattern, "");

            // Adding Unknown as default area.
            Names.Add("unknown");
            RegionColors.Add(Color.white);

            // Get blocks.
            var blocks = Regex.Match(rawFile, blockPattern);

            while (blocks.Success)
            {
                var name = blocks.Groups["regionName"].Value.Trim();
                Names.Add(name);

                RegionColors.Add(distinctColorList.GetNextColor());

                var areaSplit = blocks.Groups["areas"].Value.Trim()
                                .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var areaString in areaSplit)
                {
                    if (areaLookup.TryGetValue(areaString, out var index))
                    {
                        AreaToRegions[index] = Names.Count - 1;
                    }
                }

                blocks = blocks.NextMatch();
            }

            distinctColorList.ResetColorList();
        }
Ejemplo n.º 7
0
        public void AssignDefaults(IReadOnlyList <string> construction)
        {
            Color              = LoadMethods.ParseColor32(construction[0]);
            Uncivilized        = LoadMethods.YesNoConverter(construction[1]);
            CanReduceMilitancy = LoadMethods.YesNoConverter(construction[2]);

            if (!DateTime.TryParse(construction[3], out var dateResult))
            {
                throw new Exception("Unknown date. " + construction[3]);
            }
            int.TryParse("9" + dateResult.ToString("yyyyMMdd"), out Date);
        }
Ejemplo n.º 8
0
        public void Generate(string filePath, List <string> regionNames, DistinctColorList distinctColorList)
        {
            const string blockPattern =
                @"(?<superName>(?<=\}|^)\s*?\w+?)\s*?\=\s*?{(?<regions>.*?(?=\}))";

            Names           = new List <string>();
            RegionsToSupers = new int[regionNames.Count];
            Colors          = new List <Color32>();

            var rawFile = File.ReadAllText(filePath);

            // Triplicate remover.
            LoadMethods.EntireAllInOneRemover(ref rawFile);

            var regionLookup = new Dictionary <string, int>(regionNames.Count);

            for (var index = 0; index < regionNames.Count; index++)
            {
                regionLookup[regionNames[index]] = index;
            }

            // Adding Unknown as default area.
            Names.Add("unknown");
            Colors.Add(Color.white);

            // Get blocks.
            var blocks = Regex.Match(rawFile, blockPattern);

            while (blocks.Success)
            {
                var name = blocks.Groups["superName"].Value.Trim();
                Names.Add(name);

                Colors.Add(distinctColorList.GetNextColor());

                var regionSplit = blocks.Groups["regions"].Value.Trim()
                                  .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var areaString in regionSplit)
                {
                    if (regionLookup.TryGetValue(areaString, out var index))
                    {
                        RegionsToSupers[index] = Names.Count - 1;
                    }
                }

                blocks = blocks.NextMatch();
            }

            distinctColorList.ResetColorList();
        }
Ejemplo n.º 9
0
        public static void SetLoadingScreen(LoadingStages loadingStage)
        {
            switch (loadingStage)
            {
            case LoadingStages.Complete:
                _completed = true;
                break;

            default:
                _loadingTopText.text = "Loading " + LoadMethods.AddSpacesToSentence(loadingStage.ToString())
                                       + Environment.NewLine +
                                       $"<size=70%>{++_counter} / {(int) LoadingStages.Complete}";
                break;
            }
        }
Ejemplo n.º 10
0
        public static Dictionary <string, string> Main()
        {
            var outputDictionary = new Dictionary <string, string>();

            foreach (var localFilePath in Directory.EnumerateFiles(Path.Combine(Application.streamingAssetsPath,
                                                                                "Localization")))
            {
                foreach (var rawLine in File.ReadLines(localFilePath))
                {
                    if (LoadMethods.CommentDetector(rawLine, out var line))
                    {
                        continue;
                    }

                    // Dumping non-english sections. America!
                    var raw = Regex.Match(line, @"^.*?(?=\;)");
                    var key = raw.Value.Replace(";", "").Trim();
                    if (key == string.Empty)
                    {
                        continue;
                    }

                    var value = Regex.Match(line.Substring(raw.Length + 1), @"^.*?(?=\;|$)").Value.Trim();
                    if (value == string.Empty)
                    {
                        continue;
                    }

                    // Capitalizing
                    value = Regex.Replace(value, @"(\b[a-z])", Capitalizing);

                    if (outputDictionary.TryGetValue(key, out _))
                    {
                        outputDictionary.Remove(key);
                    }

                    outputDictionary.Add(key, value);
                }

                string Capitalizing(Match m)
                {
                    return(m.Groups[1].Value.ToUpper());
                }
            }

            return(outputDictionary);
        }
Ejemplo n.º 11
0
        public GuitarPracticeTrackerUI()
        {
            InitializeComponent();
            LoadMethods.loadSavedSongsFromXML();

            dgvSongList.RowHeadersVisible   = false;
            dgvSongList.AutoGenerateColumns = false;
            dgvSongList.Columns.Clear();

            dgvSongList.Columns.Add(new DataGridViewTextBoxColumn
            {
                HeaderText       = "ID",
                Visible          = false,
                DataPropertyName = "ID"
            });

            dgvSongList.Columns.Add(new DataGridViewTextBoxColumn
            {
                HeaderText       = "Name",
                Width            = 150,
                DataPropertyName = "Name"
            });
            dgvSongList.Columns.Add(new DataGridViewTextBoxColumn
            {
                HeaderText       = "Artist",
                Width            = 150,
                DataPropertyName = "Artist"
            });
            dgvSongList.Columns.Add(new DataGridViewTextBoxColumn
            {
                HeaderText       = "Tuning",
                Width            = 100,
                DataPropertyName = "Tuning"
            });
            dgvSongList.Columns.Add(new DataGridViewTextBoxColumn
            {
                HeaderText       = "Difficulty",
                Width            = 97,
                DataPropertyName = "Difficulty"
            });
            dgvSongList.Columns.Add(new DataGridViewTextBoxColumn
            {
                HeaderText       = "Last Practiced",
                Width            = 100,
                DataPropertyName = "LastPracticedMessage"
            });
        }
Ejemplo n.º 12
0
        public static (List <string>, List <(Color Palette, int Index)>) Main(bool cache)
        {
            var(terrainNames, terrainEntities, terrainData,
                paletteLookups) = cache ? JsonUtility.FromJson <TerrainOutput>(
                LoadMethods.Unzip(File.ReadAllBytes(Path.Combine(Application.streamingAssetsPath, "JsonData", "terrain.txt"))))
                : ParseParadoxFile();

            var em = World.DefaultGameObjectInjectionWorld.EntityManager;

            for (var index = 0; index < terrainEntities.Count; index++)
            {
                var terrain = em.CreateEntity(typeof(TerrainEntity));
                var data    = terrainEntities[index];
                data.SetName(terrainNames[index]);
                em.SetComponentData(terrain, data);

                using (var currentCoreActions = new NativeArray <FirstLevelCore>(
                           ((List <FirstLevelCore>)terrainData[index]).ToArray(), Allocator.Temp))
                {
                    em.AddBuffer <FirstLevelCore>(terrain).AddRange(currentCoreActions);
                }
            }

            // Creating collection entity.
            FileUnpacker.GetCollector <TerrainEntity>();

            /* DEBUG
             * var test = em.GetBuffer<Terrains>(terrainCollectorEntity);
             * var test1 = test.AsNativeArray();
             * for (var index = 0; index < test1.Length; index++)
             * {
             *  var terrainType = test1[index];
             *  var color = em.GetComponentData<TerrainEntity>(terrainType.TerrainEntity).Color;
             *  Debug.Log(terrainNames[index] + " color: " + color);
             *  var coreActions = em.GetBuffer<TerrainValues>(terrainType.TerrainEntity).AsNativeArray();
             *  foreach (var action in coreActions)
             *      Debug.Log(action);
             * }
             */
            return(terrainNames,
                   paletteLookups.ConvertAll(input => ((Color, int))input));
        }
Ejemplo n.º 13
0
        public static (Entity, List <string>) Main()
        {
            var governments     = new NativeList <EntityWrapper>(Allocator.Temp);
            var governmentNames = new List <string>();

            var fileTree = new List <KeyValuePair <int, object> >();
            var values   = new List <string>();

            var em = World.Active.EntityManager;

            FileUnpacker.ParseFile(Path.Combine(Application.streamingAssetsPath, "Common", "governments.txt"), fileTree,
                                   values, GovernmentMagicOverride);

            using (var governIdeologies = new NativeList <DataInt>(Allocator.Temp))
            {
                for (var index = 0; index < fileTree.Count; index++)
                {
                    var currentEntity     = governments[index];
                    var currentGovernment = new GovernmentEntity
                    {
                        Index = fileTree[index].Key - (int)MagicUnifiedNumbers.Placeholder
                    };

                    foreach (var govProp in (List <KeyValuePair <int, object> >)fileTree[index].Value)
                    {
                        var targetStr = values[(int)govProp.Value];
                        switch (govProp.Key / 10000)
                        {
                        case 0:
                            switch ((LoadVariables)govProp.Key)
                            {
                            case LoadVariables.AppointRulingParty:
                                currentGovernment.AppointRulingParty = LoadMethods.YesNoConverter(targetStr);
                                break;

                            case LoadVariables.Election:
                                currentGovernment.Election = LoadMethods.YesNoConverter(targetStr);
                                break;

                            case LoadVariables.Duration:         // Election cycle
                                if (!int.TryParse(targetStr, out var duration))
                                {
                                    throw new Exception("Unknown government duration. " + targetStr);
                                }

                                currentGovernment.Duration = duration;
                                break;

                            case LoadVariables.FlagType:
                                if (!Enum.TryParse(targetStr, true, out GovernmentEntity.Flag flagType))
                                {
                                    throw new Exception("Unknown government flag type. " + targetStr);
                                }

                                currentGovernment.FlagType = flagType;
                                break;

                            default:
                                throw new Exception("Invalid government file structure. " +
                                                    (LoadVariables)govProp.Key);
                            }

                            break;

                        case (int)MagicUnifiedNumbers.Ideology / 10000:
                            if (LoadMethods.YesNoConverter(targetStr))
                            {
                                governIdeologies.Add(govProp.Key - (int)MagicUnifiedNumbers.Ideology);
                            }
                            break;

                        default:
                            throw new Exception("Invalid magic number detected in governments.");
                        }
                    }

                    em.AddBuffer <DataInt>(currentEntity).AddRange(governIdeologies);
                    governIdeologies.Clear();
                    em.SetComponentData(currentEntity, currentGovernment);
                }
            }

            var governmentCollectorEntity = FileUnpacker.GetCollector <GovernmentCollection>(governments);

            governments.Dispose();

            return(governmentCollectorEntity, governmentNames);

            int GovernmentMagicOverride(int parent, string raw)
            {
                if (parent != -1)
                {
                    return((int)MagicUnifiedNumbers.ContinueMagicNumbers);
                }

                governments.Add(em.CreateEntity(typeof(GovernmentEntity)));

                governmentNames.Add(raw);
                // Government is used as a color override.
                return((int)MagicUnifiedNumbers.Placeholder + governmentNames.Count - 1);
            }
        }
Ejemplo n.º 14
0
 public BelongsTo(LoadMethods loadMethod)
 {
     LoadMethod = loadMethod;
 }
Ejemplo n.º 15
0
 public BelongsTo(LoadMethods loadMethod, SaveMethods saveMethod)
 {
     LoadMethod = loadMethod;
     SaveMethod = saveMethod;
 }
Ejemplo n.º 16
0
        public static (Entity, string[]) Main(Entity technologies, Entity inventions,
                                              Entity cultures, Entity ideologies, Entity subPolicies, Entity governments,
                                              Entity nationalValues)
        {
            var allCountries     = new NativeArray <EntityWrapper>(LookupDictionaries.CountryTags.Count, Allocator.Temp);
            var em               = World.Active.EntityManager;
            var countryArchetype = em.CreateArchetype(typeof(CountryPopulationComponent),
                                                      typeof(CountryPoliticsComponent), typeof(CountryTechnologyComponent));
            var rulingParties = new string[LookupDictionaries.CountryTags.Count];

            var countryPolicies =
                new NativeArray <CountryPolicies>(LookupDictionaries.PolicyGroups.Count, Allocator.Temp);

            using (var nationalValueList = em.GetBuffer <EntityWrapper>(nationalValues).ToNativeArray(Allocator.Temp))
                using (var governmentList = em.GetBuffer <EntityWrapper>(governments).ToNativeArray(Allocator.Temp))
                    using (var subPolicyList = em.GetBuffer <EntityWrapper>(subPolicies).ToNativeArray(Allocator.Temp))
                        using (var ideologyList = em.GetBuffer <EntityWrapper>(ideologies).ToNativeArray(Allocator.Temp))
                            using (var inventionList = em.GetBuffer <EntityWrapper>(inventions).ToNativeArray(Allocator.Temp))
                                using (var cultureList = em.GetBuffer <EntityWrapper>(cultures).ToNativeArray(Allocator.Temp))
                                    using (var technologyList = em.GetBuffer <EntityWrapper>(technologies).ToNativeArray(Allocator.Temp))
                                        using (var countryUpperHouse = new NativeList <CountryUpperHouse>(Allocator.Temp))
                                            using (var countryInventions = new NativeList <CountryInventions>(Allocator.Temp))
                                                using (var countryTechnologies = new NativeList <CountryTechnologies>(Allocator.Temp))
                                                    using (var countryCultures = new NativeList <CountryCultures>(Allocator.Temp))
                                                    {
                                                        foreach (var countryFile in Directory.EnumerateFiles(
                                                                     Path.Combine(Application.streamingAssetsPath, "History", "countries"), "*.txt"))
                                                        {
                                                            var fileTree = new List <KeyValuePair <int, object> >();
                                                            var values   = new List <string>();

                                                            FileUnpacker.ParseFile(countryFile, fileTree, values, CountryHistoryMagicOverride);

                                                            var countryTag = Regex.Match(Path.GetFileNameWithoutExtension(countryFile) ?? "", @"^.+?(?=\-)")
                                                                             .Value
                                                                             .Trim().ToLower();
                                                            if (!LookupDictionaries.CountryTags.TryGetValue(countryTag, out var countryIndex))
                                                            {
                                                                continue;
                                                            }

                                                            var countryEntity = em.CreateEntity(countryArchetype);

                                                            var currentCountry = new CountryEntity {
                                                                Index = countryIndex
                                                            };
                                                            var currentPopulation = new CountryPopulationComponent();
                                                            var currentPolitics   = new CountryPoliticsComponent();
                                                            var currentTechnology = new CountryTechnologyComponent();
                                                            // Resetting polices
                                                            for (var index = 0; index < countryPolicies.Length; index++)
                                                            {
                                                                countryPolicies[index] = Entity.Null;
                                                            }

                                                            foreach (var target in fileTree)
                                                            {
                                                                var targetStr = target.Key < (int)LoadVariables.BreakCore
                            ? values[(int)target.Value]
                            : string.Empty;

                                                                switch ((LoadVariables)target.Key)
                                                                {
                                                                case LoadVariables.Capital:
                                                                    currentPolitics.Capital = int.Parse(targetStr);
                                                                    break;

                                                                case LoadVariables.RulingParty:
                                                                    rulingParties[countryIndex] = targetStr;
                                                                    break;

                                                                case LoadVariables.UpperHouse:
                                                                    foreach (var ideology in (List <KeyValuePair <int, object> >)target.Value)
                                                                    {
                                                                        if (!float.TryParse(values[(int)ideology.Value], out var ideologyPercentage))
                                                                        {
                                                                            throw new Exception("Country ideology parsing failed! " +
                                                                                                values[(int)ideology.Value]);
                                                                        }

                                                                        if (ideologyPercentage > 0.01)
                                                                        {
                                                                            countryUpperHouse.Add(
                                                                                new CountryUpperHouse(
                                                                                    ideologyList[ideology.Key - (int)MagicUnifiedNumbers.Ideology],
                                                                                    ideologyPercentage));
                                                                        }
                                                                    }

                                                                    break;

                                                                case LoadVariables.Government:
                                                                    if (!LookupDictionaries.Governments.TryGetValue(targetStr, out var governmentIndex))
                                                                    {
                                                                        throw new Exception("Unknown government. " + targetStr);
                                                                    }

                                                                    currentPolitics.Government = governmentList[governmentIndex];
                                                                    break;

                                                                case LoadVariables.Prestige:
                                                                    currentPolitics.Prestige = int.Parse(targetStr);
                                                                    break;

                                                                case LoadVariables.Civilized:
                                                                    currentTechnology.Civilized = LoadMethods.YesNoConverter(targetStr);
                                                                    break;

                                                                case LoadVariables.NonStateCultureLiteracy:
                                                                    currentTechnology.NonStateCultureLiteracy = int.Parse(targetStr);
                                                                    break;

                                                                case LoadVariables.Literacy:
                                                                    currentTechnology.Literacy = int.Parse(targetStr);
                                                                    break;

                                                                case LoadVariables.Plurality:
                                                                    currentTechnology.Plurality = int.Parse(targetStr);
                                                                    break;

                                                                case LoadVariables.Consciousness:
                                                                    currentPopulation.Consciousness = int.Parse(targetStr);
                                                                    break;

                                                                case LoadVariables.NonStateConsciousness:
                                                                    currentPopulation.NonStateConsciousness = int.Parse(targetStr);
                                                                    break;

                                                                case LoadVariables.PrimaryCulture:
                                                                    if (!LookupDictionaries.Cultures.TryGetValue(targetStr, out var primaryCultureIndex))
                                                                    {
                                                                        throw new Exception("Unknown primary culture. " + targetStr);
                                                                    }

                                                                    currentPopulation.PrimaryCulture = cultureList[primaryCultureIndex];
                                                                    break;

                                                                case LoadVariables.NationalValue:
                                                                    if (!LookupDictionaries.NationalValues.TryGetValue(targetStr, out var natValIndex))
                                                                    {
                                                                        throw new Exception("Unknown national value. " + targetStr);
                                                                    }

                                                                    currentPopulation.NationalValue = nationalValueList[natValIndex];
                                                                    break;

                                                                case LoadVariables.Culture:
                                                                    if (!LookupDictionaries.Cultures.TryGetValue(targetStr, out var cultureIndex))
                                                                    {
                                                                        throw new Exception("Unknown culture. " + targetStr);
                                                                    }

                                                                    countryCultures.Add(cultureList[cultureIndex]);
                                                                    break;

                                                                case LoadVariables.ForeignInvestment:
                                                                case LoadVariables.Oob:
                                                                case LoadVariables.Decision:
                                                                    // Skipping
                                                                    break;

                                                                default:
                                                                    switch ((MagicUnifiedNumbers)(target.Key / 10000 * 10000))
                                                                    {
                                                                    case MagicUnifiedNumbers.Placeholder:
                                                                        break;

                                                                    case MagicUnifiedNumbers.Invention:
                                                                        countryInventions.Add(
                                                                            new CountryInventions(
                                                                                inventionList[target.Key - (int)MagicUnifiedNumbers.Invention],
                                                                                LoadMethods.YesNoConverter(values[(int)target.Value])));
                                                                        break;

                                                                    case MagicUnifiedNumbers.Technology:
                                                                        countryTechnologies.Add(technologyList[target.Key - (int)MagicUnifiedNumbers.Technology]);
                                                                        break;

                                                                    case MagicUnifiedNumbers.PolicyGroup:
                                                                        if (!LookupDictionaries.SubPolicies.TryGetValue(values[(int)target.Value],
                                                                                                                        out var subPolicyIndex))
                                                                        {
                                                                            throw new Exception("Unknown policy group. " + values[(int)target.Value]);
                                                                        }

                                                                        countryPolicies[countryIndex * LookupDictionaries.PolicyGroups.Count
                                                                                        + (target.Key - (int)MagicUnifiedNumbers.PolicyGroup)]
                                                                            = subPolicyList[subPolicyIndex];
                                                                        break;
                                                                    }

                                                                    Debug.LogWarning("Uncaught load variable on country history load "
                                                                                     + (LoadVariables)target.Key);
                                                                    break;
                                                                }
                                                            }

                                                            em.SetComponentData(countryEntity, currentCountry);
                                                            em.SetComponentData(countryEntity, currentPopulation);
                                                            em.SetComponentData(countryEntity, currentPolitics);
                                                            em.SetComponentData(countryEntity, currentTechnology);

                                                            em.AddBuffer <CountryUpperHouse>(countryEntity).AddRange(countryUpperHouse);
                                                            countryUpperHouse.Clear();
                                                            em.AddBuffer <CountryTechnologies>(countryEntity).AddRange(countryTechnologies);
                                                            countryTechnologies.Clear();
                                                            em.AddBuffer <CountryInventions>(countryEntity).AddRange(countryInventions);
                                                            countryInventions.Clear();
                                                            em.AddBuffer <CountryCultures>(countryEntity).AddRange(countryCultures);
                                                            countryCultures.Clear();
                                                            em.AddBuffer <CountryPolicies>(countryEntity).AddRange(countryPolicies);

                                                            allCountries[countryIndex] = countryEntity;
                                                        }
                                                    }
            // Not in using statement as the values are mutable.
            countryPolicies.Dispose();

            var countryCollector = FileUnpacker.GetCollector <CountryCollection>(allCountries);

            allCountries.Dispose();

            return(countryCollector, rulingParties);

            int CountryHistoryMagicOverride(int parent, string target)
            {
                // Skipping other start dates
                return(Regex.IsMatch(target, @"\d+")
                    ? (int)MagicUnifiedNumbers.Placeholder
                    : (int)MagicUnifiedNumbers.ContinueMagicNumbers);
            }
        }
Ejemplo n.º 17
0
    public static void Main(Entity provinces, NativeHashMap <int, int> idIndex)
    {
        var em           = World.Active.EntityManager;
        var provinceList = em.GetBuffer <EntityWrapper>(provinces).AsNativeArray();

        // TODO: Possible parallel?
        foreach (var regionPop in Directory.EnumerateFiles(
                     Path.Combine(Application.streamingAssetsPath, "History", "pops", "1836.1.1"),
                     "*.txt"))
        {
            var  curProv = 0;
            bool employToggle = false, provToggle = false;
            var  currentPop = new ProvPopInfo();

            foreach (var line in File.ReadLines(regionPop))
            {
                if (LoadMethods.CommentDetector(line, out var commentSplit))
                {
                    continue;
                }

                if (commentSplit.Contains("{"))
                {
                    if (provToggle)
                    {
                        employToggle = true;
                        currentPop   = new ProvPopInfo
                        {
                            Employment = LookupDictionaries.PopTypes[
                                Regex.Match(commentSplit, @"^.+(?=\=)").Value.Trim()]
                        };
                        continue;
                    }

                    provToggle = true;
                    int.TryParse(Regex.Match(commentSplit, @"\d+").Value, out curProv);
                    continue;
                }

                if (employToggle)
                {
                    var equalsSplit = commentSplit.Split(new[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
                    switch (equalsSplit[0].Trim())
                    {
                    case "culture":
                        currentPop.Culture = LookupDictionaries.Cultures[equalsSplit[1].Trim()];
                        break;

                    case "religion":
                        currentPop.Religion = LookupDictionaries.Religions[equalsSplit[1].Trim()];
                        break;

                    case "size":
                        if (!int.TryParse(Regex.Match(equalsSplit[1], @"\d+").Value, out var value))
                        {
                            throw new Exception("Unknown population size: " + equalsSplit[1]);
                        }
                        currentPop.Size = value;
                        break;
                    }
                }

                if (!commentSplit.Contains("}"))
                {
                    continue;
                }

                if (employToggle)
                {
                    employToggle = false;
                    em.GetBuffer <ProvPopInfo>(provinceList[idIndex[curProv]]).Add(currentPop);
                    continue;
                }

                provToggle = false;
            }
        }
    }
Ejemplo n.º 18
0
 public HasAndBelongsToMany(LoadMethods loadMethod, SaveMethods saveMethod)
 {
     LoadMethod = loadMethod;
     SaveMethod = saveMethod;
 }
Ejemplo n.º 19
0
        public static void Main()
        {
            // TODO: Needs policies and ideologies.

            // Output events list.
            var events = new List <GameEventInfo>();

            // Collapse tree into arrays
            var eventRanges = new List <int3>(); // x: type. z: start index, inclusive. w: end index, exclusive
            // If type == random_list, x is replaced with chance.
            // Value arrays
            var eventActions = new List <float2>(); // x: type. z: threshold
            var stringValues = new List <string>();

            // TODO: Possibly convert all disposes of parent location to using?
            var parentLocation = new NativeMultiHashMap <int, int>(10, Allocator.TempJob);

            foreach (var eventFile in Directory.EnumerateFiles(Path.Combine(Application.streamingAssetsPath, "Events"),
                                                               "*.txt"))
            {
                var fileTree = new List <KeyValuePair <int, object> >();
                var values   = new List <string>();

                FileUnpacker.ParseFile(eventFile, fileTree, values, EventMagicOverride);

                GameEventInfo currentEvent;

                foreach (var parsedEvent in fileTree)
                {
                    currentEvent = new GameEventInfo {
                        Fired = false, Index = eventRanges.Count
                    };
                    parentLocation.Add(parsedEvent.Key, eventRanges.Count);
                    eventRanges.Add(new int3(parsedEvent.Key, -1, -1));

                    //FileUnpacker.ProcessQueue(parsedEvent, eventActions, eventRanges,
                    //parentLocation, values, EventSwitchOverride);

                    events.Add(currentEvent);
                }

                bool EventSwitchOverride(string targetStr, KeyValuePair <int, object> kvpObject)
                {
                    switch ((LoadVariables)kvpObject.Key)
                    {
                    case LoadVariables.FireOnlyOnce:
                        currentEvent.FireOnlyOnce = LoadMethods.YesNoConverter(targetStr);
                        return(true);

                    case LoadVariables.ChangeRegionName:
                    case LoadVariables.ChangeProvinceName:
                    case LoadVariables.Title:
                    case LoadVariables.Desc:
                    case LoadVariables.Picture:
                    case LoadVariables.Name:
                        eventActions.Add(new float2(kvpObject.Key, stringValues.Count));
                        stringValues.Add(targetStr.Replace("\"", ""));
                        return(true);

                    case LoadVariables.HasLeader:     // String
                        // Skipping
                        return(true);

                    default:
                        return(false);
                    }
                }

                // Assigns magic numbers.
                int EventMagicOverride(int parent, string str)
                {
                    if ((parent == (int)LoadVariables.AddCasusBelli ||
                         parent == (int)LoadVariables.CasusBelli) &&
                        str.Equals("type"))
                    {
                        return((int)LoadVariables.TypeCasusBelli);
                    }

                    if (parent != (int)LoadVariables.RandomList)
                    {
                        return((int)MagicUnifiedNumbers.ContinueMagicNumbers);
                    }

                    if (!int.TryParse(str, out var probability))
                    {
                        throw new Exception("Random list probability unknown! " + str);
                    }
                    return((int)MagicUnifiedNumbers.Probabilities + probability);
                }
            }

            parentLocation.Dispose();
        }
Ejemplo n.º 20
0
        public static (List <(int, int)>, List <string>) Main(bool cache, NativeHashMap <int, int> idIndex)
        {
            var provinces         = new List <(int, int)>();
            var continentNames    = new List <string>();
            var continentEntities = new List <ContinentEntity>();

            if (cache)
            {
                (provinces, continentEntities, continentNames) = JsonUtility.FromJson <ContinentOutput>(
                    LoadMethods.Unzip(File.ReadAllBytes(Path.Combine(Application.streamingAssetsPath, "JsonData", "continent.txt"))));

                LoadMethods.GenerateCacheEntities <ContinentEntity, ContinentCollection>(continentEntities, continentNames);

                return(provinces, continentNames);
            }

            var em = World.DefaultGameObjectInjectionWorld.EntityManager;

            var continents = new NativeList <EntityWrapper>(Allocator.Temp);

            var outerToggle = false;
            var provToggle  = false;
            var currentCont = new ContinentEntity();

            foreach (var rawLine in File.ReadLines(Path.Combine(Application.streamingAssetsPath, "map", "continent.txt")))
            {
                if (LoadMethods.CommentDetector(rawLine, out var line))
                {
                    continue;
                }

                var equalSplit = Regex.Match(line, @"^.*?(?=\=)");

                if (line.Contains("{"))
                {
                    var newLine = line.Substring(equalSplit.Length + 1).Replace("{", "").Trim();
                    if (!outerToggle)
                    {
                        outerToggle = true;
                        var name = equalSplit.Value.Trim();
                        currentCont = new ContinentEntity {
                            Name = name
                        };                                               // {Index = continentNames.Count};
                        continentNames.Add(name);

                        if (newLine == string.Empty)
                        {
                            continue;
                        }

                        equalSplit = Regex.Match(newLine, @"^.*?(?=\=)");
                    }

                    if (!equalSplit.Value.Contains("provinces"))
                    {
                        throw new Exception("Unknown nested value: " + equalSplit);
                    }

                    provToggle = true;

                    if (newLine == string.Empty)
                    {
                        continue;
                    }

                    line = newLine;
                }

                if (provToggle)
                {
                    var numbers = Regex.Match(line, @"[\d\s]+");
                    if (numbers.Success)
                    {
                        var individualProv = numbers.Value.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var provId in individualProv)
                        {
                            if (!int.TryParse(provId, out var num))
                            {
                                continue;
                            }

                            provinces.Add((idIndex[num], continents.Length));
                        }
                    }
                }
                else
                {
                    var newLine = line.Substring(equalSplit.Length + 1).Replace("}", "").Trim();
                    switch (equalSplit.Value.Trim())
                    {
                    case "assimilation_rate":
                        if (!float.TryParse(newLine, out var assimilationRate))
                        {
                            throw new Exception("Unknown assimilation rate: " + newLine);
                        }
                        currentCont.AssimilationRate = assimilationRate;
                        break;

                    case "farm_rgo_size":
                        if (!float.TryParse(newLine, out var farmSize))
                        {
                            throw new Exception("Unknown farm RGO size: " + newLine);
                        }
                        currentCont.FarmRgoSize = farmSize;
                        break;

                    case "mine_rgo_size":
                        if (!float.TryParse(newLine, out var mineSize))
                        {
                            throw new Exception("Unknown mine RGO size: " + newLine);
                        }
                        currentCont.MineRgoSize = mineSize;
                        break;
                    }
                }

                if (!line.Contains("}"))
                {
                    continue;
                }

                if (provToggle)
                {
                    provToggle = false;
                }
                else
                {
                    outerToggle = false;
                    var target = em.CreateEntity(typeof(ContinentEntity));
                    em.SetComponentData(target, currentCont);
                    continents.Add(target);
                    continentEntities.Add(currentCont);
                }
            }

            FileUnpacker.GetCollector <ContinentCollection>();
            continents.Dispose();

            //File.WriteAllText(Path.Combine(Application.streamingAssetsPath, "JsonData", "continent.txt"),
            //JsonUtility.ToJson(new ContinentOutput(continentNames, provinces, continentEntities), true));

            File.WriteAllBytes(Path.Combine(Application.streamingAssetsPath, "JsonData", "continent.txt"),
                               LoadMethods.Zip(JsonUtility.ToJson(new ContinentOutput(continentNames, provinces, continentEntities))));

            return(provinces, continentNames);
        }
Ejemplo n.º 21
0
 public HasOne(LoadMethods loadMethod)
 {
     LoadMethod = loadMethod;
 }
Ejemplo n.º 22
0
        private static TerrainOutput ParseParadoxFile()
        {
            var fileTree = new List <(int Key, object Value)>();

            var terrainNames   = new List <string>();
            var terrains       = new List <TerrainEntity>();
            var terrainCache   = new List <List <FirstLevelCore> >();
            var paletteLookups = new List <(Color Palette, int Index)>();

            // Generating file tree representation.
            FileUnpacker.ParseFile(Path.Combine(Application.streamingAssetsPath, "map", "terrain.txt"),
                                   fileTree, TerrainMagicOverride);

            for (var index = 0; index < fileTree.Count; index++)
            {
                var currentTerrain = terrains[index];

                var(breakCores, _) = FileUnpacker.AssignFirstLevelDistributeWorkload(ref currentTerrain, fileTree[index],
                                                                                     TerrainOverride);

                terrainCache.Add(breakCores);

                bool TerrainOverride((int Key, object Value) target)
                {
                    switch ((LoadVariables)target.Key)
                    {
                    case LoadVariables.Palette:
                        if (!ColorUtility.TryParseHtmlString("#" + (string)target.Value, out var paletteColor))
                        {
                            throw new Exception("Unknown hex color. " + (string)target.Value);
                        }

                        paletteLookups.Add((paletteColor, index));
                        return(true);

                    default:
                        return(false);
                    }
                }
            }

            int TerrainMagicOverride(int parent, string str)
            {
                if (parent != -1)
                {
                    return((int)MagicUnifiedNumbers.ContinueMagicNumbers);
                }

                terrainNames.Add(str);

                terrains.Add(new TerrainEntity {
                    Name = str
                });
                return((int)MagicUnifiedNumbers.Terrain + terrainNames.Count - 1);
            }

            var output = new TerrainOutput(terrainNames, terrains, terrainCache, paletteLookups);

            //File.WriteAllText(Path.Combine(Application.streamingAssetsPath, "JsonData", "terrain.txt"),
            //JsonUtility.ToJson(output, true));

            File.WriteAllBytes(Path.Combine(Application.streamingAssetsPath, "JsonData", "terrain.txt"),
                               LoadMethods.Zip(JsonUtility.ToJson(output)));

            return(output);
        }
Ejemplo n.º 23
0
        public void Generate(string areasPath, List <int> idIndices, DistinctColorList distinctColorList)
        {
            const string colorPattern =
                @"(?<areaName>(?<=\}|^)\w+?)\s*?\=\s*?\{\s*?color\s*?\=\s*?\{(?<color>.*?(?=\}))";
            const string blockPattern        = @"(?<areaName>(?<=^|\}).*?(?=\=)).*?(?<provIds>(?<=\{).*?(?=\}))";
            const string colorRemovalPattern = @"color.*?}";

            ProvinceToAreas = new int[idIndices.Count];
            Names           = new List <string>();
            AreaColors      = new List <Color32>();
            var customColors = new Dictionary <string, Color32>();

            var idLookup = new Dictionary <int, int>(idIndices.Count);

            for (var index = 0; index < idIndices.Count; index++)
            {
                idLookup[idIndices[index]] = index;
            }

            var areaFile = File.ReadAllText(areasPath);

            // Triplicate remover.
            LoadMethods.EntireAllInOneRemover(ref areaFile);

            // Finding colors needs to be first.
            var colors = Regex.Match(areaFile, colorPattern);

            while (colors.Success)
            {
                customColors[colors.Groups["areaName"].Value.Trim()] =
                    LoadMethods.ParseColor32(colors.Groups["color"].Value);

                colors = colors.NextMatch();
            }

            // Removing colors.
            areaFile = Regex.Replace(areaFile, colorRemovalPattern, "");

            // Adding Unknown as default area.
            Names.Add("unknown");
            AreaColors.Add(Color.white);

            // Get blocks.
            var blocks = Regex.Match(areaFile, blockPattern);

            while (blocks.Success)
            {
                var name = blocks.Groups["areaName"].Value.Trim();
                Names.Add(name);

                if (customColors.TryGetValue(name, out var predefinedColor))
                {
                    AreaColors.Add(predefinedColor);
                }
                else
                {
                    AreaColors.Add(distinctColorList.GetNextColor());
                }

                var provinces = blocks.Groups["provIds"].Value.Trim()
                                .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var idString in provinces)
                {
                    if (!int.TryParse(idString, out var id))
                    {
                        throw new Exception(
                                  $"Invalid province id '{idString}' found in area '{Names.Last()}' parsing.");
                    }

                    if (idLookup.TryGetValue(id, out var index))
                    {
                        ProvinceToAreas[index] = Names.Count - 1;
                    }
                }

                blocks = blocks.NextMatch();
            }

            distinctColorList.ResetColorList();
        }
Ejemplo n.º 24
0
 public void AssignDefaults(IReadOnlyList <string> construction)
 {
     Color        = LoadMethods.ParseColor32(construction[0]);
     MovementCost = float.Parse(construction[1]);
     //Index = (int) construction[2];
 }
Ejemplo n.º 25
0
        public static (Entity, List <string>) Main()
        {
            var popFiles = Directory.GetFiles(Path.Combine(Application.streamingAssetsPath, "PopTypes"), "*.txt");

            // Output arrays
            var popTypes = new NativeList <EntityWrapper>(Allocator.Temp);
            var popNames = new List <string>();

            popNames.AddRange(popFiles.Select(Path.GetFileNameWithoutExtension));

            var em = World.Active.EntityManager;

            using (var needsList = new NativeList <DataGood>(Allocator.Temp))
                using (var popRebels = new NativeList <DataValue>(Allocator.Temp))
                {
                    for (var index = 0; index < popTypes.Length; index++)
                    {
                        // Generating file tree
                        var fileTree = new List <KeyValuePair <int, object> >();
                        var values   = new List <string>();

                        FileUnpacker.ParseFile(popFiles[index], fileTree, values,
                                               (i, s) => (int)MagicUnifiedNumbers.ContinueMagicNumbers);

                        var currentEntity  = em.CreateEntity(typeof(PopTypeEntity));
                        var currentPopType = new PopTypeEntity {
                            Index = index
                        };

                        foreach (var topLevel in fileTree)
                        {
                            switch ((LoadVariables)topLevel.Key)
                            {
                            case LoadVariables.Sprite:
                                // Skipping sprite
                                break;

                            case LoadVariables.Color:
                                currentPopType.Color = LoadMethods.ParseColor32(values[(int)topLevel.Value]);
                                break;

                            case LoadVariables.Strata:
                                if (!Enum.TryParse(values[(int)topLevel.Value], true,
                                                   out PopTypeEntity.Standing strata))
                                {
                                    throw new Exception("Strata unknown: " + values[(int)topLevel.Value]);
                                }
                                currentPopType.Strata = strata;
                                break;

                            case LoadVariables.StateCapitalOnly:
                                currentPopType.StateCapitalOnly =
                                    LoadMethods.YesNoConverter(values[(int)topLevel.Value]);
                                break;

                            case LoadVariables.Rebel:
                                RebelParser(topLevel);
                                em.AddBuffer <DataValue>(currentEntity).AddRange(popRebels);
                                popRebels.Clear();
                                break;

                            case LoadVariables.CountryMigrationTarget:
                            case LoadVariables.MigrationTarget:
                            case LoadVariables.PromoteTo:
                            case LoadVariables.Ideologies:
                                var collapsedList = new List <float2>();
                                RestParser(topLevel, collapsedList);
                                break;

                            case LoadVariables.LifeNeeds:
                            case LoadVariables.EverydayNeeds:
                            case LoadVariables.LuxuryNeeds:
                                NeedsParser(topLevel);
                                break;
                            }
                        }

                        em.AddBuffer <DataGood>(currentEntity).AddRange(needsList);
                        em.SetComponentData(currentEntity, currentPopType);
                        popTypes.Add(currentEntity);
                        needsList.Clear();

                        // DEBUG
                        //break;

                        void RestParser(KeyValuePair <int, object> currentBranch, List <float2> targetList)
                        {
                        }

                        void NeedsParser(KeyValuePair <int, object> currentBranch)
                        {
                            // There should be no nested values within needs.
                            var startingNeeds = needsList.Length;

                            foreach (var goodsKvp in (List <KeyValuePair <int, object> >)currentBranch.Value)
                            {
                                if (!float.TryParse(values[(int)goodsKvp.Value], out var goodsNeeded))
                                {
                                    throw new Exception("Unknown goods needed: " + values[(int)goodsKvp.Value]);
                                }

                                needsList.Add(new DataGood(goodsKvp.Key - (int)MagicUnifiedNumbers.Goods, goodsNeeded));
                            }

                            switch ((LoadVariables)currentBranch.Key)
                            {
                            case LoadVariables.LifeNeeds:
                                currentPopType.lifeRange = new int2(startingNeeds, needsList.Length);
                                break;

                            case LoadVariables.EverydayNeeds:
                                currentPopType.everydayRange = new int2(startingNeeds, needsList.Length);
                                break;

                            case LoadVariables.LuxuryNeeds:
                                currentPopType.luxuryRange = new int2(startingNeeds, needsList.Length);
                                break;
                            }
                        }

                        void RebelParser(KeyValuePair <int, object> currentBranch)
                        {
                            foreach (var armyKvp in (List <KeyValuePair <int, object> >)currentBranch.Value)
                            {
                                if (!float.TryParse(values[(int)armyKvp.Value], out var armyRatio))
                                {
                                    throw new Exception("Unknown army ratio: " + values[(int)armyKvp.Value]);
                                }

                                if (armyRatio < 0.001)
                                {
                                    continue;
                                }

                                popRebels.Add(new DataValue(armyKvp.Key - (int)MagicUnifiedNumbers.Unit, armyRatio));
                            }
                        }
                    }
                }

            var popTypeCollectorEntity = FileUnpacker.GetCollector <PopTypeCollection>(popTypes);

            popTypes.Dispose();

            return(popTypeCollectorEntity, popNames);
        }
Ejemplo n.º 26
0
 public HasAndBelongsToMany(String relationshipTableName, LoadMethods loadMethod, SaveMethods saveMethod)
 {
     RelationshipTableName = relationshipTableName;
     LoadMethod            = loadMethod;
     SaveMethod            = saveMethod;
 }
Ejemplo n.º 27
0
        public static (List <string>, List <string>) Main(bool cache)
        {
            var cultures          = new List <CultureEntity>();
            var cultureNames      = new List <string>();
            var cultureGroupNames = new List <string>();

            if (cache)
            {
                (cultureNames, cultureGroupNames, cultures) = JsonUtility.FromJson <CulturesOutput>(
                    LoadMethods.Unzip(File.ReadAllBytes(Path.Combine(Application.streamingAssetsPath, "JsonData", "cultures.txt"))));

                LoadMethods.GenerateCacheEntities <CultureEntity, CultureCollection>(cultures, cultureNames, cultureGroupNames);

                return(cultureNames, cultureGroupNames);
            }

            var em = World.DefaultGameObjectInjectionWorld.EntityManager;

            bool groupToggle   = false,
                 cultureToggle = false,
                 ignoreToggle  = false;
            var currentCulture = new CultureEntity();

            foreach (var line in File.ReadLines(Path.Combine(Application.streamingAssetsPath, "common",
                                                             "cultures.txt")))
            {
                if (LoadMethods.CommentDetector(line, out var commentSplit))
                {
                    continue;
                }

                if (ignoreToggle)
                {
                    if (commentSplit.Contains("}"))
                    {
                        ignoreToggle = false;
                    }

                    // Assuming no values defined after end brackets
                    continue;
                }

                var equalsSplit = Regex.Match(commentSplit, @"^.+?(?=\=)");
                var preEquals   = equalsSplit.Success ? equalsSplit.Value.Trim() : "";

                if (commentSplit.Contains("{"))
                {
                    if (!groupToggle)
                    {
                        groupToggle = true;
                        cultureGroupNames.Add(preEquals);
                        continue;
                    }

                    if (!commentSplit.Contains("_names") && !commentSplit.Contains("color"))
                    {
                        cultureToggle = true;
                        var name = preEquals.Trim();
                        cultureNames.Add(name);
                        currentCulture = new CultureEntity {
                            Group = cultureGroupNames.Last(), Name = name
                        };
                    }
                }

                switch (preEquals)
                {
                case "union":
                    currentCulture.Union =
                        LookupDictionaries.CountryTags[commentSplit.Substring(equalsSplit.Length + 1).Trim()];
                    continue;

                case "first_names":
                case "last_names":
                    // TODO: Implement names generation, someday.
                    if (!commentSplit.Contains("}"))
                    {
                        ignoreToggle = true;
                    }
                    continue;

                case "color":
                    currentCulture.Color =
                        LoadMethods.ParseColor32(commentSplit.Substring(equalsSplit.Length + 1));
                    continue;

                case "leader":
                case "unit":
                    continue;

                case "radicalism":
                    if (!float.TryParse(commentSplit.Substring(equalsSplit.Length + 1), out var radical))
                    {
                        throw new Exception("Unknown radicalism: " +
                                            commentSplit.Substring(equalsSplit.Length + 1));
                    }

                    currentCulture.Radicalism = radical;
                    continue;

                case "primary":
                    currentCulture.Primary =
                        LookupDictionaries.CountryTags[commentSplit.Substring(equalsSplit.Length + 1).Trim()];
                    continue;
                }

                if (!commentSplit.Contains("}"))
                {
                    continue;
                }

                if (cultureToggle)
                {
                    cultureToggle = false;
                    var targetCulture = em.CreateEntity(typeof(CultureEntity));
                    em.SetComponentData(targetCulture, currentCulture);

                    cultures.Add(currentCulture);
                    continue;
                }

                groupToggle = false;
            }

            File.WriteAllBytes(Path.Combine(Application.streamingAssetsPath, "JsonData", "cultures.txt"),
                               LoadMethods.Zip(JsonUtility.ToJson(
                                                   new CulturesOutput(cultureNames, cultureGroupNames, cultures))));

            FileUnpacker.GetCollector <CultureCollection>();

            return(cultureNames, cultureGroupNames);
        }
Ejemplo n.º 28
0
        public ProvinceHistoryLoad(string path, IReadOnlyList <string> provinceNames, IReadOnlyList <int> idIndex,
                                   IReadOnlyList <string> countryTags)
        {
            ProvinceCacheInfos = new ProvinceCacheInfo[provinceNames.Count];

            // var provinceLookup = new Dictionary<string, int>(provinceNames.Count);
            // for (var index = 0; index < provinceNames.Count; index++)
            //     provinceLookup[provinceNames[index]] = index;

            var idLookup = new Dictionary <int, int>(idIndex.Count);

            for (var index = 0; index < idIndex.Count; index++)
            {
                idLookup[idIndex[index]] = index;
            }

            var tagLookup = new Dictionary <string, int>(countryTags.Count);

            for (var index = 0; index < countryTags.Count; index++)
            {
                tagLookup[countryTags[index]] = index;
            }

            var nativeTag = tagLookup["nat"];
            var oceanTag  = tagLookup["ocean"];

            foreach (var filePath in Directory.EnumerateFiles(path, "*.txt"))
            {
                var fileMatch = Regex.Match(Path.GetFileNameWithoutExtension(filePath), @"(?<index>.*?)\-(?<name>.*)");
                var name      = fileMatch.Groups["name"].Value.Trim().ToLowerInvariant();
                var prevIndex = fileMatch.Groups["index"].Value.Trim();

                if (!int.TryParse(prevIndex, out var index))
                {
                    Debug.LogError($"Unknown index in file name: {filePath}");
                    continue;
                }

                if (!idLookup.TryGetValue(index, out index))
                {
                    Debug.LogError($"Unknown index lookup: {filePath}.");
                    continue;
                }

                var defineName = provinceNames[index];
                //if (!defineName.Equals(name, StringComparison.Ordinal))
                //    Debug.Log($"Definition name: {defineName} and file name: {name}. Mismatched.");

                var target = new ProvinceCacheInfo
                {
                    Cores = new List <int>(), FileName = name,
                    Name  = defineName, Index = index
                };
                var isCity = false;

                foreach (var rawLine in File.ReadLines(filePath, Encoding.GetEncoding(1252)))
                {
                    if (LoadMethods.CommentDetector(rawLine, out var sliced, false))
                    {
                        continue;
                    }

                    var variable = Regex.Match(sliced, @"^(?<key>.*?)\=(?<value>.*)");
                    // Very lazy check for nested declarations. Probably shouldn't rely on this.
                    var key = variable.Groups["key"].Value;
                    if (!variable.Success || key.IndexOfAny(new[] { '\t', ' ' }) == 0)
                    {
                        //Debug.Log($"Failed parsing: {sliced}");
                        continue;
                    }

                    key = key.Trim();

                    if (key.IndexOf('1') == 0)
                    {
                        break;
                    }

                    var value = variable.Groups["value"].Value.Trim();
                    switch (key)
                    {
                    case "add_core":
                        if (!tagLookup.TryGetValue(value, out var core))
                        {
                            Debug.Log($"Unknown country tag in cores: {value}.");
                        }

                        target.Cores.Add(core);
                        break;

                    case "owner":
                        if (!tagLookup.TryGetValue(value, out target.Owner))
                        {
                            Debug.Log($"Unknown country tag in owner: {value}.");
                        }
                        break;

                    case "controller":
                        if (!tagLookup.TryGetValue(value, out target.Controller))
                        {
                            Debug.Log($"Unknown country tag in controller: {value}.");
                        }
                        break;

                    case "religion":
                        target.Religion = value;
                        break;

                    case "culture":
                        target.Culture = value;
                        break;

                    case "base_tax":
                        target.Tax = int.Parse(value);
                        break;

                    case "base_production":
                        target.Production = int.Parse(value);
                        break;

                    case "base_manpower":
                        target.Manpower = int.Parse(value);
                        break;

                    case "capital":
                        target.Capital = value.Replace("\"", "");
                        break;

                    case "is_city":
                        isCity = LoadMethods.YesNoConverter(value);
                        break;

                    case "trade_goods":
                        target.Goods = value;
                        break;
                    }
                }

                if (!isCity)
                {
                    if (target.Tax == 0 &&
                        string.IsNullOrWhiteSpace(target.Capital) &&
                        string.IsNullOrWhiteSpace(target.Goods))
                    {
                        // Ocean, splash splash.
                        target.Owner      = oceanTag;
                        target.Controller = oceanTag;
                    }
                    else
                    {
                        // Native land, un colonized
                        target.Owner      = nativeTag;
                        target.Controller = nativeTag;
                    }
                }

                ProvinceCacheInfos[index] = target;
            }

            for (var i = 0; i < ProvinceCacheInfos.Length; i++)
            {
                if (ProvinceCacheInfos[i].FileName != null)
                {
                    continue;
                }

                var name = provinceNames[i];
                Debug.Log("Orphaned id index: " + idIndex[i] + " of name: " + name + " of index: " + i);
                ProvinceCacheInfos[i] = new ProvinceCacheInfo
                {
                    FileName = name,
                    Name     = name,
                    Index    = i
                };
            }
        }
Ejemplo n.º 29
0
        public static (Entity, Entity, List <string>, List <string>) Main()
        {
            var goods             = new NativeList <EntityWrapper>(Allocator.Temp);
            var goodsCategory     = new NativeList <EntityWrapper>(Allocator.Temp);
            var goodNames         = new List <string>();
            var goodCategoryNames = new List <string>();

            var fileTree = new List <KeyValuePair <int, object> >();
            var values   = new List <string>();

            var em = World.Active.EntityManager;
            var currentCategory = new Entity();

            FileUnpacker.ParseFile(Path.Combine(Application.streamingAssetsPath, "Common", "goods.txt"), fileTree,
                                   values, GoodsMagicOverride);

            foreach (var category in fileTree)
            {
                foreach (var goodKvp in (List <KeyValuePair <int, object> >)category.Value)
                {
                    var currentEntity = goods[goodKvp.Key - (int)MagicUnifiedNumbers.Goods];
                    var currentGood   = em.GetComponentData <GoodsEntity>(currentEntity);

                    foreach (var goodProperty in (List <KeyValuePair <int, object> >)goodKvp.Value)
                    {
                        var targetStr = values[(int)goodProperty.Value];
                        switch ((LoadVariables)goodProperty.Key)
                        {
                        case LoadVariables.Cost:
                            float.TryParse(targetStr, out var cost);
                            currentGood.Cost = cost;
                            break;

                        case LoadVariables.Color:
                            currentGood.Color = LoadMethods.ParseColor32(targetStr);
                            break;

                        case LoadVariables.AvailableFromStart:
                            currentGood.Availability = LoadMethods.YesNoConverter(targetStr);
                            break;

                        case LoadVariables.OverseasPenalty:
                            currentGood.OverseasPenalty = LoadMethods.YesNoConverter(targetStr);
                            break;

                        case LoadVariables.Money:
                            currentGood.Money = LoadMethods.YesNoConverter(targetStr);
                            break;

                        case LoadVariables.Tradeable:
                            currentGood.Tradable = LoadMethods.YesNoConverter(targetStr);
                            break;
                        }
                    }

                    em.SetComponentData(currentEntity, currentGood);
                }
            }

            var goodCollectorEntity = FileUnpacker.GetCollector <GoodsCollection>(goods);

            goods.Dispose();

            var categoryCollectorEntity = FileUnpacker.GetCollector <GoodsCategoryCollection>(goodsCategory);

            goodsCategory.Dispose();

            return(goodCollectorEntity, categoryCollectorEntity, goodNames, goodCategoryNames);

            int GoodsMagicOverride(int parent, string target)
            {
                switch (parent)
                {
                case -1:
                    var targetCategory = em.CreateEntity(typeof(GoodsCategoryEntity));
                    em.SetComponentData(targetCategory, new GoodsCategoryEntity {
                        Index = goodCategoryNames.Count
                    });
                    goodsCategory.Add(targetCategory);
                    currentCategory = targetCategory;
                    goodCategoryNames.Add(target);
                    return((int)MagicUnifiedNumbers.Placeholder);

                case (int)MagicUnifiedNumbers.Placeholder:
                    var targetGood = em.CreateEntity(typeof(GoodsEntity));
                    em.SetComponentData(targetGood,
                                        new GoodsEntity {
                        Index = goodNames.Count, Category = currentCategory
                    });
                    goods.Add(targetGood);
                    goodNames.Add(target);
                    return((int)MagicUnifiedNumbers.Goods + goodNames.Count - 1);

                default:
                    return((int)MagicUnifiedNumbers.ContinueMagicNumbers);
                }
            }
        }
Ejemplo n.º 30
0
 public HasAndBelongsToMany(LoadMethods loadMethod)
 {
     LoadMethod = loadMethod;
 }