コード例 #1
0
ファイル: Manifest.cs プロジェクト: hadow/Commander
 public ModelSequenceFormat(MiniYaml yaml)
 {
     Type     = yaml.Value;
     Metadata = new ReadOnlyDictionary <string, MiniYaml>(yaml.ToDictionary());
 }
コード例 #2
0
ファイル: Map.cs プロジェクト: hadow/Commander
        public Map(ModData modData, IReadOnlyPackage package)
        {
            this.modData = modData;
            Package      = package;

            if (!Package.Contains("map.yaml") || !Package.Contains("map.bin"))
            {
                throw new InvalidDataException("Not a valid map\n File:{0}".F(package.Name));
            }

            var yaml = new MiniYaml(null, MiniYaml.FromStream(Package.GetStream("map.yaml"), package.Name));

            foreach (var field in YamlFields)
            {
                field.Deserialize(this, yaml.Nodes);
            }

            if (MapFormat != SupportedMapFormat)
            {
                throw new InvalidDataException("Map format {0} is not supported. \n File:{1}".F(MapFormat, package.Name));
            }
            PlayerDefinitions = MiniYaml.NodesOrEmpty(yaml, "Players");
            ActorDefinitions  = MiniYaml.NodesOrEmpty(yaml, "Actors");

            Grid = modData.Manifest.Get <MapGrid>();

            var size = new Size((int)MapSize.X, (int)MapSize.Y);

            //Layer
            Tiles     = new CellLayer <TerrainTile>(Grid.Type, size);
            Resources = new CellLayer <ResourceTile>(Grid.Type, size);
            Height    = new CellLayer <byte>(Grid.Type, size);


            using (var s = Package.GetStream("map.bin"))
            {
                var header = new BinaryDataHeader(s, MapSize);

                if (header.TilesOffset > 0)
                {
                    s.Position = header.TilesOffset;
                    for (var i = 0; i < MapSize.X; i++)
                    {
                        for (var j = 0; j < MapSize.Y; j++)
                        {
                            var tile  = s.ReadUInt16();
                            var index = s.ReadUInt8();
                            if (index == byte.MaxValue)
                            {
                                index = (byte)(i % 4 + (j % 4) * 4);
                            }

                            Tiles[new MPos(i, j)] = new TerrainTile(tile, index);
                        }
                    }
                }

                if (header.ResourcesOffset > 0)
                {
                    s.Position = header.ResourcesOffset;
                    for (var i = 0; i < MapSize.X; i++)
                    {
                        for (var j = 0; j < MapSize.Y; j++)
                        {
                            var type    = s.ReadUInt8();
                            var density = s.ReadUInt8();
                            Resources[new MPos(i, j)] = new ResourceTile(type, density);
                        }
                    }
                }

                if (header.HeightsOffset > 0)
                {
                    s.Position = header.HeightsOffset;
                    for (var i = 0; i < MapSize.X; i++)
                    {
                        for (var j = 0; j < MapSize.Y; j++)
                        {
                            Height[new MPos(i, j)] = s.ReadUInt8().Clamp((byte)0, Grid.MaximumTerrainHeight);
                        }
                    }
                }
            }

            if (Grid.MaximumTerrainHeight > 0)
            {
                Tiles.CellEntryChanged  += UpdateProjection;
                Height.CellEntryChanged += UpdateProjection;
            }

            PostInit();

            Uid = ComputeUID(Package);
        }
コード例 #3
0
ファイル: Ruleset.cs プロジェクト: hadow/Commander
 static bool AnyCustomYaml(MiniYaml yaml)
 {
     return(yaml != null && (yaml.Value != null || yaml.Nodes.Any()));
 }
コード例 #4
0
ファイル: Manifest.cs プロジェクト: hadow/Commander
        public Manifest(string modId, IReadOnlyPackage package)
        {
            Id      = modId;
            Package = package;

            yaml = new MiniYaml(null, MiniYaml.FromStream(Package.GetStream("mod.yaml"), "mod.yaml")).ToDictionary();

            Metadata = FieldLoader.Load <ModMetadata>(yaml["Metadata"]);

            MapFolders = YamlDictionary(yaml, "MapFolders");

            MiniYaml packages;

            if (yaml.TryGetValue("Packages", out packages))
            {
                Packages = packages.ToDictionary(x => x.Value).AsReadOnly();
            }
            Rules          = YamlList(yaml, "Rules");
            Sequences      = YamlList(yaml, "Sequences");
            ModelSequences = YamlList(yaml, "ModelSequences");
            Assemblies     = YamlList(yaml, "Assemblies");
            Weapons        = YamlList(yaml, "Weapons");
            Voices         = YamlList(yaml, "Voices");
            Notifications  = YamlList(yaml, "Notifications");
            Music          = YamlList(yaml, "Music");
            TileSets       = YamlList(yaml, "TileSets");
            Missions       = YamlList(yaml, "Missions");
            ServerTraits   = YamlList(yaml, "ServerTraits");
            Chrome         = YamlList(yaml, "Chrome");
            ChromeLayout   = YamlList(yaml, "ChromeLayout");
            ChromeMetrics  = YamlList(yaml, "ChromeMetrics");
            Fonts          = yaml["Fonts"].ToDictionary(my =>
            {
                var nd = my.ToDictionary();
                return(Pair.New(nd["Font"].Value, Exts.ParseIntegerInvariant(nd["Size"].Value)));
            });
            if (!yaml.TryGetValue("LoadScreen", out LoadScreen))
            {
                throw new InvalidDataException("'LoadScreen' section is not defined.");
            }

            var compat = new List <string> {
                Id
            };

            if (yaml.ContainsKey("SupportsMapsFrom"))
            {
                compat.AddRange(yaml["SupportsMapsFrom"].Value.Split(',').Select(c => c.Trim()));
            }

            MapCompatibility = compat.ToArray();

            if (yaml.ContainsKey("SpriteFormats"))
            {
                SpriteFormats = FieldLoader.GetValue <string[]>("SpriteFormats", yaml["SpriteFormats"].Value);
            }

            if (yaml.ContainsKey("PackageFormats"))
            {
                PackageFormats = FieldLoader.GetValue <string[]>("PackageFormats", yaml["PackageFormats"].Value);
            }

            if (yaml.ContainsKey("SoundFormats"))
            {
                SoundFormats = FieldLoader.GetValue <string[]>("SoundFormats", yaml["SoundFormats"].Value);
            }
        }
コード例 #5
0
ファイル: Ruleset.cs プロジェクト: hadow/Commander
        /// <summary>
        /// 合并Yaml文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <param name="fileSystem"></param>
        /// <param name="files"></param>
        /// <param name="additional"></param>
        /// <param name="defaults"></param>
        /// <param name="makeObject"></param>
        /// <returns></returns>
        static IReadOnlyDictionary <string, T> MergeOrDefault <T>(string name, IReadOnlyFileSystem fileSystem, IEnumerable <string> files, MiniYaml additional,
                                                                  IReadOnlyDictionary <string, T> defaults, Func <MiniYamlNode, T> makeObject)
        {
            if (additional == null && defaults != null)
            {
                return(defaults);
            }

            var result = MiniYaml.Load(fileSystem, files, additional)
                         .ToDictionaryWithConflictLog(k => k.Key.ToLowerInvariant(), makeObject, "LoadFromManifest<" + name + ">");

            return(new ReadOnlyDictionary <string, T>(result));
        }
コード例 #6
0
ファイル: Ruleset.cs プロジェクト: hadow/Commander
        public static bool DefinesUnsafeCustomRules(ModData modData, IReadOnlyFileSystem fileSystem, MiniYaml mapRules, MiniYaml mapWeapons, MiniYaml mapVoices, MiniYaml mapNotifications, MiniYaml mapSequences)
        {
            if (AnyCustomYaml(mapWeapons) || AnyCustomYaml(mapVoices) || AnyCustomYaml(mapNotifications) || AnyCustomYaml(mapSequences))
            {
                return(true);
            }

            if (mapRules != null)
            {
                if (AnyFlaggedTraits(modData, mapRules.Nodes))
                {
                    return(true);
                }

                if (mapRules.Value != null)
                {
                    var mapFiles = FieldLoader.GetValue <string[]>("value", mapRules.Value);
                    foreach (var f in mapFiles)
                    {
                        if (AnyFlaggedTraits(modData, MiniYaml.FromStream(fileSystem.Open(f), f)))
                        {
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
コード例 #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="fieldType"></param>
        /// <param name="yaml"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public static object GetValue(string fieldName, Type fieldType, MiniYaml yaml, MemberInfo field)
        {
            var value = yaml.Value;

            if (value != null)
            {
                value = value.Trim();
            }

            if (fieldType == typeof(int))
            {
                int res;
                if (Exts.TryParseIntegerInvariant(value, out res))
                {
                    return(res);
                }
                return(InvalidValueAction(value, fieldType, fieldName));
            }
            else if (fieldType == typeof(ushort))
            {
                ushort res;
                if (ushort.TryParse(value, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out res))
                {
                    return(res);
                }
                return(InvalidValueAction(value, fieldType, fieldName));
            }
            else if (fieldType == typeof(long))
            {
                long res;
                if (long.TryParse(value, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out res))
                {
                    return(res);
                }
                return(InvalidValueAction(value, fieldType, fieldName));
            }
            else if (fieldType == typeof(float))
            {
                float res;
                if (value != null && float.TryParse(value.Replace("%", ""), NumberStyles.Float, NumberFormatInfo.InvariantInfo, out res))
                {
                    return(res * (value.Contains('%') ? 0.01f : 1f));
                }
                return(InvalidValueAction(value, fieldType, fieldName));
            }
            else if (fieldType == typeof(decimal))
            {
                decimal res;
                if (value != null && decimal.TryParse(value.Replace("%", ""), NumberStyles.Float, NumberFormatInfo.InvariantInfo, out res))
                {
                    return(res * (value.Contains('%') ? 0.01m : 1m));
                }
                return(InvalidValueAction(value, fieldType, fieldName));
            }
            else if (fieldType == typeof(string))
            {
                if (field != null && MemberHasTranslateAttribute[field] && value != null)
                {
                }
                return(value);
            }
            else if (fieldType == typeof(WRot))
            {
                if (value != null)
                {
                    var parts = value.Split(',');
                    if (parts.Length == 3)
                    {
                        int rr, rp, ry;
                        if (Exts.TryParseIntegerInvariant(parts[0], out rr) &&
                            Exts.TryParseIntegerInvariant(parts[1], out rp) &&
                            Exts.TryParseIntegerInvariant(parts[2], out ry))
                        {
                            return(new WRot(new WAngle(rr), new WAngle(rp), new WAngle(ry)));
                        }
                    }
                }

                return(InvalidValueAction(value, fieldType, fieldName));
            }
            else if (fieldType == typeof(WAngle))
            {
                int res;
                if (Exts.TryParseIntegerInvariant(value, out res))
                {
                    return(new WAngle(res));
                }
                return(InvalidValueAction(value, fieldType, fieldName));
            }
            else if (fieldType == typeof(WVec))
            {
                if (value != null)
                {
                    var parts = value.Split(',');
                    if (parts.Length == 3)
                    {
                        WDist rx, ry, rz;
                        if (WDist.TryParse(parts[0], out rx) && WDist.TryParse(parts[1], out ry) && WDist.TryParse(parts[2], out rz))
                        {
                            return(new WVec(rx, ry, rz));
                        }
                    }
                }
            }
            else if (fieldType == typeof(WVec[]))
            {
                if (value != null)
                {
                    var parts = value.Split(',');
                    if (parts.Length % 3 != 0)
                    {
                        return(InvalidValueAction(value, fieldType, fieldName));
                    }

                    var vecs = new WVec[parts.Length / 3];
                    for (var i = 0; i < vecs.Length; i++)
                    {
                        WDist rx, ry, rz;
                        if (WDist.TryParse(parts[3 * i], out rx) && WDist.TryParse(parts[3 * i + 1], out ry) && WDist.TryParse(parts[3 * i + 2], out rz))
                        {
                            vecs[i] = new WVec(rx, ry, rz);
                        }
                    }
                    return(vecs);
                }

                return(InvalidValueAction(value, fieldType, fieldName));
            }
            else if (fieldType == typeof(WDist))
            {
                WDist res;
                if (WDist.TryParse(value, out res))
                {
                    return(res);
                }
                return(InvalidValueAction(value, fieldType, fieldName));
            }
            else if (fieldType == typeof(WPos))
            {
                if (value != null)
                {
                    var parts = value.Split(',');
                    if (parts.Length == 3)
                    {
                        WDist rx, ry, rz;
                        if (WDist.TryParse(parts[0], out rx) && WDist.TryParse(parts[1], out ry) && WDist.TryParse(parts[2], out rz))
                        {
                            return(new WPos(rx, ry, rz));
                        }
                    }
                }
                return(InvalidValueAction(value, fieldType, fieldName));
            }
            else if (fieldType == typeof(CPos))
            {
                if (value != null)
                {
                    var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    return(new CPos(Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1])));
                }
                return(InvalidValueAction(value, fieldType, fieldName));
            }
            else if (fieldType == typeof(CVec))
            {
                if (value != null)
                {
                    var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    return(new CVec(Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1])));
                }
            }
            else if (fieldType == typeof(CVec[]))
            {
                if (value != null)
                {
                    var parts = value.Split(',');

                    if (parts.Length % 2 != 0)
                    {
                        return(InvalidValueAction(value, fieldType, fieldName));
                    }

                    var vecs = new CVec[parts.Length / 2];

                    for (var i = 0; i < vecs.Length; i++)
                    {
                        int rx, ry;
                        if (int.TryParse(parts[2 * i], out rx) && int.TryParse(parts[2 * i + 1], out ry))
                        {
                            vecs[i] = new CVec(rx, ry);
                        }
                    }
                    return(vecs);
                }

                return(InvalidValueAction(value, fieldType, fieldName));
            }
            else if (fieldType == typeof(Int2))
            {
                if (value != null)
                {
                    var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    return(new Int2(Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1])));
                }

                return(InvalidValueAction(value, fieldType, fieldName));
            }
            else if (fieldType.IsEnum)
            {
                try
                {
                    return(Enum.Parse(fieldType, value, true));
                }
                catch (ArgumentException)
                {
                    return(InvalidValueAction(value, fieldType, fieldName));
                }
            }
            else if (fieldType == typeof(Size))
            {
                if (value != null)
                {
                    var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    return(new Size(Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1])));
                }
            }
            else if (fieldType.IsArray && fieldType.GetArrayRank() == 1) //获取Rank属性,例如,一维数组返回1,二维数组返回2
            {
                if (value == null)
                {
                    return(Array.CreateInstance(fieldType.GetElementType(), 0));
                }
                var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                var ret = Array.CreateInstance(fieldType.GetElementType(), parts.Length);
                for (var i = 0; i < parts.Length; i++)
                {
                    ret.SetValue(GetValue(fieldName, fieldType.GetElementType(), parts[i].Trim(), field), i);
                }
                return(ret);
            }
            else if (fieldType == typeof(Rectangle))
            {
                if (value != null)
                {
                    var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    return(new Rectangle(
                               Exts.ParseIntegerInvariant(parts[0]),
                               Exts.ParseIntegerInvariant(parts[1]),
                               Exts.ParseIntegerInvariant(parts[2]),
                               Exts.ParseIntegerInvariant(parts[3])));
                }
                return(InvalidValueAction(value, fieldType, fieldName));
            }
            else if (fieldType == typeof(EW.Framework.Point))
            {
                if (value != null)
                {
                    var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    return(new EW.Framework.Point(Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1])));
                }
            }
            else if (fieldType == typeof(bool))
            {
                return(ParseYesNo(value, fieldType, fieldName));
            }
            else if (fieldType == typeof(Vector2))
            {
                if (value != null)
                {
                    var   parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    float xx    = 0;
                    float yy    = 0;
                    float res;
                    if (float.TryParse(parts[0].Replace("%", ""), NumberStyles.Float, NumberFormatInfo.InvariantInfo, out res))
                    {
                        xx = res * (parts[0].Contains('%') ? 0.01f : 1f);
                    }
                    if (float.TryParse(parts[1].Replace("%", ""), NumberStyles.Float, NumberFormatInfo.InvariantInfo, out res))
                    {
                        yy = res * (parts[1].Contains('%') ? 0.01f : 1f);
                    }
                    return(new Vector2(xx, yy));
                }
            }
            else if (fieldType == typeof(Vector3))
            {
                if (value != null)
                {
                    var   parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    float x, y, z = 0;
                    float.TryParse(parts[0], NumberStyles.Float, NumberFormatInfo.InvariantInfo, out x);
                    float.TryParse(parts[1], NumberStyles.Float, NumberFormatInfo.InvariantInfo, out y);

                    if (parts.Length > 2)
                    {
                        float.TryParse(parts[2], NumberStyles.Float, NumberFormatInfo.InvariantInfo, out z);
                    }

                    return(new Vector3(x, y, z));
                }
            }
            else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(HashSet <>))
            {
                var set = Activator.CreateInstance(fieldType);
                if (value == null)
                {
                    return(set);
                }

                var parts     = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var addMethod = fieldType.GetMethod("Add", fieldType.GetGenericArguments());
                for (var i = 0; i < parts.Length; i++)
                {
                    addMethod.Invoke(set, new[] { GetValue(fieldName, fieldType.GetGenericArguments()[0], parts[i].Trim(), field) });
                }
                return(set);
            }
            else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Dictionary <,>))
            {
                var dict      = Activator.CreateInstance(fieldType);
                var arguments = fieldType.GetGenericArguments();
                var addMethod = fieldType.GetMethod("Add", arguments);
                foreach (var node in yaml.Nodes)
                {
                    var key = GetValue(fieldName, arguments[0], node.Key, field);
                    var val = GetValue(fieldName, arguments[1], node.Value, field);
                    addMethod.Invoke(dict, new[] { key, val });
                }
                return(dict);
            }
            else if (fieldType == typeof(System.Drawing.Color))
            {
                System.Drawing.Color color;
                if (value != null && HSLColor.TryParseRGB(value, out color))
                {
                    return(color);
                }

                return(InvalidValueAction(value, fieldType, fieldName));
            }
            else if (fieldType == typeof(System.Drawing.Color[]))
            {
                if (value != null)
                {
                    var parts  = value.Split(',');
                    var colors = new System.Drawing.Color[parts.Length];

                    for (var i = 0; i < parts.Length; i++)
                    {
                        if (!HSLColor.TryParseRGB(parts[i], out colors[i]))
                        {
                            return(InvalidValueAction(value, fieldType, fieldName));
                        }
                    }
                    return(colors);
                }
            }
            else if (fieldType == typeof(HSLColor))
            {
                if (value != null)
                {
                    System.Drawing.Color rgb;
                    if (HSLColor.TryParseRGB(value, out rgb))
                    {
                        return(new HSLColor(rgb));
                    }

                    //Allowed old HSLColor / ColorRamp formats to be parsed as HSLColor
                    var parts = value.Split(',');
                    if (parts.Length == 3 || parts.Length == 4)
                    {
                        return(new HSLColor((byte)Exts.ParseIntegerInvariant(parts[0]).Clamp(0, 255),
                                            (byte)Exts.ParseIntegerInvariant(parts[1]).Clamp(0, 255),
                                            (byte)Exts.ParseIntegerInvariant(parts[2]).Clamp(0, 255)));
                    }
                }

                return(InvalidValueAction(value, fieldType, fieldName));
            }
            else if (fieldType == typeof(BooleanExpression))
            {
                if (value != null)
                {
                    try
                    {
                        return(new BooleanExpression(value));
                    }
                    catch (InvalidDataException e)
                    {
                        throw new YamlException(e.Message);
                    }
                }
                return(InvalidValueAction(value, fieldType, fieldName));
            }
            else
            {
                var conv = TypeDescriptor.GetConverter(fieldType);
                if (conv.CanConvertFrom(typeof(string)))
                {
                    try
                    {
                        return(conv.ConvertFromInvariantString(value));
                    }
                    catch
                    {
                        return(InvalidValueAction(value, fieldType, fieldName));
                    }
                }
            }

            UnknownFieldAction("[Type]{0}".F(value), fieldType);
            return(null);
        }
コード例 #8
0
ファイル: Ruleset.cs プロジェクト: hadow/Commander
        /// <summary>
        ///
        /// </summary>
        /// <param name="modData"></param>
        /// <param name="fileSystem"></param>
        /// <param name="tileSet"></param>
        /// <param name="mapRules"></param>
        /// <param name="mapWeapons"></param>
        /// <param name="mapVoices"></param>
        /// <param name="mapNotifications"></param>
        /// <param name="mapMusic"></param>
        /// <param name="mapSequences"></param>
        /// <returns></returns>
        public static Ruleset Load(ModData modData, IReadOnlyFileSystem fileSystem, string tileSet,
                                   MiniYaml mapRules, MiniYaml mapWeapons, MiniYaml mapVoices, MiniYaml mapNotifications, MiniYaml mapMusic, MiniYaml mapSequences, MiniYaml mapModelSequences)
        {
            var m  = modData.Manifest;
            var dr = modData.DefaultRules;

            Ruleset ruleset = null;

            Action f = () =>
            {
                var actors = MergeOrDefault("Rules", fileSystem, m.Rules, mapRules, dr.Actors, k => new ActorInfo(modData.ObjectCreator, k.Key.ToLowerInvariant(), k.Value));

                var weapons = MergeOrDefault("Weapons", fileSystem, m.Weapons, mapWeapons, dr.Weapons, k => new WeaponInfo(k.Key.ToLowerInvariant(), k.Value));

                var voices = MergeOrDefault("Voices", fileSystem, m.Voices, mapVoices, dr.Voices, k => new SoundInfo(k.Value));

                var notifications = MergeOrDefault("Notifications", fileSystem, m.Notifications, mapNotifications, dr.Notifications, k => new SoundInfo(k.Value));

                var music = MergeOrDefault("Music", fileSystem, m.Music, mapMusic, dr.Music, k => new MusicInfo(k.Key, k.Value));

                var ts = modData.DefaultTileSets[tileSet];

                var sequences = mapSequences == null ? modData.DefaultSequences[tileSet] : new SequenceProvider(fileSystem, modData, ts, mapSequences);

                var modelSequences = dr.ModelSequences;
                if (mapModelSequences != null)
                {
                    modelSequences = MergeOrDefault("ModelSequences", fileSystem, m.ModelSequences, mapModelSequences, dr.ModelSequences, k => k);
                }

                ruleset = new Ruleset(actors, weapons, voices, notifications, music, ts, sequences, modelSequences);
            };

            if (modData.IsOnMainThread)
            {
                modData.HandleLoadingProgress();

                var loader = new Task(f);
                loader.Start();

                //Animate the loadscreen while we wait
                while (!loader.Wait(40))
                {
                    modData.HandleLoadingProgress();
                }
            }
            else
            {
                f();
            }

            return(ruleset);
        }
コード例 #9
0
ファイル: MapPreview.cs プロジェクト: hadow/Commander
        /// <summary>
        ///
        /// </summary>
        /// <param name="p"></param>
        /// <param name="parent"></param>
        /// <param name="classification"></param>
        /// <param name="mapCompatibility"></param>
        /// <param name="gridT"></param>
        public void UpdateFromMap(IReadOnlyPackage p, IReadOnlyPackage parent, MapClassification classification, string[] mapCompatibility, MapGridT gridT)
        {
            Dictionary <string, MiniYaml> yaml;

            using (var yamlStream = p.GetStream("map.yaml"))
            {
                if (yamlStream == null)
                {
                    throw new FileNotFoundException("Required file map.yaml not present in this map");
                }

                yaml = new MiniYaml(null, MiniYaml.FromStream(yamlStream, "map.yaml")).ToDictionary();
            }

            Package       = p;
            parentPackage = parent;


            var newData = innerData.Clone();

            newData.GridT = gridT;
            newData.Class = classification;

            MiniYaml temp;

            if (yaml.TryGetValue("MapFormat", out temp))
            {
                var format = FieldLoader.GetValue <int>("MapFormat", temp.Value);
                if (format != Map.SupportedMapFormat)
                {
                    throw new InvalidOperationException("Map format {0} is not supported.".F(format));
                }
            }
            if (yaml.TryGetValue("Title", out temp))
            {
                newData.Title = temp.Value;
            }
            if (yaml.TryGetValue("Categories", out temp))
            {
                newData.Categories = FieldLoader.GetValue <string[]>("Categories", temp.Value);
            }
            if (yaml.TryGetValue("Tileset", out temp))
            {
                newData.TileSet = temp.Value;
            }

            if (yaml.TryGetValue("Author", out temp))
            {
                newData.Author = temp.Value;
            }
            if (yaml.TryGetValue("Bounds", out temp))
            {
                newData.Bounds = FieldLoader.GetValue <Rectangle>("Bounds", temp.Value);
            }

            if (yaml.TryGetValue("Visibility", out temp))
            {
                newData.Visibility = FieldLoader.GetValue <MapVisibility>("Visibility", temp.Value);
            }

            string requiresMod = string.Empty;

            if (yaml.TryGetValue("RequiresMod", out temp))
            {
                requiresMod = temp.Value;
            }

            newData.Status = mapCompatibility == null || mapCompatibility.Contains(requiresMod) ? MapStatus.Available : MapStatus.Unavailable;

            try
            {
                MiniYaml actorDefinitions;
                if (yaml.TryGetValue("Actors", out actorDefinitions))
                {
                    var spawns = new List <CPos>();
                    foreach (var kv in actorDefinitions.Nodes.Where(d => d.Value.Value == "mpspawn"))
                    {
                        var s = new ActorReference(kv.Value.Value, kv.Value.ToDictionary());
                        spawns.Add(s.InitDict.Get <LocationInit>().Value(null));
                    }
                    newData.SpawnPoints = spawns.ToArray();
                }
                else
                {
                    newData.SpawnPoints = new CPos[0];
                }
            }
            catch (Exception)
            {
                newData.SpawnPoints = new CPos[0];
                newData.Status      = MapStatus.Unavailable;
            }


            try
            {
                //Player definitions may change if the map format changes
                MiniYaml playerDefinitions;
                if (yaml.TryGetValue("Players", out playerDefinitions))
                {
                    newData.Players     = new MapPlayers(playerDefinitions.Nodes);
                    newData.PlayerCount = newData.Players.Players.Count(x => x.Value.Playable);
                }
            }
            catch (Exception)
            {
                newData.Status = MapStatus.Unavailable;
            }

            newData.SetRulesetGenerator(modData, () => {
                var ruleDefinitions          = LoadRuleSection(yaml, "Rules");
                var weaponDefinitions        = LoadRuleSection(yaml, "Weapons");
                var voiceDefinitions         = LoadRuleSection(yaml, "Voices");
                var musicDefinitions         = LoadRuleSection(yaml, "Music");
                var notificationDefinitions  = LoadRuleSection(yaml, "Notifications");
                var sequenceDefinitions      = LoadRuleSection(yaml, "Sequences");
                var modelSequenceDefinitions = LoadRuleSection(yaml, "ModelSequences");

                var rules = Ruleset.Load(modData, this, TileSet, ruleDefinitions, weaponDefinitions, voiceDefinitions, notificationDefinitions, musicDefinitions, sequenceDefinitions, modelSequenceDefinitions);

                var flagged = Ruleset.DefinesUnsafeCustomRules(modData, this, ruleDefinitions, weaponDefinitions, voiceDefinitions, notificationDefinitions, sequenceDefinitions);
                return(Pair.New(rules, flagged));
            });

            if (Package.Contains("map.png"))
            {
                using (var dataStream = p.GetStream("map.png"))
                    newData.Preview = BitmapFactory.DecodeStream(dataStream, null,
                                                                 new BitmapFactory.Options
                    {
                        InScaled           = false,
                        InDither           = false,
                        InJustDecodeBounds = false,
                        InPurgeable        = true,
                        InInputShareable   = true,
                    });
            }

            innerData = newData;
        }
コード例 #10
0
ファイル: PlayerReference.cs プロジェクト: hadow/Commander
 public PlayerReference(MiniYaml my)
 {
     FieldLoader.Load(this, my);
 }
コード例 #11
0
ファイル: TileSet.cs プロジェクト: hadow/Commander
 public TerrainTypeInfo(MiniYaml my)
 {
     FieldLoader.Load(this, my);
 }
コード例 #12
0
 public MiniYamlNode(string k, MiniYaml v, SourceLocation loc) : this(k, v)
 {
     Location = loc;
 }
コード例 #13
0
 public MiniYamlNode(string k, MiniYaml v)
 {
     Key   = k;
     Value = v;
 }
コード例 #14
0
        public static List <MiniYamlNode> NodesOrEmpty(MiniYaml y, string s)
        {
            var nd = y.ToDictionary();

            return(nd.ContainsKey(s) ? nd[s].Nodes : new List <MiniYamlNode>());
        }
コード例 #15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileSystem"></param>
        /// <param name="files"></param>
        /// <param name="mapRules"></param>
        /// <returns></returns>
        public static List <MiniYamlNode> Load(IReadOnlyFileSystem fileSystem, IEnumerable <string> files, MiniYaml mapRules)
        {
            if (mapRules != null && mapRules.Value != null)
            {
                var mapFiles = FieldLoader.GetValue <string[]>("value", mapRules.Value);
                files = files.Append(mapFiles);
            }

            var yaml = files.Select(s => MiniYaml.FromStream(fileSystem.Open(s), s));

            if (mapRules != null && mapRules.Nodes.Any())
            {
                yaml = yaml.Append(mapRules.Nodes);
            }

            return(Merge(yaml));
        }