コード例 #1
0
        private static int Launch(Atlas args)
        {
            if (args.AtlasFile.Equals(""))
            {
                return((int)FailCode.FailedParsingArguments);
            }
            else
            {
                // make sure we found some images
                if (args.TextureList.Count == 0)
                {
                    Logging.Manager("No images to pack for " + args.AtlasFile);
                    return((int)FailCode.NoImages);
                }

                // generate our output
                ImagePacker imagePacker = new ImagePacker();

                // Logging.Manager("try to add " + args.TextureList.Count + " images to atlas file " + args.AtlasFile);

                // pack the image, generating a map only if desired
                int result = imagePacker.PackImage(args.TextureList, args.PowOf2, args.Square, args.FastImagePacker, args.AtlasWidth, args.AtlasHeight, args.Padding, args.mapExporter != null, out Bitmap outputImage, out Dictionary <string, Rectangle> outputMap);
                if (result != 0)
                {
                    Logging.Manager("There was an error making the image sheet.");
                    //error result 7 = "failed to pack image" most likely it won't fit
                    return(result);
                }
                else
                {
                    Logging.Manager(string.Format("Packing '{0}' to {1} x {2} pixel", Path.GetFileName(args.AtlasFile), outputImage.Height, outputImage.Width));
                }

                // try to save using our exporters
                try
                {
                    if (File.Exists(args.AtlasFile))
                    {
                        File.Delete(args.AtlasFile);
                    }
                    if (args.imageHandler.Save(args.AtlasFile, outputImage))
                    {
                        Logging.Manager("successfully created Atlas image: " + args.AtlasFile);
                    }
                    Logging.InstallerGroup("created Atlases");                                              // write comment
                    Logging.Installer(Utils.ReplaceDirectorySeparatorChar(args.AtlasFile));                 // write created filename with path
                }
                catch (Exception e)
                {
                    Logging.Manager("Error saving file: " + e.Message);
                    return((int)FailCode.FailedToSaveImage);
                }

                if (args.mapExporter != null)
                {
                    try
                    {
                        if (File.Exists(args.MapFile))
                        {
                            File.Delete(args.MapFile);
                        }
                        args.mapExporter.Save(args.MapFile, outputMap);
                        Logging.Installer(Utils.ReplaceDirectorySeparatorChar(args.MapFile));                 // write created filename with path
                    }
                    catch (Exception e)
                    {
                        Logging.Manager("Error saving file: " + e.Message);
                        return((int)FailCode.FailedToSaveMap);
                    }
                }
            }
            return(0);
        }
コード例 #2
0
        /// <summary>
        /// Create the atlas image
        /// </summary>
        /// <returns>Success code if complete, any other FailCode otherwise</returns>
        public FailCode CreateAtlas()
        {
            //input checks
            if (Atlas == null)
            {
                throw new BadMemeException("you forgot to set the atlas object. nice.");
            }

            //create the save directory if it does not already exist
            if (!Directory.Exists(Atlas.AtlasSaveDirectory))
            {
                Directory.CreateDirectory(Atlas.AtlasSaveDirectory);
            }

            //set the mapfile name
            Atlas.MapFile = string.Format("{0}.xml", Path.GetFileNameWithoutExtension(Atlas.AtlasFile));
            Logging.Debug("[atlas file {0}]: set map name as {1}", Path.GetFileName(Atlas.AtlasFile), Path.GetFileName(Atlas.MapFile));

            //set location to extract original WG atlas files
            tempAtlasImageFile = Path.Combine(Settings.RelhaxTempFolderPath, Atlas.AtlasFile);
            tempAtlasMapFile   = Path.Combine(Settings.RelhaxTempFolderPath, Atlas.MapFile);

            //delete the temp files if they exist
            if (File.Exists(tempAtlasImageFile))
            {
                File.Delete(tempAtlasImageFile);
            }
            if (File.Exists(tempAtlasMapFile))
            {
                File.Delete(tempAtlasMapFile);
            }

            //extract the map and atlas files
            Logging.Info("[atlas file {0}]: unpack of atlas and map starting", Path.GetFileName(Atlas.AtlasFile));
            stopwatch.Restart();
            Logging.Debug("[atlas file {0}]: atlas file unpack", Path.GetFileName(Atlas.AtlasFile));
            lock (AtlasUtils.AtlasLoaderLockObject)
            {
                Utils.Unpack(Atlas.Pkg, Path.Combine(Atlas.DirectoryInArchive, Atlas.AtlasFile), tempAtlasImageFile);
            }
            OnAtlasProgres?.Invoke(this, null);
            Token.ThrowIfCancellationRequested();

            Logging.Debug("[atlas file {0}]: map file unpack", Path.GetFileName(Atlas.AtlasFile));
            lock (AtlasUtils.AtlasLoaderLockObject)
            {
                Utils.Unpack(Atlas.Pkg, Path.Combine(Atlas.DirectoryInArchive, Atlas.MapFile), tempAtlasMapFile);
            }
            OnAtlasProgres?.Invoke(this, null);
            Token.ThrowIfCancellationRequested();

            stopwatch.Stop();
            Logging.Info("[atlas file {0}]: unpack completed in {1} msec", Path.GetFileName(Atlas.AtlasFile), stopwatch.ElapsedMilliseconds);
            stopwatch.Restart();

            //parse the xml map file into the list of subtextures
            Logging.Info("[atlas file {0}]: parsing map file", Path.GetFileName(Atlas.AtlasFile));
            Logging.Debug("[atlas file {0}]: using map file {1}", Path.GetFileName(Atlas.AtlasFile), tempAtlasMapFile);
            Atlas.TextureList = LoadMapFile(tempAtlasMapFile);
            OnAtlasProgres?.Invoke(this, null);

            //using the parsed size and location definitions from above, copy each individual subtexture to the texture list
            Size originalAtlasSize = new Size();

            Logging.Info("[atlas file {0}]: loading atlas to bitmap data", Path.GetFileName(Atlas.AtlasFile));
            Logging.Debug("[atlas file {0}]: using atlas file {1}", Path.GetFileName(Atlas.AtlasFile), tempAtlasImageFile);
            stopwatch.Restart();
            lock (AtlasUtils.AtlasLoaderLockObject)
            {
                //the native library can only be used once at a time
                atlasImage = LoadDDS(tempAtlasImageFile);
            }
            OnAtlasProgres?.Invoke(this, null);
            Token.ThrowIfCancellationRequested();

            //get the size from grumpel code
            originalAtlasSize = atlasImage.Size;

            //copy the subtexture bitmap data to each texture bitmap data
            Logging.Info("[atlas file {0}]: parsing bitmap data", Path.GetFileName(Atlas.AtlasFile));
            lock (AtlasUtils.AtlasLoaderLockObject)
            {
                //lock the atlas image into memory
                Rectangle  rect      = new Rectangle(0, 0, atlasImage.Width, atlasImage.Height);
                BitmapData atlasLock = atlasImage.LockBits(rect, ImageLockMode.ReadOnly, atlasImage.PixelFormat);
                foreach (Texture texture in Atlas.TextureList)
                {
                    Token.ThrowIfCancellationRequested();
                    //copy the texture bitmap data into the texture bitmap object
                    //https://docs.microsoft.com/en-us/dotnet/api/system.drawing.bitmap.clone?redirectedfrom=MSDN&view=netframework-4.8#System_Drawing_Bitmap_Clone_System_Drawing_Rectangle_System_Drawing_Imaging_PixelFormat_
                    //rectangle of desired area to clone
                    Rectangle textureRect = new Rectangle(texture.X, texture.Y, texture.Width, texture.Height);
                    //copy the bitmap
                    try
                    {
                        texture.AtlasImage = atlasImage.Clone(textureRect, atlasImage.PixelFormat);
                    }
                    catch (Exception ex)
                    {
                        Logging.Exception("failed to clone atlas image data");
                        Logging.Exception(ex.ToString());
                        try
                        {
                            atlasImage.UnlockBits(atlasLock);
                            atlasImage.Dispose();
                        }
                        catch
                        { }
                        return(FailCode.ImageImporter);
                    }
                }
                atlasImage.UnlockBits(atlasLock);
                atlasImage.Dispose();
            }
            OnAtlasProgres?.Invoke(this, null);

            stopwatch.Stop();
            Logging.Info("[atlas file {0}]: parsing bitmap data completed in {1} msec", Path.GetFileName(Atlas.AtlasFile), stopwatch.ElapsedMilliseconds);

            //prepare atlas objects for processing
            Atlas.AtlasFile = Path.Combine(Atlas.AtlasSaveDirectory, Atlas.AtlasFile);
            Atlas.MapFile   = Path.Combine(Atlas.AtlasSaveDirectory, Atlas.MapFile);

            // if the arguments in width and/or height of the atlases-creator-config-xml-file are 0 (or below) or not given, work with the original file dimensions to get working width and height
            if ((Atlas.AtlasHeight < 1) | (Atlas.AtlasWidth < 1))
            {
                //fix atlas width and size parameters if they are wrong
                if (Atlas.AtlasWidth < 1)
                {
                    throw new BadMemeException("grumpel...");
                }

                if (Atlas.AtlasHeight < 1)
                {
                    throw new BadMemeException("grumpel...");
                }

                //
                if ((originalAtlasSize.Height * originalAtlasSize.Width) == (Atlas.AtlasWidth * Atlas.AtlasHeight))
                {
                    Atlas.AtlasHeight = (int)(Atlas.AtlasHeight * 1.5);
                }
                else
                {
                    // this is to be sure that the image size that will be created, is at least the original size
                    while ((originalAtlasSize.Height * originalAtlasSize.Width) > (Atlas.AtlasWidth * Atlas.AtlasHeight))
                    {
                        Atlas.AtlasHeight = (int)(Atlas.AtlasHeight * 1.2);
                    }
                }
            }

            //
            if ((originalAtlasSize.Height * originalAtlasSize.Width) > (Atlas.AtlasWidth * Atlas.AtlasHeight))
            {
                Logging.Warning("[atlas file {0}]: max possible size is smaller then original size", Path.GetFileName(Atlas.AtlasFile));
                Logging.Warning("original h x w:     {1} x {2}", originalAtlasSize.Height, originalAtlasSize.Width);
                Logging.Warning("max possible h x w: {3} x {4}", Atlas.AtlasHeight, Atlas.AtlasWidth);
            }
            else
            {
                Logging.Debug("[atlas file {0}]: max possible size of new atlas file-> {1} (h) x {2} (w)", Path.GetFileName(Atlas.AtlasFile), Atlas.AtlasHeight, Atlas.AtlasWidth);
            }

            //wait for task here
            Logging.Info("[atlas file {0}]: waiting for mod texture parse task", Path.GetFileName(Atlas.AtlasFile));
            AtlasUtils.ParseModTexturesTask.Wait();
            Logging.Info("[atlas file {0}]: mod texture parse task complete, continue execution", Path.GetFileName(Atlas.AtlasFile));
            OnAtlasProgres?.Invoke(this, null);

            //check if any custom mod contour icons were parsed
            if (AtlasUtils.ModContourIconImages.Count > 0)
            {
                Logging.Info("[atlas file {0}]: {1} custom icons parsed", Path.GetFileName(Atlas.AtlasFile), AtlasUtils.ModContourIconImages.Count);
            }
            else
            {
                Logging.Info("[atlas file {0}]: 0 custom icons parsed for atlas file {1}, no need to make a custom atlas!", AtlasUtils.ModContourIconImages.Count, Path.GetFileName(Atlas.AtlasFile));
                return(FailCode.None);
            }

            //replace the original atlas textures with the mod ones
            Logging.Info("[atlas file {0}]: mod images replacing starting", Path.GetFileName(Atlas.AtlasFile));
            stopwatch.Restart();
            for (int i = 0; i < Atlas.TextureList.Count; i++)
            {
                Token.ThrowIfCancellationRequested();

                //get the matching texture, if it exists
                Texture[] originalResults = AtlasUtils.ModContourIconImages.Where(texturee => texturee.Name.Equals(Atlas.TextureList[i].Name)).ToArray();
                if (originalResults.Count() == 0)
                {
                    continue;
                }
                Texture textureResult = originalResults[originalResults.Count() - 1];
                //here means the count is one, replace the WG original subtexture with the mod one
                Atlas.TextureList[i].AtlasImage.Dispose();
                Atlas.TextureList[i].AtlasImage = null;
                Atlas.TextureList[i].AtlasImage = textureResult.AtlasImage;
                Atlas.TextureList[i].X          = 0;
                Atlas.TextureList[i].Y          = 0;
                Atlas.TextureList[i].Height     = textureResult.AtlasImage.Height;
                Atlas.TextureList[i].Width      = textureResult.AtlasImage.Width;
            }
            OnAtlasProgres?.Invoke(this, null);
            stopwatch.Stop();
            Logging.Info("[atlas file {0}]: mod images replacing completed in {1} msec", Path.GetFileName(Atlas.AtlasFile), stopwatch.ElapsedMilliseconds);

            //(finally) run the atlas creator program
            Logging.Info("[atlas file {0}]: building starting", Path.GetFileName(Atlas.AtlasFile));
            stopwatch.Restart();

            // pack the image, generating a map only if desired
            FailCode result = imagePacker.PackImage(Atlas.TextureList, Atlas.PowOf2, Atlas.Square, Atlas.FastImagePacker, Atlas.AtlasWidth, Atlas.AtlasHeight,
#pragma warning disable IDE0068 // Use recommended dispose pattern
                                                    Atlas.Padding, out Bitmap outputImage, out Dictionary <string, Rectangle> outputMap);

#pragma warning restore IDE0068 // Use recommended dispose pattern
            OnAtlasProgres?.Invoke(this, null);
            if (result != 0)
            {
                Logging.Error("[atlas file {0}]: There was an error making the image sheet", Path.GetFileName(Atlas.AtlasFile));
                //error result 7 = "failed to pack image" most likely it won't fit
                return(result);
            }
            else
            {
                Logging.Info("[atlas file {0}]: Success Packing into {1} x {2} pixel", Path.GetFileName(Atlas.AtlasFile), outputImage.Height, outputImage.Width);
            }

            //save it to the class for disposal
            outputAtlasImage = outputImage;

            //export the atlas file
            //delete one if it exists
            if (File.Exists(Atlas.AtlasFile))
            {
                File.Delete(Atlas.AtlasFile);
            }
            //then save
            SaveDDS(Atlas.AtlasFile, outputImage);
            OnAtlasProgres?.Invoke(this, null);
            Logging.Info("[atlas file {0}]: successfully created Atlas image: {1}", Path.GetFileName(Atlas.AtlasFile), Atlas.AtlasFile);

            //export the mapfile
            //delete one if it exists
            if (File.Exists(Atlas.MapFile))
            {
                File.Delete(Atlas.MapFile);
            }

            //then save
            SaveMapfile(Atlas.MapFile, outputMap);
            OnAtlasProgres?.Invoke(this, null);
            Logging.Info("[atlas file {0}]: successfully created map: {1}", Path.GetFileName(Atlas.AtlasFile), Atlas.MapFile);

            stopwatch.Stop();
            Logging.Info("[atlas file {0}]: building completed in {1} msec", Path.GetFileName(Atlas.AtlasFile), stopwatch.ElapsedMilliseconds);

            return(FailCode.None);
        }