Beispiel #1
0
        /// <summary> Save the map, under the specified file name using the specified format. </summary>
        /// <param name="mapToSave"> Map file to be saved. </param>
        /// <param name="fileName">The name of the file to save to. </param>
        /// <param name="mapFormat"> The format to use when saving the map. </param>
        /// <exception cref="ArgumentNullException"> mapToSave or fileName are null. </exception>
        /// <exception cref="ArgumentException"> mapFormat is set to MapFormat.Unknown. </exception>
        /// <exception cref="NoMapConverterFoundException"> No exporter could be found for the given format. </exception>
        /// <exception cref="Exception"> Other kinds of exceptions may be thrown by the map exporter. </exception>
        public static void Save([NotNull] Map mapToSave, [NotNull] string fileName, MapFormat mapFormat)
        {
            if (mapToSave == null)
            {
                throw new ArgumentNullException("mapToSave");
            }
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }
            if (mapFormat == MapFormat.Unknown)
            {
                throw new ArgumentException("Format may not be \"Unknown\"", "mapFormat");
            }

            if (Exporters.ContainsKey(mapFormat))
            {
                IMapExporter converter = Exporters[mapFormat];
                if (converter.SupportsExport)
                {
                    converter.Save(mapToSave, fileName);
                }
            }

            throw new NoMapConverterFoundException("No exporter could be found for the given format.");
        }
Beispiel #2
0
        /// <summary> Attempts to save the map, under the specified filename using the specified format. </summary>
        /// <param name="mapToSave"> Map file to be saved.</param>
        /// <param name="fileName">The name of the file to save to. </param>
        /// <param name="format"> The format to use when saving the map. </param>
        /// <returns> Whether or not the map save completed successfully. </returns>
        /// <exception cref="ArgumentNullException"> If mapToSave or fileName are null. </exception>
        /// <exception cref="ArgumentException"> If format is set to MapFormat.Unknown. </exception>
        /// <exception cref="MapFormatException">  If no converter could be found for the given format. </exception>
        /// <exception cref="NotImplementedException"> If saving to this format is not implemented or supported. </exception>
        public static bool TrySave([NotNull] Map mapToSave, [NotNull] string fileName, MapFormat format)
        {
            if (mapToSave == null)
            {
                throw new ArgumentNullException("mapToSave");
            }
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }
            if (format == MapFormat.Unknown)
            {
                throw new ArgumentException("Format may not be \"Unknown\"", "format");
            }

            if (Exporters.ContainsKey(format))
            {
                IMapExporter converter = Exporters[format];
                if (converter.SupportsExport)
                {
                    try {
                        return(converter.Save(mapToSave, fileName));
                    } catch (Exception ex) {
                        Logger.LogAndReportCrash("Map failed to save", "MapConversion", ex, false);
                        return(false);
                    }
                }
                else
                {
                    throw new NotSupportedException(format + " map converter does not support saving.");
                }
            }

            throw new NoMapConverterFoundException("No converter could be found for the given format.");
        }
Beispiel #3
0
        public static void RegisterConverter(IMapConverter converter)
        {
            IMapImporter asImporter = converter as IMapImporter;
            IMapExporter asExporter = converter as IMapExporter;

            if (asImporter != null)
            {
                Importers.Add(asImporter.Format, asImporter);
            }
            if (asExporter != null)
            {
                Exporters.Add(asExporter.Format, asExporter);
            }
            if (asImporter == null && asExporter == null)
            {
                throw new ArgumentException("Given converter is neither an IMapImporter nor an IMapExporter.");
            }
        }
Beispiel #4
0
        public static int Launch(string[] args)
        {
            ProgramArguments arguments = ProgramArguments.Parse(args);

            if (arguments == null)
            {
                return((int)FailCode.FailedParsingArguments);
            }
            else
            {
                // make sure we have our list of exporters
                Exporters.Load();

                // try to find matching exporters
                IImageExporter imageExporter = null;
                IMapExporter   mapExporter   = null;

                string imageExtension = Path.GetExtension(arguments.image).Substring(1).ToLower();
                foreach (var exporter in Exporters.ImageExporters)
                {
                    if (exporter.ImageExtension.ToLower() == imageExtension)
                    {
                        imageExporter = exporter;
                        break;
                    }
                }

                if (imageExporter == null)
                {
                    Console.WriteLine("Failed to find exporters for specified image type.");
                    return((int)FailCode.ImageExporter);
                }

                if (!string.IsNullOrEmpty(arguments.map))
                {
                    string mapExtension = Path.GetExtension(arguments.map).Substring(1).ToLower();
                    foreach (var exporter in Exporters.MapExporters)
                    {
                        if (exporter.MapExtension.ToLower() == mapExtension)
                        {
                            mapExporter = exporter;
                            break;
                        }
                    }

                    if (mapExporter == null)
                    {
                        Console.WriteLine("Failed to find exporters for specified map type.");
                        return((int)FailCode.MapExporter);
                    }
                }

                // compile a list of images
                List <string> images = new List <string>();
                FindImages(arguments, images);

                // make sure we found some images
                if (images.Count == 0)
                {
                    Console.WriteLine("No images to pack.");
                    return((int)FailCode.NoImages);
                }

                // make sure no images have the same name if we're building a map
                if (mapExporter != null)
                {
                    for (int i = 0; i < images.Count; i++)
                    {
                        string str1 = Path.GetFileNameWithoutExtension(images[i]);

                        for (int j = i + 1; j < images.Count; j++)
                        {
                            string str2 = Path.GetFileNameWithoutExtension(images[j]);

                            if (str1 == str2)
                            {
                                Console.WriteLine("Two images have the same name: {0} = {1}", images[i], images[j]);
                                return((int)FailCode.ImageNameCollision);
                            }
                        }
                    }
                }

                // generate our output
                ImagePacker imagePacker = new ImagePacker();
                Bitmap      outputImage;
                Dictionary <string, Rectangle> outputMap;

                // pack the image, generating a map only if desired
                int result = imagePacker.PackImage(images, arguments.pow2, arguments.sqr, arguments.mw, arguments.mh, arguments.pad, mapExporter != null, out outputImage, out outputMap);
                if (result != 0)
                {
                    Console.WriteLine("There was an error making the image sheet.");
                    return(result);
                }

                // try to save using our exporters
                try
                {
                    if (File.Exists(arguments.image))
                    {
                        File.Delete(arguments.image);
                    }
                    imageExporter.Save(arguments.image, outputImage);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error saving file: " + e.Message);
                    return((int)FailCode.FailedToSaveImage);
                }

                if (mapExporter != null)
                {
                    try
                    {
                        if (File.Exists(arguments.map))
                        {
                            File.Delete(arguments.map);
                        }
                        mapExporter.Save(arguments.map, outputMap);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error saving file: " + e.Message);
                        return((int)FailCode.FailedToSaveMap);
                    }
                }
            }

            return(0);
        }
Beispiel #5
0
        protected override bool Setup()
        {
            ReadConfigs();
            CreateTasks();

            mMapExporter = new GorgonMapExporter()
            {
                atlasHeight = 4096, atlasWidth = 4096
            };
            mImageExporter = new PngImageExporter();

            var setup = base.Setup();
            var ptr   = TextureManager.Singleton.CreateManual("RttTex",
                                                              ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME,
                                                              TextureType.TEX_TYPE_2D,
                                                              148,
                                                              148,
                                                              0,
                                                              PixelFormat.PF_R8G8B8A8,
                                                              (int)TextureUsage.TU_RENDERTARGET
                                                              );

            mRTT  = ptr.GetBuffer().GetRenderTarget();
            mRTVP = mRTT.AddViewport(mCamera);
            mRTVP.BackgroundColour = new ColourValue(0, 0, 0, 0);
            mRTVP.SetClearEveryFrame(true);
            mRTVP.OverlaysEnabled = false;

            //Calculate diagonal distance value
            //mPythDistance = (mDistance / Mogre.Math.Sqrt(2));

            var altitude = new Degree(mCameraAngle);
            var angles   = new float[] {
                180f,  // South
                135f,  // Southeast
                90f,   // East
                45f,   // Northeast
                0f,    // North
                -45f,  // Northwest
                -90f,  // West
                -135f, // Southwest
            };

            mCameraDirections = new List <string> {
                "s",
                "se",
                "e",
                "ne",
                "n",
                "nw",
                "w",
                "sw"
            };
            mCameraPositions = new List <Vector3>();
            for (var i = 0; i < 8; i++)
            {
                float   azimuth = angles[i];
                string  dirname = mCameraDirections[i];
                Vector3 pos     = getPosOnSphere(mDistance, new Degree(-azimuth), -altitude);
                mCameraPositions.Add(pos);
                Console.WriteLine("Determined camera pos: {0,2} is {1,5:F2},{2,5:F2},{3,5:F2}", dirname, pos.x, pos.y, pos.z);
            }

            /*
             * mCameraPositions = new List<Vector3> {
             *  new Vector3(0, mDistance, mDistance),                   // Front / South
             *  new Vector3(-mPythDistance, mDistance, mPythDistance),  // Front-right / southwest
             *  new Vector3(-mDistance, mDistance, 0),                  // Right / west
             *  new Vector3(-mPythDistance, mDistance, -mPythDistance), // Back-right / northwest
             *  new Vector3(0, mDistance, -mDistance),                  // Back / north
             *  new Vector3(mPythDistance, mDistance, -mPythDistance),  // Back-left / northeast
             *  new Vector3(mDistance, mDistance, 0),                   // Left / east
             *  new Vector3(mPythDistance, mDistance, mPythDistance),   // Front-left / southeast
             * };
             */



            //CompositorManager.Singleton.AddCompositor(vp, "EdgeDetectCompositor", 0);
            //CompositorManager.Singleton.AddCompositor(rtvp, "EdgeDetectCompositor", 0);
            //CompositorManager.Singleton.SetCompositorEnabled(vp, "EdgeDetectCompositor", true);
            //CompositorManager.Singleton.SetCompositorEnabled(rtvp, "EdgeDetectCompositor", true);

            /*CompositorManager.Singleton.AddCompositor(vp, "Pixelate", 0);
             * CompositorManager.Singleton.AddCompositor(mRTVP, "Pixelate", 0);
             * CompositorManager.Singleton.SetCompositorEnabled(vp, "Pixelate", true);
             * CompositorManager.Singleton.SetCompositorEnabled(mRTVP, "Pixelate", true);*/

            //CompositorManager.Singleton.AddCompositor(vp, "Normal", 0);
            //CompositorManager.Singleton.AddCompositor(rtvp, "Normal", 0);
            //CompositorManager.Singleton.SetCompositorEnabled(vp, "Normal", true);
            //CompositorManager.Singleton.SetCompositorEnabled(rtvp, "Normal", true);

            //CompositorManager.Singleton.AddCompositor(vp, "SMAA", 0);
            //CompositorManager.Singleton.AddCompositor(rtvp, "SMAA", 0);
            //CompositorManager.Singleton.SetCompositorEnabled(vp, "SMAA", true);
            //CompositorManager.Singleton.SetCompositorEnabled(rtvp, "SMAA", true);

            //CompositorManager.Singleton.AddCompositor(vp, "FXAA", 0);
            //CompositorManager.Singleton.AddCompositor(rtvp, "FXAA", 0);
            //CompositorManager.Singleton.SetCompositorEnabled(vp, "FXAA", true);
            //CompositorManager.Singleton.SetCompositorEnabled(rtvp, "FXAA", true);

            //Set up task scheduler
            imageTrimScheduler   = new LimitedConcurrencyLevelTaskScheduler(3);
            imageTrimTaskFactory = new TaskFactory(imageTrimScheduler);
            imagePackScheduler   = new LimitedConcurrencyLevelTaskScheduler(1);
            imagePackTaskFactory = new TaskFactory(imagePackScheduler);
            return(setup);
        }
Beispiel #6
0
        protected override bool Setup()
        {
            ReadConfigs();
            CreateTasks();

            mMapExporter = new GorgonMapExporter() { atlasHeight = 4096, atlasWidth = 4096 };
            mImageExporter = new PngImageExporter();

            var setup = base.Setup();
            var ptr = TextureManager.Singleton.CreateManual("RttTex",
                                                            ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME,
                                                            TextureType.TEX_TYPE_2D,
                                                            148,
                                                            148,
                                                            0,
                                                            PixelFormat.PF_R8G8B8A8,
                                                            (int)TextureUsage.TU_RENDERTARGET
                );
            mRTT = ptr.GetBuffer().GetRenderTarget();
            mRTVP = mRTT.AddViewport(mCamera);
            mRTVP.BackgroundColour = new ColourValue(0, 0, 0, 0);
            mRTVP.SetClearEveryFrame(true);
            mRTVP.OverlaysEnabled = false;

            //Calculate diagonal distance value
            //mPythDistance = (mDistance / Mogre.Math.Sqrt(2));

            var altitude = new Degree(mCameraAngle);
            var angles = new float[]{
                180f, // South
                135f, // Southeast
                 90f, // East
                 45f, // Northeast
                  0f, // North
                -45f, // Northwest
                -90f, // West
               -135f, // Southwest
            };
            mCameraDirections = new List<string> {
                "s",
                "se",
                "e",
                "ne",
                "n",
                "nw",
                "w",
                "sw"
            };
            mCameraPositions = new List<Vector3>();
            for (var i = 0; i < 8; i++)
            {
                float azimuth = angles[i];
                string dirname = mCameraDirections[i];
                Vector3 pos = getPosOnSphere(mDistance, new Degree(-azimuth), -altitude);
                mCameraPositions.Add(pos);
                Console.WriteLine("Determined camera pos: {0,2} is {1,5:F2},{2,5:F2},{3,5:F2}", dirname, pos.x, pos.y, pos.z);
            }
            /*
            mCameraPositions = new List<Vector3> {
                new Vector3(0, mDistance, mDistance),                   // Front / South
                new Vector3(-mPythDistance, mDistance, mPythDistance),  // Front-right / southwest
                new Vector3(-mDistance, mDistance, 0),                  // Right / west
                new Vector3(-mPythDistance, mDistance, -mPythDistance), // Back-right / northwest
                new Vector3(0, mDistance, -mDistance),                  // Back / north
                new Vector3(mPythDistance, mDistance, -mPythDistance),  // Back-left / northeast
                new Vector3(mDistance, mDistance, 0),                   // Left / east
                new Vector3(mPythDistance, mDistance, mPythDistance),   // Front-left / southeast
            };
            */

            //CompositorManager.Singleton.AddCompositor(vp, "EdgeDetectCompositor", 0);
            //CompositorManager.Singleton.AddCompositor(rtvp, "EdgeDetectCompositor", 0);
            //CompositorManager.Singleton.SetCompositorEnabled(vp, "EdgeDetectCompositor", true);
            //CompositorManager.Singleton.SetCompositorEnabled(rtvp, "EdgeDetectCompositor", true);

            /*CompositorManager.Singleton.AddCompositor(vp, "Pixelate", 0);
            CompositorManager.Singleton.AddCompositor(mRTVP, "Pixelate", 0);
            CompositorManager.Singleton.SetCompositorEnabled(vp, "Pixelate", true);
            CompositorManager.Singleton.SetCompositorEnabled(mRTVP, "Pixelate", true);*/

            //CompositorManager.Singleton.AddCompositor(vp, "Normal", 0);
            //CompositorManager.Singleton.AddCompositor(rtvp, "Normal", 0);
            //CompositorManager.Singleton.SetCompositorEnabled(vp, "Normal", true);
            //CompositorManager.Singleton.SetCompositorEnabled(rtvp, "Normal", true);

            //CompositorManager.Singleton.AddCompositor(vp, "SMAA", 0);
            //CompositorManager.Singleton.AddCompositor(rtvp, "SMAA", 0);
            //CompositorManager.Singleton.SetCompositorEnabled(vp, "SMAA", true);
            //CompositorManager.Singleton.SetCompositorEnabled(rtvp, "SMAA", true);

            //CompositorManager.Singleton.AddCompositor(vp, "FXAA", 0);
            //CompositorManager.Singleton.AddCompositor(rtvp, "FXAA", 0);
            //CompositorManager.Singleton.SetCompositorEnabled(vp, "FXAA", true);
            //CompositorManager.Singleton.SetCompositorEnabled(rtvp, "FXAA", true);

            //Set up task scheduler
            imageTrimScheduler = new LimitedConcurrencyLevelTaskScheduler(3);
            imageTrimTaskFactory = new TaskFactory(imageTrimScheduler);
            imagePackScheduler = new LimitedConcurrencyLevelTaskScheduler(1);
            imagePackTaskFactory = new TaskFactory(imagePackScheduler);
            return setup;
        }
Beispiel #7
0
        static int Main( string[] args ) {
            Logger.Logged += OnLogged;

            ReturnCode optionParsingResult = ParseOptions( args );
            if( optionParsingResult != ReturnCode.Success ) {
                return (int)optionParsingResult;
            }

            // parse importer name
            if( importerName != null && !importerName.Equals( "auto", StringComparison.OrdinalIgnoreCase ) ) {
                MapFormat importFormat;
                if( !EnumUtil.TryParse( importerName, out importFormat, true )  ) {
                    Console.Error.WriteLine( "Unsupported importer \"{0}\"", importerName );
                    PrintUsage();
                    return (int)ReturnCode.UnrecognizedImporter;
                }
                importer = MapUtility.GetImporter( importFormat );
                if( importer == null ) {
                    Console.Error.WriteLine( "Loading from \"{0}\" is not supported", importFormat );
                    PrintUsage();
                    return (int)ReturnCode.UnsupportedLoadFormat;
                }
            }

            // parse exporter format
            MapFormat exportFormat;
            if( !EnumUtil.TryParse( exporterName, out exportFormat, true ) ) {
                Console.Error.WriteLine( "Unrecognized exporter \"{0}\"", exporterName );
                PrintUsage();
                return (int)ReturnCode.UnrecognizedExporter;
            }

            exporter = MapUtility.GetExporter( exportFormat );
            if( exporter == null ) {
                Console.Error.WriteLine( "Saving to \"{0}\" is not supported", exportFormat );
                PrintUsage();
                return (int)ReturnCode.UnsupportedSaveFormat;
            }

            // check if input path exists, and if it's a file or directory
            bool directoryMode;
            try {
                if( File.Exists( inputPath ) ) {
                    directoryMode = false;
                    if( outputDirName == null ) {
                        outputDirName = Paths.GetDirectoryNameOrRoot( inputPath );
                    }

                } else if( Directory.Exists( inputPath ) ) {
                    directoryMode = true;
                    if( outputDirName == null ) {
                        outputDirName = Paths.GetDirectoryNameOrRoot( inputPath );
                    }

                } else {
                    Console.Error.WriteLine( "MapConverter: Cannot locate \"{0}\"", inputPath );
                    return (int)ReturnCode.InputDirNotFound;
                }

                if( !Directory.Exists( outputDirName ) ) {
                    Directory.CreateDirectory( outputDirName );
                }

            } catch( Exception ex ) {
                Console.Error.WriteLine( "MapConverter: {0}: {1}",
                                         ex.GetType().Name,
                                         ex.Message );
                return (int)ReturnCode.PathError;
            }

            // check recursive flag
            if( recursive && !directoryMode ) {
                Console.Error.WriteLine( "MapConverter: Recursive flag is given, but input is not a directory." );
            }

            // check input filter
            if( inputFilter != null && !directoryMode ) {
                Console.Error.WriteLine( "MapConverter: Filter param is given, but input is not a directory." );
            }

            if( !recursive && importer != null && importer.StorageType == MapStorageType.Directory ) {
                // single-directory conversion
                ConvertOneMap( new DirectoryInfo( inputPath ) );

            } else if( !directoryMode ) {
                // single-file conversion
                ConvertOneMap( new FileInfo( inputPath ) );

            } else {
                // possible single-directory conversion
                if( !recursive && ConvertOneMap( new DirectoryInfo( inputPath ) ) ) {
                    return (int)ReturnCode.Success;
                }

                // otherwise, go through all files inside the given directory
                SearchOption recursiveOption = ( recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly );
                DirectoryInfo inputDirInfo = new DirectoryInfo( inputPath );
                if( inputFilter == null ) inputFilter = "*";
                foreach( var dir in inputDirInfo.GetDirectories( inputFilter, recursiveOption ) ) {
                    ConvertOneMap( dir );
                }
                foreach( var file in inputDirInfo.GetFiles( inputFilter, recursiveOption ) ) {
                    ConvertOneMap( file );
                }
            }

            return (int)ReturnCode.Success;
        }
Beispiel #8
0
        static int Main( string[] args ) {
            Logger.Logged += OnLogged;
            Logger.DisableFileLogging();

            ReturnCode optionParsingResult = ParseOptions( args );
            if( optionParsingResult != ReturnCode.Success ) {
                return (int)optionParsingResult;
            }

            // parse importer name
            if( importerName != null && !importerName.Equals( "auto", StringComparison.OrdinalIgnoreCase ) ) {
                MapFormat importFormat;
                if( !EnumUtil.TryParse( importerName, out importFormat, true ) ) {
                    Console.Error.WriteLine( "MapConverter: Unsupported importer \"{0}\"", importerName );
                    PrintUsage();
                    return (int)ReturnCode.UnrecognizedImporter;
                }
                importer = MapUtility.GetImporter( importFormat );
                if( importer == null ) {
                    Console.Error.WriteLine( "MapConverter: Loading from \"{0}\" is not supported", importFormat );
                    PrintUsage();
                    return (int)ReturnCode.UnsupportedLoadFormat;
                }
            }

            // parse exporter format
            MapFormat exportFormat;
            if( !EnumUtil.TryParse( exporterName, out exportFormat, true ) ) {
                Console.Error.WriteLine( "MapConverter: Unrecognized exporter \"{0}\"", exporterName );
                PrintUsage();
                return (int)ReturnCode.UnrecognizedExporter;
            }
            exporter = MapUtility.GetExporter( exportFormat );
            if( exporter == null ) {
                Console.Error.WriteLine( "MapConverter: Saving to \"{0}\" is not supported", exportFormat );
                PrintUsage();
                return (int)ReturnCode.UnsupportedSaveFormat;
            }

            // check input paths
            bool hadFile = false,
                 hadDir = false;
            foreach( string inputPath in inputPathList ) {
                if( hadDir ) {
                    Console.Error.WriteLine( "MapConverter: Only one directory may be specified at a time." );
                    return (int)ReturnCode.ArgumentError;
                }
                // check if input path exists, and if it's a file or directory
                try {
                    if( File.Exists( inputPath ) ) {
                        hadFile = true;
                    } else if( Directory.Exists( inputPath ) ) {
                        hadDir = true;
                        if( hadFile ) {
                            Console.Error.WriteLine( "MapConverter: Cannot mix directories and files in input." );
                            return (int)ReturnCode.ArgumentError;
                        }
                        directoryMode = true;
                        if( !outputDirGiven ) {
                            outputDirName = inputPath;
                        }
                    } else {
                        Console.Error.WriteLine( "MapConverter: Cannot locate \"{0}\"", inputPath );
                        return (int)ReturnCode.InputPathNotFound;
                    }
                } catch( Exception ex ) {
                    Console.Error.WriteLine( "MapConverter: {0}: {1}",
                                             ex.GetType().Name,
                                             ex.Message );
                    return (int)ReturnCode.PathError;
                }
            }

            // check recursive flag
            if( recursive && !directoryMode ) {
                Console.Error.WriteLine( "MapConverter: Recursive flag is given, but input is not a directory." );
                return (int)ReturnCode.ArgumentError;
            }

            // check input filter
            if( inputFilter != null && !directoryMode ) {
                Console.Error.WriteLine( "MapConverter: Filter param is given, but input is not a directory." );
                return (int)ReturnCode.ArgumentError;
            }

            // check regex filter
            if( useRegex ) {
                try {
                    filterRegex = new Regex( inputFilter );
                } catch( ArgumentException ex ) {
                    Console.Error.WriteLine( "MapConverter: Cannot parse filter regex: {0}",
                                             ex.Message );
                    return (int)ReturnCode.ArgumentError;
                }
            }

            // check if output dir exists; create it if needed
            if( outputDirName != null ) {
                try {
                    if( !Directory.Exists( outputDirName ) ) {
                        Directory.CreateDirectory( outputDirName );
                    }
                } catch( Exception ex ) {
                    Console.Error.WriteLine( "MapRenderer: Error checking output directory: {0}: {1}",
                                             ex.GetType().Name,
                                             ex.Message );
                }
            }

            // process inputs, one path at a time
            foreach( string inputPath in inputPathList ) {
                ReturnCode code = ProcessInputPath( inputPath );
                if( code != ReturnCode.Success ) {
                    return (int)code;
                }
            }
            return (int)ReturnCode.Success;
        }
Beispiel #9
0
        static int Main(string[] args)
        {
            Logger.Logged += OnLogged;
            Logger.DisableFileLogging();

            ReturnCode optionParsingResult = ParseOptions(args);

            if (optionParsingResult != ReturnCode.Success)
            {
                return((int)optionParsingResult);
            }

            // parse importer name
            if (importerName != null && !importerName.Equals("auto", StringComparison.OrdinalIgnoreCase))
            {
                MapFormat importFormat;
                if (!EnumUtil.TryParse(importerName, out importFormat, true))
                {
                    Console.Error.WriteLine("MapConverter: Unsupported importer \"{0}\"", importerName);
                    PrintUsage();
                    return((int)ReturnCode.UnrecognizedImporter);
                }
                importer = MapUtility.GetImporter(importFormat);
                if (importer == null)
                {
                    Console.Error.WriteLine("MapConverter: Loading from \"{0}\" is not supported", importFormat);
                    PrintUsage();
                    return((int)ReturnCode.UnsupportedLoadFormat);
                }
            }

            // parse exporter format
            MapFormat exportFormat;

            if (!EnumUtil.TryParse(exporterName, out exportFormat, true))
            {
                Console.Error.WriteLine("MapConverter: Unrecognized exporter \"{0}\"", exporterName);
                PrintUsage();
                return((int)ReturnCode.UnrecognizedExporter);
            }
            exporter = MapUtility.GetExporter(exportFormat);
            if (exporter == null)
            {
                Console.Error.WriteLine("MapConverter: Saving to \"{0}\" is not supported", exportFormat);
                PrintUsage();
                return((int)ReturnCode.UnsupportedSaveFormat);
            }

            // check input paths
            bool hadFile = false,
                 hadDir  = false;

            foreach (string inputPath in inputPathList)
            {
                if (hadDir)
                {
                    Console.Error.WriteLine("MapConverter: Only one directory may be specified at a time.");
                    return((int)ReturnCode.ArgumentError);
                }
                // check if input path exists, and if it's a file or directory
                try {
                    if (File.Exists(inputPath))
                    {
                        hadFile = true;
                    }
                    else if (Directory.Exists(inputPath))
                    {
                        hadDir = true;
                        if (hadFile)
                        {
                            Console.Error.WriteLine("MapConverter: Cannot mix directories and files in input.");
                            return((int)ReturnCode.ArgumentError);
                        }
                        directoryMode = true;
                        if (!outputDirGiven)
                        {
                            outputDirName = inputPath;
                        }
                    }
                    else
                    {
                        Console.Error.WriteLine("MapConverter: Cannot locate \"{0}\"", inputPath);
                        return((int)ReturnCode.InputPathNotFound);
                    }
                } catch (Exception ex) {
                    Console.Error.WriteLine("MapConverter: {0}: {1}",
                                            ex.GetType().Name,
                                            ex.Message);
                    return((int)ReturnCode.PathError);
                }
            }

            // check recursive flag
            if (recursive && !directoryMode)
            {
                Console.Error.WriteLine("MapConverter: Recursive flag is given, but input is not a directory.");
                return((int)ReturnCode.ArgumentError);
            }

            // check input filter
            if (inputFilter != null && !directoryMode)
            {
                Console.Error.WriteLine("MapConverter: Filter param is given, but input is not a directory.");
                return((int)ReturnCode.ArgumentError);
            }

            // check regex filter
            if (useRegex)
            {
                try {
                    filterRegex = new Regex(inputFilter);
                } catch (ArgumentException ex) {
                    Console.Error.WriteLine("MapConverter: Cannot parse filter regex: {0}",
                                            ex.Message);
                    return((int)ReturnCode.ArgumentError);
                }
            }

            // check if output dir exists; create it if needed
            if (outputDirName != null)
            {
                try {
                    if (!Directory.Exists(outputDirName))
                    {
                        Directory.CreateDirectory(outputDirName);
                    }
                } catch (Exception ex) {
                    Console.Error.WriteLine("MapRenderer: Error checking output directory: {0}: {1}",
                                            ex.GetType().Name,
                                            ex.Message);
                }
            }

            // process inputs, one path at a time
            foreach (string inputPath in inputPathList)
            {
                ReturnCode code = ProcessInputPath(inputPath);
                if (code != ReturnCode.Success)
                {
                    return((int)code);
                }
            }
            return((int)ReturnCode.Success);
        }
Beispiel #10
0
        static int Main(string[] args)
        {
            Logger.Logged += OnLogged;

            ReturnCode optionParsingResult = ParseOptions(args);

            if (optionParsingResult != ReturnCode.Success)
            {
                return((int)optionParsingResult);
            }

            // parse importer name
            if (importerName != null && !importerName.Equals("auto", StringComparison.OrdinalIgnoreCase))
            {
                MapFormat importFormat;
                if (!EnumUtil.TryParse(importerName, out importFormat, true) ||
                    (importer = MapUtility.GetImporter(importFormat)) == null)
                {
                    Console.Error.WriteLine("Unsupported importer \"{0}\"", importerName);
                    PrintUsage();
                    return((int)ReturnCode.UnrecognizedImporter);
                }
            }

            // parse exporter format
            MapFormat exportFormat;

            if (!EnumUtil.TryParse(exporterName, out exportFormat, true) ||
                (exporter = MapUtility.GetExporter(exportFormat)) == null)
            {
                Console.Error.WriteLine("Unsupported exporter \"{0}\"", exporterName);
                PrintUsage();
                return((int)ReturnCode.UnrecognizedExporter);
            }

            // check if input path exists, and if it's a file or directory
            bool directoryMode;

            try {
                if (File.Exists(inputPath))
                {
                    directoryMode = false;
                    if (outputDirName == null)
                    {
                        outputDirName = Paths.GetDirectoryNameOrRoot(inputPath);
                    }
                }
                else if (Directory.Exists(inputPath))
                {
                    directoryMode = true;
                    if (outputDirName == null)
                    {
                        outputDirName = Paths.GetDirectoryNameOrRoot(inputPath);
                    }
                }
                else
                {
                    Console.Error.WriteLine("MapConverter: Cannot locate \"{0}\"", inputPath);
                    return((int)ReturnCode.InputDirNotFound);
                }

                if (!Directory.Exists(outputDirName))
                {
                    Directory.CreateDirectory(outputDirName);
                }
            } catch (Exception ex) {
                Console.Error.WriteLine("MapConverter: {0}: {1}",
                                        ex.GetType().Name,
                                        ex.Message);
                return((int)ReturnCode.PathError);
            }

            // check recursive flag
            if (recursive && !directoryMode)
            {
                Console.Error.WriteLine("MapConverter: Recursive flag is given, but input is not a directory.");
            }

            // check input filter
            if (inputFilter != null && !directoryMode)
            {
                Console.Error.WriteLine("MapConverter: Filter param is given, but input is not a directory.");
            }

            if (!recursive && importer != null && importer.StorageType == MapStorageType.Directory)
            {
                // single-directory conversion
                ConvertOneMap(new DirectoryInfo(inputPath));
            }
            else if (!directoryMode)
            {
                // single-file conversion
                ConvertOneMap(new FileInfo(inputPath));
            }
            else
            {
                // possible single-directory conversion
                if (!recursive && ConvertOneMap(new DirectoryInfo(inputPath)))
                {
                    return((int)ReturnCode.Success);
                }

                // otherwise, go through all files inside the given directory
                SearchOption  recursiveOption = (recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
                DirectoryInfo inputDirInfo    = new DirectoryInfo(inputPath);
                if (inputFilter == null)
                {
                    inputFilter = "*";
                }
                foreach (var dir in inputDirInfo.GetDirectories(inputFilter, recursiveOption))
                {
                    ConvertOneMap(dir);
                }
                foreach (var file in inputDirInfo.GetFiles(inputFilter, recursiveOption))
                {
                    ConvertOneMap(file);
                }
            }

            return((int)ReturnCode.Success);
        }
Beispiel #11
0
        public static void Launch(string dir)
        {
            // make sure we have our list of exporters
            Exporters.Exporters.Load();

            // try to find matching exporters
            IImageExporter imageExporter = null;
            IMapExporter   mapExporter   = null;

            string imageExtension = "png";

            foreach (var exporter in Exporters.Exporters.ImageExporters)
            {
                if (exporter.ImageExtension.ToLower() == imageExtension)
                {
                    imageExporter = exporter;
                    break;
                }
            }

            string mapExtension = "txt";

            foreach (var exporter in Exporters.Exporters.MapExporters)
            {
                if (exporter.MapExtension.ToLower() == mapExtension)
                {
                    mapExporter = exporter;
                    break;
                }
            }

            // compile a list of images
            List <string> images         = new List <string>();
            List <string> images_lowres  = new List <string>();
            List <string> images_highres = new List <string>();

            foreach (string str in Directory.GetFiles(dir, "*.png"))
            {
                if (str.EndsWith(".small.png"))
                {
                    images_lowres.Add(str.Substring(str.LastIndexOf(@"\") + 1).Replace(".small.png", ""));
                }
                else
                {
                    images.Add(str);
                }
            }

            if (Directory.Exists(dir + "_huge"))
            {
                foreach (string str in Directory.GetFiles(dir + "_huge", "*.png"))
                {
                    images_highres.Add(str.Substring(str.LastIndexOf(@"\") + 1).Replace(".png", ""));
                }
            }

            // generate our output
            ImagePacker imagePacker = new ImagePacker();
            Bitmap      outputImage;
            Dictionary <string, Rectangle> outputMap;

            // pack the image, generating a map only if desired
            int result = imagePacker.PackImage(images, true, false, 2048, 2048, 2, true, out outputImage, out outputMap);

            string sheetName = dir.Substring(dir.LastIndexOf(@"/") + 1);

            Bitmap   bmpLowres = new Bitmap(outputImage, new Size(outputImage.Width / 2, outputImage.Height / 2));
            Graphics gfxLowres = Graphics.FromImage(bmpLowres);

            gfxLowres.CompositingMode = CompositingMode.SourceCopy;

            Bitmap   bmpHighres = new Bitmap(outputImage, new Size(outputImage.Width * 2, outputImage.Height * 2));
            Graphics gfxHighres = Graphics.FromImage(bmpHighres);

            gfxHighres.CompositingMode = CompositingMode.SourceCopy;

            foreach (var m in outputMap)
            {
                if (m.Value.Width % 2 != 0)
                {
                    Console.WriteLine("FATAL: width of " + m.Key + " is not div 2");
                }
                if (m.Value.Height % 2 != 0)
                {
                    Console.WriteLine("FATAL: width of " + m.Key + " is not div 2");
                }

                string spriteName = m.Key.Substring(m.Key.LastIndexOf(@"\") + 1).Replace(".png", "");

                if (images_lowres.Contains(spriteName))
                {
                    Bitmap spriteLowres = Bitmap.FromFile(m.Key.Replace(".png", ".small.png")) as Bitmap;
                    gfxLowres.DrawImageUnscaledAndClipped(spriteLowres, new Rectangle(m.Value.X / 2, m.Value.Y / 2, m.Value.Width / 2, m.Value.Height / 2));
                }

                Brush transparentBrush = new SolidBrush(Color.Transparent);

                if (images_highres.Contains(spriteName))
                {
                    Bitmap spriteHighres = Bitmap.FromFile(dir + "_huge\\" + spriteName + ".png") as Bitmap;

                    if (spriteHighres.Width != m.Value.Width * 2 || spriteHighres.Height != m.Value.Height * 2)
                    {
                        Console.WriteLine("FATAL: dimensions of high res sprite " + m.Key + " do not match!");
                    }

                    // wipe away any sprite gunk that bled into the padding region from the upscale.
                    gfxHighres.FillRectangle(transparentBrush, new Rectangle(m.Value.X * 2 - 4, m.Value.Y * 2 - 4, m.Value.Width * 2 + 8, m.Value.Height * 2 + 8));
                    gfxHighres.DrawImageUnscaledAndClipped(spriteHighres, new Rectangle(m.Value.X * 2, m.Value.Y * 2, m.Value.Width * 2, m.Value.Height * 2));
                }

                sb.AppendFormat("            textureLocations.Add(OsuTexture.{0}, new SpriteSheetTexture(\"{1}\", {2}, {3}, {4}, {5}));\r\n",
                                spriteName, sheetName, m.Value.Left, m.Value.Top, m.Value.Width, m.Value.Height);
            }

            if (result != 0)
            {
                Console.WriteLine("There was an error making the image sheet for " + dir);
                return;
            }

            if (File.Exists(dir))
            {
                File.Delete(dir);
            }

            imageExporter.Save(dir + "_960.png", outputImage);
            bmpLowres.Save(dir + "_480.png", ImageFormat.Png);
            bmpHighres.Save(dir + "_1920.png", ImageFormat.Png);
        }