Пример #1
0
        public static int Main(string[] args)
        {
            InitLoggerConfig();
            InitSettings(args);

            // DumpTileProperties();

            if (!ValidateSettings())
            {
                return(2);
            }

            try {
                Logger.Info("Initializing virtual filesystem");

                var         mapStream = File.Open(Settings.InputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                VirtualFile vmapFile;
                var         mixMap = new MixFile(mapStream, Settings.InputFile, 0, mapStream.Length, false, false);
                if (mixMap.IsValid())                   // input max is a mix
                {
                    var mapArchive = new MixFile(mapStream, Path.GetFileName(Settings.InputFile), true);
                    // grab the largest file in the archive
                    var mixEntry = mapArchive.Index.OrderByDescending(me => me.Value.Length).First();
                    vmapFile = mapArchive.OpenFile(mixEntry.Key);
                }
                else
                {
                    vmapFile = new VirtualFile(mapStream, Path.GetFileName(Settings.InputFile), true);
                }
                var mapFile = new MapFile(vmapFile, Path.GetFileName(Settings.InputFile));

                if (!string.IsNullOrEmpty(Settings.ModConfig))
                {
                    if (File.Exists(Settings.ModConfig))
                    {
                        ModConfig cfg;
                        try {
                            using (FileStream f = File.OpenRead(Settings.ModConfig))
                                cfg = ModConfig.Deserialize(f);
                            ModConfig.ActiveConfig = cfg;
                            if (Settings.Engine != EngineType.AutoDetect)
                            {
                                if (Settings.Engine != cfg.Engine)
                                {
                                    Logger.Warn("Provided engine override does not match mod config.");
                                }
                            }
                            else
                            {
                                Settings.Engine = ModConfig.ActiveConfig.Engine;
                            }
                        }
                        catch (IOException) {
                            Logger.Error("IOException while loading mod config");
                        }
                        catch (XmlException) {
                            Logger.Error("XmlException while loading mod config");
                        }
                        catch (SerializationException) {
                            Logger.Error("Serialization exception while loading mod config");
                        }
                    }
                    else
                    {
                        Logger.Error("Invalid mod config file specified");
                    }
                }

                if (Settings.Engine == EngineType.AutoDetect)
                {
                    Settings.Engine = EngineDetector.DetectEngineType(mapFile);
                    Logger.Info("Engine autodetect result: {0}", Settings.Engine);
                }

                // ---------------------------------------------------------------
                // Code to organize moving of maps in a directory for themselves

                /*
                 * string mapName = DetermineMapName(mapFile, Settings.Engine);
                 * string ndir = Path.Combine(Path.GetDirectoryName(Settings.InputFile), mapName);
                 * if (!Directory.Exists(ndir)) Directory.CreateDirectory(ndir);
                 * mapFile.Close();
                 * mapFile.Dispose();
                 * File.Move(Settings.InputFile, Path.Combine(ndir, Path.GetFileName(mapFile.FileName)));
                 * return 0;*/
                // ---------------------------------------------------------------

                // enginetype is now definitive, load mod config
                if (ModConfig.ActiveConfig == null)
                {
                    ModConfig.LoadDefaultConfig(Settings.Engine);
                }

                // first add the dirs, then load the extra mixes, then scan the dirs
                foreach (string modDir in ModConfig.ActiveConfig.Directories)
                {
                    VFS.Add(modDir);
                }

                // add mixdir to VFS (if it's not included in the mod config)
                if (!ModConfig.ActiveConfig.Directories.Any())
                {
                    string mixDir = VFS.DetermineMixDir(Settings.MixFilesDirectory, Settings.Engine);
                    VFS.Add(mixDir);
                }
                foreach (string mixFile in ModConfig.ActiveConfig.ExtraMixes)
                {
                    VFS.Add(mixFile);
                }
                foreach (var dir in VFS.Instance.AllArchives.OfType <DirArchive>().Select(d => d.Directory).ToList())
                {
                    VFS.Instance.ScanMixDir(dir, Settings.Engine);
                }

                var map = new Map {
                    IgnoreLighting  = Settings.IgnoreLighting,
                    StartPosMarking = Settings.StartPositionMarking,
                    MarkOreFields   = Settings.MarkOreFields
                };

                if (!map.Initialize(mapFile, Settings.Engine))
                {
                    Logger.Error("Could not successfully load this map. Try specifying the engine type manually.");
                    return(1);
                }

                if (!map.LoadTheater())
                {
                    Logger.Error("Could not successfully load all required components for this map. Aborting.");
                    return(1);
                }

                if (Settings.StartPositionMarking == StartPositionMarking.Tiled)
                {
                    map.MarkTiledStartPositions();
                }

                if (Settings.MarkOreFields)
                {
                    map.MarkOreAndGems();
                }

                map.Draw();

#if DEBUG
                // ====================================================================================
                using (var form = new DebugDrawingSurfaceWindow(map.GetDrawingSurface(), map.GetTiles(), map.GetTheater(), map)) {
                    form.RequestTileEvaluate += map.DebugDrawTile; form.ShowDialog();
                }
                // ====================================================================================
#endif

                if (Settings.StartPositionMarking == StartPositionMarking.Squared)
                {
                    map.DrawSquaredStartPositions();
                }

                if (Settings.OutputFile == "")
                {
                    Settings.OutputFile = DetermineMapName(mapFile, Settings.Engine);
                }

                if (Settings.OutputDir == "")
                {
                    Settings.OutputDir = Path.GetDirectoryName(Settings.InputFile);
                }

                // free up as much memory as possible before saving the large images
                Rectangle      saveRect = map.GetSizePixels(Settings.SizeMode);
                DrawingSurface ds       = map.GetDrawingSurface();
                // if we don't need this data anymore, we can try to save some memory
                if (!Settings.GeneratePreviewPack)
                {
                    ds.FreeNonBitmap();
                    map.FreeUseless();
                    GC.Collect();
                }

                if (Settings.SaveJPEG)
                {
                    ds.SaveJPEG(Path.Combine(Settings.OutputDir, Settings.OutputFile + ".jpg"), Settings.JPEGCompression, saveRect);
                }

                if (Settings.SavePNG)
                {
                    ds.SavePNG(Path.Combine(Settings.OutputDir, Settings.OutputFile + ".png"), Settings.PNGQuality, saveRect);
                }

                Regex reThumb = new Regex(@"(\+)?\((\d+),(\d+)\)");
                var   match   = reThumb.Match(Settings.ThumbnailSettings);
                if (match.Success)
                {
                    Size dimensions = new Size(
                        int.Parse(match.Groups[2].Captures[0].Value),
                        int.Parse(match.Groups[3].Captures[0].Value));
                    var cutRect = map.GetSizePixels(Settings.SizeMode);

                    if (match.Groups[1].Captures[0].Value == "+")
                    {
                        // + means maintain aspect ratio
                        double aspectRatio = cutRect.Width / (double)cutRect.Height;
                        if (dimensions.Width / (double)dimensions.Height > aspectRatio)
                        {
                            dimensions.Height = (int)(dimensions.Width / aspectRatio);
                        }
                        else
                        {
                            dimensions.Width = (int)(dimensions.Height / aspectRatio);
                        }
                    }
                    Logger.Info("Saving thumbnail with dimensions {0}x{1}", dimensions.Width, dimensions.Height);
                    ds.SaveThumb(dimensions, cutRect, Path.Combine(Settings.OutputDir, "thumb_" + Settings.OutputFile + ".jpg"));
                }

                if (Settings.GeneratePreviewPack)
                {
                    if (mapFile.BaseStream is MixFile)
                    {
                        Logger.Error("Cannot inject thumbnail into an archive (.mmx/.yro/.mix)!");
                    }
                    else
                    {
                        map.GeneratePreviewPack(Settings.OmitPreviewPackMarkers, Settings.SizeMode, mapFile);
                        Logger.Info("Saving map");
                        mapFile.Save(Settings.InputFile);
                    }
                }
            }
            catch (Exception exc) {
                Logger.Error(string.Format("An unknown fatal exception occured: {0}", exc), exc);
#if DEBUG
                throw;
#else
                return(1);
#endif
            }

            LogManager.Configuration = null;             // required for mono release to flush possible targets
            return(0);
        }
Пример #2
0
        public EngineResult Execute()
        {
            try {
                _logger.Info("Initializing virtual filesystem");

                var         mapStream = File.Open(_settings.InputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                VirtualFile vmapFile;
                var         mixMap = new MixFile(mapStream, _settings.InputFile, 0, mapStream.Length, false, false);
                if (mixMap.IsValid())                   // input max is a mix
                {
                    var mapArchive = new MixFile(mapStream, Path.GetFileName(_settings.InputFile), true);
                    // grab the largest file in the archive
                    var mixEntry = mapArchive.Index.OrderByDescending(me => me.Value.Length).First();
                    vmapFile = mapArchive.OpenFile(mixEntry.Key);
                }
                else
                {
                    vmapFile = new VirtualFile(mapStream, Path.GetFileName(_settings.InputFile), true);
                }
                var mapFile = new MapFile(vmapFile, Path.GetFileName(_settings.InputFile));

                ModConfig modConfig = null;
                if (!string.IsNullOrEmpty(_settings.ModConfig))
                {
                    if (File.Exists(_settings.ModConfig))
                    {
                        try {
                            using (FileStream f = File.OpenRead(_settings.ModConfig))
                                modConfig = ModConfig.Deserialize(f);
                        }
                        catch (IOException) {
                            _logger.Fatal("IOException while loading mod config");
                        }
                        catch (XmlException) {
                            _logger.Fatal("XmlException while loading mod config");
                        }
                        catch (SerializationException) {
                            _logger.Fatal("Serialization exception while loading mod config");
                        }
                    }
                    else
                    {
                        _logger.Fatal("Invalid mod config file specified");
                    }
                }

                if (_settings.Engine == EngineType.AutoDetect)
                {
                    _settings.Engine = EngineDetector.DetectEngineType(mapFile);
                    _logger.Info("Engine autodetect result: {0}", _settings.Engine);
                }

                // Engine type is now definitive, load mod config
                if (modConfig == null)
                {
                    modConfig = ModConfig.GetDefaultConfig(_settings.Engine);
                }

                var map = new Map.Map {
                    IgnoreLighting  = _settings.IgnoreLighting,
                    StartPosMarking = _settings.StartPositionMarking,
                    StartMarkerSize = _settings.MarkerStartSize,
                    MarkOreFields   = _settings.MarkOreFields
                };

                using (var vfs = new VirtualFileSystem()) {
                    // first add the dirs, then load the extra mixes, then scan the dirs
                    foreach (string modDir in modConfig.Directories)
                    {
                        vfs.Add(modDir);
                    }

                    // add mixdir to VFS (if it's not included in the mod config)
                    if (!modConfig.Directories.Any())
                    {
                        string mixDir =
                            VirtualFileSystem.DetermineMixDir(_settings.MixFilesDirectory, _settings.Engine);
                        vfs.Add(mixDir);
                    }

                    foreach (string mixFile in modConfig.ExtraMixes)
                    {
                        vfs.Add(mixFile);
                    }

                    vfs.LoadMixes(_settings.Engine);

                    if (!map.Initialize(mapFile, modConfig, vfs))
                    {
                        _logger.Error("Could not successfully load this map. Try specifying the engine type manually.");
                        return(EngineResult.LoadRulesFailed);
                    }

                    if (!map.LoadTheater())
                    {
                        _logger.Error("Could not successfully load all required components for this map. Aborting.");
                        return(EngineResult.LoadTheaterFailed);
                    }

                    if (_settings.MarkStartPos && _settings.StartPositionMarking == StartPositionMarking.Tiled)
                    {
                        map.MarkTiledStartPositions();
                    }

                    if (_settings.MarkOreFields)
                    {
                        map.MarkOreAndGems();
                    }

                    if ((_settings.GeneratePreviewPack || _settings.FixupTiles || _settings.FixOverlays ||
                         _settings.CompressTiles) && _settings.Backup)
                    {
                        if (mapFile.BaseStream is MixFile)
                        {
                            _logger.Error("Cannot generate a map file backup into an archive (.mmx/.yro/.mix)!");
                        }
                        else
                        {
                            try {
                                string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
                                string fileInput = Path.Combine(Path.GetDirectoryName(_settings.InputFile),
                                                                Path.GetFileName(_settings.InputFile));
                                fileInput = fileInput.TrimEnd(Path.DirectorySeparatorChar,
                                                              Path.AltDirectorySeparatorChar);
                                string fileInputNoExtn = Path.Combine(Path.GetDirectoryName(_settings.InputFile),
                                                                      Path.GetFileNameWithoutExtension(_settings.InputFile));
                                fileInputNoExtn = fileInputNoExtn.TrimEnd(Path.DirectorySeparatorChar,
                                                                          Path.AltDirectorySeparatorChar);
                                string fileBackup = fileInputNoExtn + "_" + timestamp + ".bkp";
                                File.Copy(fileInput, fileBackup, true);
                                _logger.Info("Creating map backup: " + fileBackup);
                            }
                            catch (Exception) {
                                _logger.Error("Unable to generate a map file backup!");
                            }
                        }
                    }

                    if (_settings.FixupTiles)
                    {
                        map.FixupTileLayer();
                    }

                    map.Draw();

                    if (_settings.MarkIceGrowth)
                    {
                        map.MarkIceGrowth();
                    }

                    if (_settings.TunnelPaths)
                    {
                        map.PlotTunnels(_settings.TunnelPosition);
                    }

                    if (_settings.MarkStartPos && (_settings.StartPositionMarking == StartPositionMarking.Squared ||
                                                   _settings.StartPositionMarking == StartPositionMarking.Circled ||
                                                   _settings.StartPositionMarking == StartPositionMarking.Diamond ||
                                                   _settings.StartPositionMarking == StartPositionMarking.Ellipsed ||
                                                   _settings.StartPositionMarking == StartPositionMarking.Starred))
                    {
                        map.DrawStartPositions();
                    }

                    if (_settings.OutputFile == "")
                    {
                        _settings.OutputFile = DetermineMapName(mapFile, _settings.Engine, vfs);
                    }

                    if (_settings.OutputDir == "")
                    {
                        _settings.OutputDir = Path.GetDirectoryName(_settings.InputFile);
                    }

                    if (_settings.DiagnosticWindow)
                    {
                        using (var form = new DebugDrawingSurfaceWindow(map.GetDrawingSurface(), map.GetTiles(),
                                                                        map.GetTheater(), map)) {
                            form.RequestTileEvaluate += map.DebugDrawTile;
                            form.ShowDialog();
                        }
                    }
                }                 // VFS resources can now be released

                // free up as much memory as possible before saving the large images
                Rectangle      saveRect = map.GetSizePixels(_settings.SizeMode);
                DrawingSurface ds       = map.GetDrawingSurface();
                saveRect.Intersect(new Rectangle(0, 0, ds.Width, ds.Height));
                // if we don't need this data anymore, we can try to save some memory
                if (!_settings.GeneratePreviewPack)
                {
                    ds.FreeNonBitmap();
                    map.FreeUseless();
                    GC.Collect();
                }

                if (_settings.SaveJPEG)
                {
                    ds.SaveJPEG(Path.Combine(_settings.OutputDir, _settings.OutputFile + ".jpg"),
                                _settings.JPEGCompression, saveRect);
                }

                if (_settings.SavePNG)
                {
                    ds.SavePNG(Path.Combine(_settings.OutputDir, _settings.OutputFile + ".png"),
                               _settings.PNGQuality, saveRect);
                }

                Regex reThumb = new Regex(@"(\+|)?\((\d+),(\d+)\)");
                var   match   = reThumb.Match(_settings.ThumbnailConfig);
                if (match.Success)
                {
                    Size dimensions = new Size(
                        int.Parse(match.Groups[2].Captures[0].Value),
                        int.Parse(match.Groups[3].Captures[0].Value));
                    var cutRect = map.GetSizePixels(_settings.SizeMode);

                    if (match.Groups[1].Captures[0].Value == "+")
                    {
                        // + means maintain aspect ratio

                        if (dimensions.Width > 0 && dimensions.Height > 0)
                        {
                            float scaleHeight = (float)dimensions.Height / (float)cutRect.Height;
                            float scaleWidth  = (float)dimensions.Width / (float)cutRect.Width;
                            float scale       = Math.Min(scaleHeight, scaleWidth);
                            dimensions.Width  = Math.Max((int)(cutRect.Width * scale), 1);
                            dimensions.Height = Math.Max((int)(cutRect.Height * scale), 1);
                        }
                        else
                        {
                            double aspectRatio = cutRect.Width / (double)cutRect.Height;
                            if (dimensions.Width / (double)dimensions.Height > aspectRatio)
                            {
                                dimensions.Height = (int)(dimensions.Width / aspectRatio);
                            }
                            else
                            {
                                dimensions.Width = (int)(dimensions.Height * aspectRatio);
                            }
                        }
                    }

                    _logger.Info("Saving thumbnail with dimensions {0}x{1}", dimensions.Width, dimensions.Height);

                    if (!_settings.SavePNGThumbnails)
                    {
                        ds.SaveThumb(dimensions, cutRect,
                                     Path.Combine(_settings.OutputDir, "thumb_" + _settings.OutputFile + ".jpg"));
                    }
                    else
                    {
                        ds.SaveThumb(dimensions, cutRect,
                                     Path.Combine(_settings.OutputDir, "thumb_" + _settings.OutputFile + ".png"), true);
                    }
                }

                if (_settings.GeneratePreviewPack || _settings.FixupTiles || _settings.FixOverlays ||
                    _settings.CompressTiles)
                {
                    if (mapFile.BaseStream is MixFile)
                    {
                        _logger.Error(
                            "Cannot fix tile layer or inject thumbnail into an archive (.mmx/.yro/.mix)!");
                    }
                    else
                    {
                        if (_settings.GeneratePreviewPack)
                        {
                            map.GeneratePreviewPack(_settings.PreviewMarkers, _settings.SizeMode, mapFile,
                                                    _settings.FixPreviewDimensions);
                        }

                        if (_settings.FixOverlays)
                        {
                            map.FixupOverlays();                             // fixing is done earlier, it now creates overlay and its data pack
                        }
                        // Keep this last in tiles manipulation
                        if (_settings.CompressTiles)
                        {
                            map.CompressIsoMapPack5();
                        }

                        _logger.Info("Saving map to " + _settings.InputFile);
                        mapFile.Save(_settings.InputFile);
                    }
                }
            }
            catch (Exception exc) {
                _logger.Error(string.Format("An unknown fatal exception occurred: {0}", exc), exc);
#if DEBUG
                throw;
#endif
                return(EngineResult.Exception);
            }
            return(EngineResult.RenderedOk);
        }