Represents a type of map generator. Provides general information about this generator, and ways to create IMapGeneratorParameters objects.
Esempio n. 1
0
        public Map LoadMap()
        {
            var tempMap = Map;

            if (tempMap != null)
            {
                return(tempMap);
            }

            lock ( SyncRoot ) {
                if (Map != null)
                {
                    return(Map);
                }

                if (File.Exists(MapFileName))
                {
                    try {
                        Map = MapUtility.Load(MapFileName);
                    } catch (Exception ex) {
                        Logger.Log(LogType.Error,
                                   "World.LoadMap: Failed to load map ({0}): {1}",
                                   MapFileName, ex);
                    }
                }

                // or generate a default one
                if (Map == null)
                {
                    Server.Message("&WMapfile is missing for world {0}&W. A new map has been created.", ClassyName);
                    Logger.Log(LogType.SystemActivity,
                               "World.LoadMap: Map file missing for world {0}. Generating default flatgrass map.",
                               Name);
                    Map = MapGenerator.GenerateFlatgrass(128, 128, 64);
                }

                return(Map);
            }
        }
Esempio n. 2
0
        public static void Start(Player player)
        {
            Map map = MapGenerator.GenerateEmpty(64, 128, 16);

            map.Save("maps/minefield.fcm");
            if (_world != null)
            {
                WorldManager.RemoveWorld(_world);
            }
            WorldManager.AddWorld(Player.Console, "Minefield", map, true);
            _map   = map;
            _world = WorldManager.FindWorldExact("Minefield");
            SetUpRed();
            SetUpMiddleWater();
            SetUpGreen();
            SetUpMines();
            _map.Spawn = new Position(_map.Width / 2, 5, _ground + 3).ToVector3I().ToPlayerCoords();
            _world.LoadMap();
            _world.gameMode = GameMode.MineField;
            _world.EnableTNTPhysics(Player.Console, false);
            Server.Message("{0}&S started a game of MineField on world Minefield!", player.ClassyName);
            WorldManager.SaveWorldList();
            Server.RequestGC();
        }
Esempio n. 3
0
        public void LoadMap()
        {
            lock ( WorldLock ) {
                if (Map != null)
                {
                    return;
                }

                try {
                    Map = MapUtility.Load(GetMapName());
                } catch (Exception ex) {
                    Logger.Log("World.LoadMap: Failed to load map ({0}): {1}", LogType.Error,
                               GetMapName(), ex);
                }

                // or generate a default one
                if (Map != null)
                {
                    Map.World = this;
                }
                else
                {
                    Logger.Log("World.LoadMap: Generating default flatgrass level.", LogType.SystemActivity);
                    Map = new Map(this, 64, 64, 64, true);

                    MapGenerator.GenerateFlatgrass(Map);
                    Map.ResetSpawn();
                }
                StartTasks();

                if (OnLoaded != null)
                {
                    OnLoaded();
                }
            }
        }
Esempio n. 4
0
        internal static bool LoadWorldList()
        {
            World newMainWorld = null;

            Worlds = new World[0];
            if (File.Exists(Paths.WorldListFileName))
            {
                try {
                    XDocument doc  = XDocument.Load(Paths.WorldListFileName);
                    XElement  root = doc.Root;
                    if (root != null)
                    {
                        foreach (XElement el in root.Elements("World"))
                        {
#if !DEBUG
                            try {
#endif
                            LoadWorldListEntry(el);
#if !DEBUG
                        }
                        catch (Exception ex) {
                            Logger.LogAndReportCrash("An error occured while trying to parse one of the entries on the world list",
                                                     "LegendCraft", ex, false);
                        }
#endif
                        }

                        XAttribute temp;
                        if ((temp = root.Attribute("main")) != null)
                        {
                            World suggestedMainWorld = FindWorldExact(temp.Value);

                            if (suggestedMainWorld != null)
                            {
                                newMainWorld = suggestedMainWorld;
                            }
                            else if (firstWorld != null)
                            {
                                // if specified main world does not exist, use first-defined world
                                Logger.Log(LogType.Warning,
                                           "The specified main world \"{0}\" does not exist. " +
                                           "\"{1}\" was designated main instead. You can use /WMain to change it.",
                                           temp.Value, firstWorld.Name);
                                newMainWorld = firstWorld;
                            }
                            // if firstWorld was also null, LoadWorldList() should try creating a new mainWorld
                        }
                        else if (firstWorld != null)
                        {
                            newMainWorld = firstWorld;
                        }
                    }
                } catch (Exception ex) {
                    Logger.LogAndReportCrash("Error occured while trying to load the world list.", "800Craft", ex, true);
                    return(false);
                }

                if (newMainWorld == null)
                {
                    Logger.Log(LogType.Warning,
                               "Server.Start: Could not load any of the specified worlds, or no worlds were specified. " +
                               "Creating default \"main\" world. Ignore this message if this is your first time running LegendCraft.");
                    newMainWorld = AddWorld(null, "main", MapGenerator.GenerateFlatgrass(128, 128, 64), true);
                }
            }
            else
            {
                Logger.Log(LogType.SystemActivity,
                           "Server.Start: No world list found. Creating default \"main\" world.");
                newMainWorld = AddWorld(null, "main", MapGenerator.GenerateFlatgrass(128, 128, 64), true);
            }

            // if there is no default world still, die.
            if (newMainWorld == null)
            {
                throw new Exception("Could not create any worlds.");
            }
            else if (newMainWorld.AccessSecurity.HasRestrictions)
            {
                Logger.Log(LogType.Warning,
                           "Server.LoadWorldList: Main world cannot have any access restrictions. " +
                           "Access permission for \"{0}\" has been reset.",
                           newMainWorld.Name);
                newMainWorld.AccessSecurity.Reset();
            }

            MainWorld = newMainWorld;

            return(true);
        }
Esempio n. 5
0
        public static void RealmCreate(Player player, Command cmd, string themeName, string templateName)
        {
            MapGenTemplate template;
            MapGenTheme    theme;

            int wx, wy, height = 128;

            if (!(cmd.NextInt(out wx) && cmd.NextInt(out wy) && cmd.NextInt(out height)))
            {
                if (player.World != null)
                {
                    wx     = 128;
                    wy     = 128;
                    height = 128;
                }
                else
                {
                    player.Message("When used from console, /gen requires map dimensions.");

                    return;
                }
                cmd.Rewind();
                cmd.Next();
                cmd.Next();
            }

            if (!Map.IsValidDimension(wx))
            {
                player.Message("Cannot make map with width {0}: dimensions must be multiples of 16.", wx);
                return;
            }
            else if (!Map.IsValidDimension(wy))
            {
                player.Message("Cannot make map with length {0}: dimensions must be multiples of 16.", wy);
                return;
            }
            else if (!Map.IsValidDimension(height))
            {
                player.Message("Cannot make map with height {0}: dimensions must be multiples of 16.", height);
                return;
            }

            string fileName     = player.Name;
            string fullFileName = null;

            if (fileName == null)
            {
                if (player.World == null)
                {
                    player.Message("When used from console, /gen requires FileName.");

                    return;
                }
                if (!cmd.IsConfirmed)
                {
                    player.Confirm(cmd, "Replace this realm's map with a generated one?");
                    return;
                }
            }
            else
            {
                fileName = fileName.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
                if (!fileName.EndsWith(".fcm", StringComparison.OrdinalIgnoreCase))
                {
                    fileName += ".fcm";
                }
                fullFileName = Path.Combine(Paths.MapPath, fileName);
                if (!Paths.IsValidPath(fullFileName))
                {
                    player.Message("Invalid filename.");
                    return;
                }
                if (!Paths.Contains(Paths.MapPath, fullFileName))
                {
                    player.MessageUnsafePath();
                    return;
                }
                string dirName = fullFileName.Substring(0, fullFileName.LastIndexOf(Path.DirectorySeparatorChar));
                if (!Directory.Exists(dirName))
                {
                    Directory.CreateDirectory(dirName);
                }
                if (!cmd.IsConfirmed && File.Exists(fullFileName))
                {
                    player.Confirm(cmd, "The mapfile \"{0}\" already exists. Overwrite?", fileName);
                    return;
                }
            }

            bool noTrees;

            if (themeName.Equals("grass", StringComparison.OrdinalIgnoreCase))
            {
                theme   = MapGenTheme.Forest;
                noTrees = true;
            }
            else
            {
                try
                {
                    theme   = (MapGenTheme)Enum.Parse(typeof(MapGenTheme), themeName, true);
                    noTrees = (theme != MapGenTheme.Forest);
                }
                catch (Exception)
                {
                    player.MessageNow("Unrecognized theme \"{0}\". Available themes are: Grass, {1}",
                                      themeName,
                                      String.Join(", ", Enum.GetNames(typeof(MapGenTheme))));
                    return;
                }
            }

            try
            {
                template = (MapGenTemplate)Enum.Parse(typeof(MapGenTemplate), templateName, true);
            }
            catch (Exception)
            {
                player.Message("Unrecognized template \"{0}\". Available templates are: {1}",
                               templateName,
                               String.Join(", ", Enum.GetNames(typeof(MapGenTemplate))));
                return;
            }

            if (!Enum.IsDefined(typeof(MapGenTheme), theme) || !Enum.IsDefined(typeof(MapGenTemplate), template))
            {
                return;
            }

            MapGeneratorArgs args = MapGenerator.MakeTemplate(template);

            args.MapWidth  = wx;
            args.MapLength = wy;
            args.MapHeight = height;
            args.MaxHeight = (int)(args.MaxHeight / 80d * height);
            args.MaxDepth  = (int)(args.MaxDepth / 80d * height);
            args.Theme     = theme;
            args.AddTrees  = !noTrees;

            Map map;

            try
            {
                if (theme == MapGenTheme.Forest && noTrees)
                {
                    player.MessageNow("Generating Grass {0}...", template);
                }
                else
                {
                    player.MessageNow("Generating {0} {1}...", theme, template);
                }
                if (theme == MapGenTheme.Forest && noTrees && template == MapGenTemplate.Flat)
                {
                    map = MapGenerator.GenerateFlatgrass(args.MapWidth, args.MapLength, args.MapHeight);
                }
                else
                {
                    MapGenerator generator = new MapGenerator(args);
                    map = generator.Generate();
                }
            }
            catch (Exception ex)
            {
                Logger.Log(LogType.Error, "MapGenerator: Generation failed: {0}",
                           ex);
                player.MessageNow("&WAn error occured while generating the map.");
                return;
            }

            if (fileName != null)
            {
                if (map.Save(fullFileName))
                {
                    player.MessageNow("Generation done. Saved to {0}", fileName);
                }
                else
                {
                    player.Message("&WAn error occured while saving generated map to {0}", fileName);
                }
            }
            else
            {
                player.MessageNow("Generation done. Changing map...");
                player.World.ChangeMap(map);
            }
        }
Esempio n. 6
0
        static void GenHandler(Player player, Command cmd)
        {
            World playerWorld = player.World;
            string themeName = cmd.Next();
            string templateName;
            bool genOcean = false;
            bool genEmpty = false;
            bool noTrees = false;

            if (themeName == null)
            {
                CdGenerate.PrintUsage(player);
                return;
            }
            MapGenTheme theme = MapGenTheme.Forest;
            MapGenTemplate template = MapGenTemplate.Flat;

            // parse special template names (which do not need a theme)
            if (themeName.Equals("ocean"))
            {
                genOcean = true;

            }
            else if (themeName.Equals("empty"))
            {
                genEmpty = true;

            }
            else
            {
                templateName = cmd.Next();
                if (templateName == null)
                {
                    CdGenerate.PrintUsage(player);
                    return;
                }

                // parse theme
                bool swapThemeAndTemplate = false;
                if (themeName.Equals("grass", StringComparison.OrdinalIgnoreCase))
                {
                    theme = MapGenTheme.Forest;
                    noTrees = true;

                }
                else if (templateName.Equals("grass", StringComparison.OrdinalIgnoreCase))
                {
                    theme = MapGenTheme.Forest;
                    noTrees = true;
                    swapThemeAndTemplate = true;

                }
                else if (EnumUtil.TryParse(themeName, out theme, true))
                {
                    noTrees = (theme != MapGenTheme.Forest);

                }
                else if (EnumUtil.TryParse(templateName, out theme, true))
                {
                    noTrees = (theme != MapGenTheme.Forest);
                    swapThemeAndTemplate = true;

                }
                else
                {
                    player.Message("Gen: Unrecognized theme \"{0}\". Available themes are: Grass, {1}",
                                    themeName,
                                    Enum.GetNames(typeof(MapGenTheme)).JoinToString());
                    return;
                }

                // parse template
                if (swapThemeAndTemplate)
                {
                    if (!EnumUtil.TryParse(themeName, out template, true))
                    {
                        player.Message("Unrecognized template \"{0}\". Available terrain types: Empty, Ocean, {1}",
                                        themeName,
                                        Enum.GetNames(typeof(MapGenTemplate)).JoinToString());
                        return;
                    }
                }
                else
                {
                    if (!EnumUtil.TryParse(templateName, out template, true))
                    {
                        player.Message("Unrecognized template \"{0}\". Available terrain types: Empty, Ocean, {1}",
                                        templateName,
                                        Enum.GetNames(typeof(MapGenTemplate)).JoinToString());
                        return;
                    }
                }
            }

            // parse map dimensions
            int mapWidth, mapLength, mapHeight;
            if (cmd.HasNext)
            {
                int offset = cmd.Offset;
                if (!(cmd.NextInt(out mapWidth) && cmd.NextInt(out mapLength) && cmd.NextInt(out mapHeight)))
                {
                    if (playerWorld != null)
                    {
                        Map oldMap = player.WorldMap;
                        // If map dimensions were not given, use current map's dimensions
                        mapWidth = oldMap.Width;
                        mapLength = oldMap.Length;
                        mapHeight = oldMap.Height;
                    }
                    else
                    {
                        player.Message("When used from console, /Gen requires map dimensions.");
                        CdGenerate.PrintUsage(player);
                        return;
                    }
                    cmd.Offset = offset;
                }
            }
            else if (playerWorld != null)
            {
                Map oldMap = player.WorldMap;
                // If map dimensions were not given, use current map's dimensions
                mapWidth = oldMap.Width;
                mapLength = oldMap.Length;
                mapHeight = oldMap.Height;
            }
            else
            {
                player.Message("When used from console, /Gen requires map dimensions.");
                CdGenerate.PrintUsage(player);
                return;
            }

            // Check map dimensions
            const string dimensionRecommendation = "Dimensions must be between 16 and 2047. " +
                                                   "Recommended values: 16, 32, 64, 128, 256, 512, and 1024.";
            if (!Map.IsValidDimension(mapWidth))
            {
                player.Message("Cannot make map with width {0}. {1}", mapWidth, dimensionRecommendation);
                return;
            }
            else if (!Map.IsValidDimension(mapLength))
            {
                player.Message("Cannot make map with length {0}. {1}", mapLength, dimensionRecommendation);
                return;
            }
            else if (!Map.IsValidDimension(mapHeight))
            {
                player.Message("Cannot make map with height {0}. {1}", mapHeight, dimensionRecommendation);
                return;
            }
            long volume = (long)mapWidth * (long)mapLength * (long)mapHeight;
            if (volume > Int32.MaxValue)
            {
                player.Message("Map volume may not exceed {0}", Int32.MaxValue);
                return;
            }

            if (!cmd.IsConfirmed && (!Map.IsRecommendedDimension(mapWidth) || !Map.IsRecommendedDimension(mapLength) || !Map.IsRecommendedDimension(mapHeight)))
            {
                player.Message("&WThe map will have non-standard dimensions. " +
                                "You may see glitched blocks or visual artifacts. " +
                                "The only recommended map dimensions are: 16, 32, 64, 128, 256, 512, and 1024.");
            }

            // figure out full template name
            bool genFlatgrass = (theme == MapGenTheme.Forest && noTrees && template == MapGenTemplate.Flat);
            string templateFullName;
            if (genEmpty)
            {
                templateFullName = "Empty";
            }
            else if (genOcean)
            {
                templateFullName = "Ocean";
            }
            else if (genFlatgrass)
            {
                templateFullName = "Flatgrass";
            }
            else
            {
                if (theme == MapGenTheme.Forest && noTrees)
                {
                    templateFullName = "Grass " + template;
                }
                else
                {
                    templateFullName = theme + " " + template;
                }
            }

            // check file/world name
            string fileName = cmd.Next();
            string fullFileName = null;
            if (fileName == null)
            {
                // replacing current world
                if (playerWorld == null)
                {
                    player.Message("When used from console, /Gen requires FileName.");
                    CdGenerate.PrintUsage(player);
                    return;
                }
                if (!cmd.IsConfirmed)
                {
                    player.Confirm(cmd, "Replace THIS MAP with a generated one ({0})?", templateFullName);
                    return;
                }

            }
            else
            {
                if (cmd.HasNext)
                {
                    CdGenerate.PrintUsage(player);
                    return;
                }
                // saving to file
                fileName = fileName.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
                if (!fileName.EndsWith(".fcm", StringComparison.OrdinalIgnoreCase))
                {
                    fileName += ".fcm";
                }
                if (!Paths.IsValidPath(fileName))
                {
                    player.Message("Invalid filename.");
                    return;
                }
                fullFileName = Path.Combine(Paths.MapPath, fileName);
                if (!Paths.Contains(Paths.MapPath, fullFileName))
                {
                    player.MessageUnsafePath();
                    return;
                }
                string dirName = fullFileName.Substring(0, fullFileName.LastIndexOf(Path.DirectorySeparatorChar));
                if (!Directory.Exists(dirName))
                {
                    Directory.CreateDirectory(dirName);
                }
                if (!cmd.IsConfirmed && File.Exists(fullFileName))
                {
                    player.Confirm(cmd, "The mapfile \"{0}\" already exists. Overwrite?", fileName);
                    return;
                }
            }

            // generate the map
            Map map;
            player.MessageNow("Generating {0}...", templateFullName);

            if (genEmpty)
            {
                map = MapGenerator.GenerateEmpty(mapWidth, mapLength, mapHeight);

            }
            else if (genOcean)
            {
                map = MapGenerator.GenerateOcean(mapWidth, mapLength, mapHeight);

            }
            else if (genFlatgrass)
            {
                map = MapGenerator.GenerateFlatgrass(mapWidth, mapLength, mapHeight);

            }
            else
            {
                MapGeneratorArgs args = MapGenerator.MakeTemplate(template);
                if (theme == MapGenTheme.Desert)
                {
                    args.AddWater = false;
                }
                float ratio = mapHeight / (float)args.MapHeight;
                args.MapWidth = mapWidth;
                args.MapLength = mapLength;
                args.MapHeight = mapHeight;
                args.MaxHeight = (int)Math.Round(args.MaxHeight * ratio);
                args.MaxDepth = (int)Math.Round(args.MaxDepth * ratio);
                args.SnowAltitude = (int)Math.Round(args.SnowAltitude * ratio);
                args.Theme = theme;
                args.AddTrees = !noTrees;

                MapGenerator generator = new MapGenerator(args);
                map = generator.Generate();
            }

            // save map to file, or load it into a world
            if (fileName != null)
            {
                if (map.Save(fullFileName))
                {
                    player.Message("Generation done. Saved to {0}", fileName);
                }
                else
                {
                    player.Message("&WAn error occured while saving generated map to {0}", fileName);
                }
            }
            else
            {
                if (playerWorld == null) PlayerOpException.ThrowNoWorld(player);
                player.MessageNow("Generation done. Changing map...");
                playerWorld.MapChangedBy = player.Name;
                playerWorld.ChangeMap(map);
            }
            Server.RequestGC();
        }
Esempio n. 7
0
        internal static bool LoadWorldList()
        {
            World firstWorld   = null;
            World newMainWorld = null;

            lock ( SyncRoot ) {
                Worlds = new World[0];
                if (File.Exists(Paths.WorldListFileName))
                {
#if !DEBUG
                    try {
#endif
                    XDocument doc = XDocument.Load(Paths.WorldListFileName);
                    XElement root = doc.Root;
                    if (root != null)
                    {
                        foreach (XElement el in root.Elements("World"))
                        {
#if DEBUG
                            World newWorld = AddWorld(el);
#else
                            World newWorld;
                            try {
                                newWorld = AddWorld(el);
                            } catch (Exception ex) {
                                Logger.LogAndReportCrash("An error occurred while trying to parse one of the entries on the world list",
                                                         "fCraft", ex, false);
                                continue;
                            }
#endif
                            if (firstWorld == null)
                            {
                                firstWorld = newWorld;
                            }
                        }

                        XAttribute temp;
                        if ((temp = root.Attribute("main")) != null)
                        {
                            World suggestedMainWorld = FindWorldExact(temp.Value);

                            if (suggestedMainWorld != null)
                            {
                                newMainWorld = suggestedMainWorld;
                            }
                            else if (firstWorld != null)
                            {
                                // if specified main world does not exist, use first-defined world
                                Logger.Log(LogType.Warning,
                                           "The specified main world \"{0}\" does not exist. " +
                                           "\"{1}\" was designated main instead. You can use /WMain to change it.",
                                           temp.Value, firstWorld.Name);
                                newMainWorld = firstWorld;
                            }
                            // if firstWorld was also null, LoadWorldList() should try creating a new mainWorld
                        }
                        else if (firstWorld != null)
                        {
                            newMainWorld = firstWorld;
                        }

                        foreach (XElement mainedRankEl in root.Elements(RankMainXmlTagName))
                        {
                            temp = mainedRankEl.Attribute("rank");
                            if (temp == null)
                            {
                                Logger.Log(LogType.Warning,
                                           "WorldManager.Load: Malformed RankMain element: \"rank\" attribute missing.");
                                continue;
                            }

                            string rankName = temp.Value;
                            Rank   rank     = Rank.Parse(rankName);
                            if (rank == null)
                            {
                                Logger.Log(LogType.Warning,
                                           "Rank main defined for an unrecognized rank \"{0}\"",
                                           rankName);
                                continue;
                            }

                            temp = mainedRankEl.Attribute("world");
                            if (temp == null)
                            {
                                Logger.Log(LogType.Warning,
                                           "WorldManager.Load: Malformed RankMain element: \"world\" attribute missing.");
                                continue;
                            }

                            string worldName = temp.Value;
                            World  world     = FindWorldExact(mainedRankEl.Value);
                            if (world == null)
                            {
                                Logger.Log(LogType.Warning,
                                           "Rank main for \"{0}\" set to an unrecognized world \"{1}\"",
                                           rank.Name, worldName);
                                continue;
                            }

                            if (rank < world.AccessSecurity.MinRank)
                            {
                                world.AccessSecurity.MinRank = rank;
                                Logger.Log(LogType.Warning,
                                           "WorldManager: Lowered access MinRank of world {0} to {1}+ to allow it to be the main world for that rank.",
                                           world.Name, rank.Name);
                            }
                            rank.MainWorld = world;
                        }
                    }
#if !DEBUG
                }
                catch (XmlException ex) {
                    string errorMsg = "WorldManager.LoadWorldList: worlds.xml is not properly formatted: " + ex.Message;
                    Logger.LogAndReportCrash("World list failed to load", "fCraft",
                                             new MisconfigurationException(errorMsg, ex), true);
                    return(false);
                } catch (Exception ex) {
                    Logger.LogAndReportCrash("World list failed to load", "fCraft", ex, true);
                    return(false);
                }
#endif

                    if (newMainWorld == null)
                    {
                        Logger.Log(LogType.Error,
                                   "Server.Start: Could not load any of the specified worlds, or no worlds were specified. " +
                                   "Creating default \"main\" world.");
                        newMainWorld = AddWorld(null, "main", MapGenerator.GenerateFlatgrass(128, 128, 64), true);
                    }
                }
                else
                {
                    Logger.Log(LogType.SystemActivity,
                               "Server.Start: No world list found. Creating default \"main\" world.");
                    newMainWorld = AddWorld(null, "main", MapGenerator.GenerateFlatgrass(128, 128, 64), true);
                }

                if (newMainWorld.AccessSecurity.HasRestrictions)
                {
                    Logger.Log(LogType.Warning,
                               "Server.LoadWorldList: Main world cannot have any access restrictions. " +
                               "Access permission for \"{0}\" has been reset.",
                               newMainWorld.Name);
                    newMainWorld.AccessSecurity.Reset();
                }

                MainWorld = newMainWorld;
            }
            return(true);
        }
Esempio n. 8
0
        public static void RealmCreate(Player player, Command cmd, string themeName, string templateName)
        {
            MapGenTemplate template;
            MapGenTheme theme;

            int wx, wy, height = 128;
            if (!(cmd.NextInt(out wx) && cmd.NextInt(out wy) && cmd.NextInt(out height)))
            {
                if (player.World != null)
                {
                    wx = 128;
                    wy = 128;
                    height = 128;
                }
                else
                {
                    player.Message("When used from console, /gen requires map dimensions.");

                    return;
                }
                cmd.Rewind();
                cmd.Next();
                cmd.Next();
            }

            if (!Map.IsValidDimension(wx))
            {
                player.Message("Cannot make map with width {0}: dimensions must be multiples of 16.", wx);
                return;
            }
            else if (!Map.IsValidDimension(wy))
            {
                player.Message("Cannot make map with length {0}: dimensions must be multiples of 16.", wy);
                return;
            }
            else if (!Map.IsValidDimension(height))
            {
                player.Message("Cannot make map with height {0}: dimensions must be multiples of 16.", height);
                return;
            }

            string fileName = player.Name;
            string fullFileName = null;

            if (fileName == null)
            {
                if (player.World == null)
                {
                    player.Message("When used from console, /gen requires FileName.");

                    return;
                }
                if (!cmd.IsConfirmed)
                {
                    player.Confirm(cmd, "Replace this realm's map with a generated one?");
                    return;
                }
            }
            else
            {
                fileName = fileName.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
                if (!fileName.EndsWith(".fcm", StringComparison.OrdinalIgnoreCase))
                {
                    fileName += ".fcm";
                }
                fullFileName = Path.Combine(Paths.MapPath, fileName);
                if (!Paths.IsValidPath(fullFileName))
                {
                    player.Message("Invalid filename.");
                    return;
                }
                if (!Paths.Contains(Paths.MapPath, fullFileName))
                {
                    player.MessageUnsafePath();
                    return;
                }
                string dirName = fullFileName.Substring(0, fullFileName.LastIndexOf(Path.DirectorySeparatorChar));
                if (!Directory.Exists(dirName))
                {
                    Directory.CreateDirectory(dirName);
                }
                if (!cmd.IsConfirmed && File.Exists(fullFileName))
                {
                    player.Confirm(cmd, "The mapfile \"{0}\" already exists. Overwrite?", fileName);
                    return;
                }
            }

            bool noTrees;
            if (themeName.Equals("grass", StringComparison.OrdinalIgnoreCase))
            {
                theme = MapGenTheme.Forest;
                noTrees = true;
            }
            else
            {
                try
                {
                    theme = (MapGenTheme)Enum.Parse(typeof(MapGenTheme), themeName, true);
                    noTrees = (theme != MapGenTheme.Forest);
                }
                catch (Exception)
                {
                    player.MessageNow("Unrecognized theme \"{0}\". Available themes are: Grass, {1}",
                                       themeName,
                                       String.Join(", ", Enum.GetNames(typeof(MapGenTheme))));
                    return;
                }
            }

            try
            {
                template = (MapGenTemplate)Enum.Parse(typeof(MapGenTemplate), templateName, true);
            }
            catch (Exception)
            {
                player.Message("Unrecognized template \"{0}\". Available templates are: {1}",
                                templateName,
                                String.Join(", ", Enum.GetNames(typeof(MapGenTemplate))));
                return;
            }

            if (!Enum.IsDefined(typeof(MapGenTheme), theme) || !Enum.IsDefined(typeof(MapGenTemplate), template))
            {

                return;
            }

            MapGeneratorArgs args = MapGenerator.MakeTemplate(template);
            args.MapWidth = wx;
            args.MapLength = wy;
            args.MapHeight = height;
            args.MaxHeight = (int)(args.MaxHeight / 80d * height);
            args.MaxDepth = (int)(args.MaxDepth / 80d * height);
            args.Theme = theme;
            args.AddTrees = !noTrees;

            Map map;
            try
            {
                if (theme == MapGenTheme.Forest && noTrees)
                {
                    player.MessageNow("Generating Grass {0}...", template);
                }
                else
                {
                    player.MessageNow("Generating {0} {1}...", theme, template);
                }
                if (theme == MapGenTheme.Forest && noTrees && template == MapGenTemplate.Flat)
                {
                    map = MapGenerator.GenerateFlatgrass(args.MapWidth, args.MapLength, args.MapHeight);
                }
                else
                {
                    MapGenerator generator = new MapGenerator(args);
                    map = generator.Generate();
                }

            }
            catch (Exception ex)
            {
                Logger.Log(LogType.Error, "MapGenerator: Generation failed: {0}",
                            ex);
                player.MessageNow("&WAn error occured while generating the map.");
                return;
            }

            if (fileName != null)
            {
                if (map.Save(fullFileName))
                {
                    player.MessageNow("Generation done. Saved to {0}", fileName);
                }
                else
                {
                    player.Message("&WAn error occured while saving generated map to {0}", fileName);
                }
            }
            else
            {
                player.MessageNow("Generation done. Changing map...");
                player.World.ChangeMap(map);
            }
        }
Esempio n. 9
0
        void AsyncGen( object sender, DoWorkEventArgs e ) {
            stopwatch = Stopwatch.StartNew();
            GC.Collect( GC.MaxGeneration, GCCollectionMode.Forced );
            Map generatedMap;
            if( tab == Tabs.Generator ) {
                MapGenerator gen = new MapGenerator( generatorArgs );
                gen.ProgressCallback = delegate( object _sender, ProgressChangedEventArgs args ) {
                    bwGenerator.ReportProgress( args.ProgressPercentage, args.UserState );
                };
                generatedMap = gen.Generate();
            } else {
                generatedMap = new Map( null,
                                        Convert.ToInt32( nFlatgrassDimX.Value ),
                                        Convert.ToInt32( nFlatgrassDimY.Value ),
                                        Convert.ToInt32( nFlatgrassDimH.Value ),
                                        true );
                MapGenerator.GenerateFlatgrass( generatedMap );
                generatedMap.ResetSpawn();
            }

            if( floodBarrier ) generatedMap.MakeFloodBarrier();
            generatedMap.CalculateShadows();
            map = generatedMap;
            GC.Collect( GC.MaxGeneration, GCCollectionMode.Forced );
        }