Esempio n. 1
0
        /// <summary>
        /// Writes an image to disk taking the shader type into account
        /// </summary>
        /// <param name="index">The index in the file list</param>
        /// <param name="type">The shader type</param>
        /// <param name="folderName">An optional folder name to put the files into</param>
        private void WriteImage(int index, ShaderType type, string folderName = "")
        {
            if (index < 0 || index >= _files.Count)
            {
                return;
            }

            if (!_files[index].Name.EndsWith(".bmp"))
            {
                return;
            }

            if (_files[index].Bytes == null)
            {
                return;
            }

            string pngName    = _files[index].Name.Substring(0, _files[index].Name.Length - 3) + "png";
            string exportPath = Path.GetFileNameWithoutExtension(_exportPath) + "/";

            if (!string.IsNullOrEmpty(folderName))
            {
                exportPath += folderName;
            }

            var byteStream = new MemoryStream(_files[index].Bytes);

            ImageWriter.WriteImage(byteStream, exportPath, pngName, type);
        }
        public void ImportImagePacks()
        {
            // The datapacks
            var di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);

            foreach (var file in di.GetFiles("*" + PackExtension))
            {
                using (var dataPack = new FileStream(file.FullName, FileMode.Open))
                {
                    var archive = new ZipArchive(dataPack);

                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        if (entry.Name != string.Empty)
                        {
                            var iw = new ImageWriter();
                            using (var image = entry.Open())
                            {
                                iw.WriteImage(_cacheLocation + entry.Name, image);
                            }
                        }
                    }
                }

                LogManager.GetLogger().Log(file.Name, LogType.Set);
            }
        }
Esempio n. 3
0
        // Genetic Algorithm maxA testing method
        public IEnumerator StartEvolution()
        {
            CHROMOSOME_SIZE = resolution * resolution;

            // Initializing the population (we chose 500 genes for the population,
            // but you can play with the population size to try different approaches)
            InitializeAlgorithm(POPULATION_SIZE);
            int generationCount = 0;

            // For the sake of this sample, evolution goes on forever.
            // If you wish the evolution to halt (for instance, after a number of
            //   generations is reached or the maximum fitness has been achieved),
            //   this is the place to make any such checks
            while (generationCount < MAX_GENERATIONS)
            {
                // --- evaluate current generation:
                EvaluateGeneration();
                // --- print results here:
                // we choose to print the average fitness,
                // as well as the maximum and minimum fitness
                // as part of our progress monitoring
                float   avgFitness     = 0;
                float   minFitness     = float.PositiveInfinity;
                float   maxFitness     = float.NegativeInfinity;
                Color[] bestIndividual = new Color[CHROMOSOME_SIZE];
                Color[] worstIndividual;
                for (int i = 0; i < Size(); i++)
                {
                    float currFitness = GetGene(i).GetFitness();
                    avgFitness += currFitness;
                    if (currFitness < minFitness)
                    {
                        minFitness      = currFitness;
                        worstIndividual = GetGene(i).GetPhenotype();
                    }
                    if (currFitness > maxFitness)
                    {
                        maxFitness     = currFitness;
                        bestIndividual = GetGene(i).GetPhenotype();
                    }
                }
                if (Size() > 0)
                {
                    avgFitness = avgFitness / Size();
                }
                string output = "Generation: " + generationCount;
                output += "\t AvgFitness: " + avgFitness;
                output += "\t MinFitness: " + minFitness; // + " (" + worstIndividual + ")";
                output += "\t MaxFitness: " + maxFitness; // + " (" + bestIndividual + ")";
                Debug.Log(output);

                ImageWriter.WriteImage(resolution, bestIndividual, visualizer);
                // produce next generation:
                ProduceNextGeneration();
                generationCount++;

                yield return(null);
            }
        }
Esempio n. 4
0
        public static void WriteModuleTo(ModuleDefinition module, Stream stream, WriterParameters parameters)
        {
            AssemblyNameDefinition name;

            if ((int)(module.Attributes & ModuleAttributes.ILOnly) == 0)
            {
                throw new NotSupportedException("Writing mixed-mode assemblies is not supported");
            }
            if (module.HasImage && module.ReadingMode == ReadingMode.Deferred)
            {
                ImmediateModuleReader.ReadModule(module);
            }
            module.MetadataSystem.Clear();
            if (module.assembly != null)
            {
                name = module.assembly.Name;
            }
            else
            {
                name = null;
            }
            AssemblyNameDefinition publicKey           = name;
            string fullyQualifiedName                  = stream.GetFullyQualifiedName();
            ISymbolWriterProvider symbolWriterProvider = parameters.SymbolWriterProvider;

            if (symbolWriterProvider == null && parameters.WriteSymbols)
            {
                symbolWriterProvider = SymbolProvider.GetPlatformWriterProvider();
            }
            ISymbolWriter symbolWriter = ModuleWriter.GetSymbolWriter(module, fullyQualifiedName, symbolWriterProvider);

            if (parameters.StrongNameKeyPair != null && publicKey != null)
            {
                publicKey.PublicKey = parameters.StrongNameKeyPair.PublicKey;
                ModuleDefinition attributes = module;
                attributes.Attributes = attributes.Attributes | ModuleAttributes.StrongNameSigned;
            }
            MetadataBuilder metadataBuilder = new MetadataBuilder(module, fullyQualifiedName, symbolWriterProvider, symbolWriter);

            ModuleWriter.BuildMetadata(module, metadataBuilder);
            if (module.symbol_reader != null)
            {
                module.symbol_reader.Dispose();
            }
            ImageWriter imageWriter = ImageWriter.CreateWriter(module, metadataBuilder, stream);

            imageWriter.WriteImage();
            if (parameters.StrongNameKeyPair != null)
            {
                CryptoService.StrongName(stream, imageWriter, parameters.StrongNameKeyPair);
            }
            if (symbolWriter != null)
            {
                symbolWriter.Dispose();
            }
        }
Esempio n. 5
0
        public virtual void Save(Stream stream)
        {
            Image image = new Image();

            image.Rows = MetadataObjects.AsParallel().Select(m => m.ImageRow).ToArray();

            //writer closes stream on disposing. Error in CfuPackage
            //using (ImageWriter writer = new ImageWriter(stream))
            //{
            //    writer.WriteImage(image);
            //}
            ImageWriter writer = new ImageWriter(stream);

            writer.WriteImage(image);
            writer.Flush();
        }
Esempio n. 6
0
        public static void WriteModuleTo(ModuleDefinition module, Stream stream, WriterParameters parameters)
        {
            if ((module.Attributes & ModuleAttributes.ILOnly) == 0)
            {
                throw new NotSupportedException("Writing mixed-mode assemblies is not supported");
            }
            if (module.HasImage && (module.ReadingMode == ReadingMode.Deferred))
            {
                ImmediateModuleReader.ReadModule(module);
            }
            module.MetadataSystem.Clear();
            AssemblyNameDefinition name = module.assembly?.Name;
            string fullyQualifiedName   = stream.GetFullyQualifiedName();
            ISymbolWriterProvider symbolWriterProvider = parameters.SymbolWriterProvider;

            if ((symbolWriterProvider == null) && parameters.WriteSymbols)
            {
                symbolWriterProvider = SymbolProvider.GetPlatformWriterProvider();
            }
            ISymbolWriter writer = GetSymbolWriter(module, fullyQualifiedName, symbolWriterProvider);

            if ((parameters.StrongNameKeyPair != null) && (name != null))
            {
                name.PublicKey     = parameters.StrongNameKeyPair.PublicKey;
                module.Attributes |= ModuleAttributes.StrongNameSigned;
            }
            MetadataBuilder metadata = new MetadataBuilder(module, fullyQualifiedName, symbolWriterProvider, writer);

            BuildMetadata(module, metadata);
            if (module.symbol_reader != null)
            {
                module.symbol_reader.Dispose();
            }
            ImageWriter writer2 = ImageWriter.CreateWriter(module, metadata, stream);

            writer2.WriteImage();
            if (parameters.StrongNameKeyPair != null)
            {
                CryptoService.StrongName(stream, writer2, parameters.StrongNameKeyPair);
            }
            if (writer != null)
            {
                writer.Dispose();
            }
        }
Esempio n. 7
0
        private static void Write(ModuleDefinition module, Disposable <Stream> stream, WriterParameters parameters)
        {
            if ((module.Attributes & ModuleAttributes.ILOnly) == (ModuleAttributes)0)
            {
                throw new NotSupportedException("Writing mixed-mode assemblies is not supported");
            }
            if (module.HasImage && module.ReadingMode == ReadingMode.Deferred)
            {
                ImmediateModuleReader immediateModuleReader = new ImmediateModuleReader(module.Image);
                immediateModuleReader.ReadModule(module, false);
                immediateModuleReader.ReadSymbols(module);
            }
            module.MetadataSystem.Clear();
            if (module.symbol_reader != null)
            {
                module.symbol_reader.Dispose();
            }
            AssemblyNameDefinition assemblyNameDefinition = (module.assembly != null) ? module.assembly.Name : null;
            string fileName  = stream.value.GetFileName();
            uint   timestamp = parameters.Timestamp ?? module.timestamp;
            ISymbolWriterProvider symbolWriterProvider = parameters.SymbolWriterProvider;

            if (symbolWriterProvider == null && parameters.WriteSymbols)
            {
                symbolWriterProvider = new DefaultSymbolWriterProvider();
            }
            if (parameters.StrongNameKeyPair != null && assemblyNameDefinition != null)
            {
                assemblyNameDefinition.PublicKey = parameters.StrongNameKeyPair.PublicKey;
                module.Attributes |= ModuleAttributes.StrongNameSigned;
            }
            using (ISymbolWriter symbol_writer = GetSymbolWriter(module, fileName, symbolWriterProvider, parameters))
            {
                MetadataBuilder metadata = new MetadataBuilder(module, fileName, timestamp, symbolWriterProvider, symbol_writer);
                BuildMetadata(module, metadata);
                ImageWriter imageWriter = ImageWriter.CreateWriter(module, metadata, stream);
                stream.value.SetLength(0L);
                imageWriter.WriteImage();
                if (parameters.StrongNameKeyPair != null)
                {
                    CryptoService.StrongName(stream.value, imageWriter, parameters.StrongNameKeyPair);
                }
            }
        }
Esempio n. 8
0
        public void GetCardImages(Game game)
        {
            LogManager.GetLogger().Log(game.Name, LogType.Game);

            var wc = new WebClient();

            foreach (var set in game.Sets)
            {
                if (set == null || !set.ImagesNeeded)
                {
                    continue;
                }

                LogManager.GetLogger().Log(set.Name, LogType.Set);

                foreach (var card in set.Cards)
                {
                    try
                    {
                        byte[] image = _cache.GetImage(card.Id);

                        if (image == null)
                        {
                            image = wc.DownloadData(ApiBaseUrl + "/" + Uri.EscapeUriString(set.Name) + "/" + card.Id + ".png");
                            _cache.SaveImage(card.Id, ".png", image);
                        }

                        _imageWriter.WriteImage(OctgnPaths.CardImagePath(game.Id, set.Id, card.Id, ".png"), image);
                    }
                    catch (WebException ex)
                    {
                        LogManager.GetLogger().Log("Unable to find: " + card.Name, LogType.Card);

                        if (((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.NotFound)
                        {
                            throw;
                        }
                    }
                }
            }
        }
Esempio n. 9
0
        public void GetCardImages(Game game)
        {
            LogManager.GetLogger().Log(game.Name, LogType.Game);

            var wc = new WebClient();

            dynamic apiSets = Json.Decode(wc.DownloadString(ApiBaseUrl + "/api/public/packs/"));

            foreach (var apiSet in apiSets)
            {
                string setName = apiSet.name;

                //I needed to match the sets using a custom method since there were no identifying marks except for the actual name.
                var set = game.Sets.SingleOrDefault(s => StringExtensions.CustomContains(s.Name, setName));

                if (set == null || !set.ImagesNeeded)
                {
                    if (set == null)
                    {
                        LogManager.GetLogger().Log("Unable to map set: " + setName + ".  It may not be on OCTGN yet.", LogType.Error);
                    }

                    continue;
                }

                LogManager.GetLogger().Log(set.Name + ": " + apiSet.name, LogType.Set);

                dynamic apiCards = Json.Decode(wc.DownloadString(ApiBaseUrl + "/api/public/cards/" + apiSet.code));

                foreach (var apiCard in apiCards)
                {
                    var card = set.Cards.FirstOrDefault(c => c.Id.Equals(apiCard.octgnid));

                    if (card != null && apiCard.imagesrc != string.Empty)
                    {
                        try
                        {
                            byte[] image = _cache.GetImage(card.Id);

                            if (image == null)
                            {
                                image = wc.DownloadData(ApiBaseUrl + apiCard.imagesrc);
                                _cache.SaveImage(card.Id, ".jpg", image);
                            }

                            _imageWriter.WriteImage(OctgnPaths.CardImagePath(game.Id, set.Id, card.Id, ".jpg"), image);
                        }
                        catch (WebException ex)
                        {
                            LogManager.GetLogger().Log("Unable to find: " + card.Name, LogType.Card);

                            if (((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.NotFound)
                            {
                                throw;
                            }
                        }
                    }
                    else
                    {
                        LogManager.GetLogger().Log("Unable to find: " + apiCard.title, LogType.Card);
                    }
                }
            }
        }
Esempio n. 10
0
        private ImageRow CreateImageRow(FileInfo fileInfo, string path)
        {
            ImageRow row = new ImageRow();

            row.Creation = System.IO.File.GetCreationTime(path);
            row.Modified = System.IO.File.GetLastWriteTime(path);
            row.FileName = fileInfo.Id;

            string model = "";

            Type fileInfoClass = typeof(MetadataPackage).Assembly.GetType(fileInfo.Class);

            if (((fileInfoClass == typeof(UnresolvedPart)) || fileInfoClass.IsSubclassOf(typeof(UnresolvedPart))) &&
                ((fileInfo.BodyType == ImageRowTypes.CompressedUtf8MarkedString) || (fileInfo.BodyType == ImageRowTypes.Utf8MarkedString)))
            {
                using (StreamReader reader = new StreamReader(path))
                {
                    model = reader.ReadToEnd();
                }
            }
            else if (fileInfoClass.IsSubclassOf(typeof(MetadataPart)))
            {
                if (_settings.Type == ProjectType.Debug)
                {
                    using (StreamReader reader = new StreamReader(path))
                    {
                        model = reader.ReadToEnd();
                    }
                }
                else if (_settings.Type == ProjectType.Xml)
                {
                    MetadataPart mp = null;
                    using (XmlReader xmlReader = XmlReader.Create(path))
                    {
                        mp = System.Windows.Markup.XamlReader.Load(xmlReader) as MetadataPart;
                        //mp.CreateModelFromProperties();
                    }
                    DataSerializer ds = new DataSerializer();
                    model = ds.Serialize(mp.GetModel());
                }
                else
                {
                    throw new InvalidOperationException("Unknown project type");
                }
            }
            else if (fileInfo.BodyType == ImageRowTypes.CompressedImage)
            {
                Image image = new Image();

                if (fileInfo.Items != null)
                {
                    image.Rows = fileInfo.Items.AsParallel().Select(m => CreateImageRow(m, Path.Combine(fileInfo.Path, m.Path))).ToArray();
                }

                using (MemoryStream stream = new MemoryStream())
                {
                    ImageWriter imageWriter = new ImageWriter(stream);
                    imageWriter.WriteImage(image);
                    imageWriter.Dispose();

                    row.BinaryData = stream.GetBuffer();
                    return(row);
                }
            }
            else if ((fileInfoClass == typeof(UnresolvedPart)) || fileInfoClass.IsSubclassOf(typeof(UnresolvedPart)))
            {
                row.BinaryData = System.IO.File.ReadAllBytes(path);
                return(row);
            }
            else
            {
                throw new InvalidOperationException("Unknown fileInfo class");
            }

            UTF8Encoding utf8   = new UTF8Encoding(true);
            MemoryStream memory = new MemoryStream();

            byte[] preamble = utf8.GetPreamble();
            memory.Write(preamble, 0, preamble.Length);
            byte[] content = utf8.GetBytes(model);
            memory.Write(content, 0, content.Length);
            byte[] deflatedBody = memory.ToArray();

            if (fileInfo.BodyType == ImageRowTypes.Utf8MarkedString)
            {
                row.BinaryData = deflatedBody;
            }
            else if (fileInfo.BodyType == ImageRowTypes.CompressedUtf8MarkedString)
            {
                MemoryStream  compressedStream = new MemoryStream();
                DeflateStream stream           = new DeflateStream(compressedStream, CompressionMode.Compress);
                stream.Write(deflatedBody, 0, deflatedBody.Length);
                stream.Close();
                row.BinaryData = compressedStream.ToArray();
            }
            else
            {
                throw new InvalidOperationException("Unknown File Info Body Type");
            }

            return(row);
        }
Esempio n. 11
0
 public void SaveImage(string cardId, string fileExtension, byte [] image)
 {
     _imageWriter.WriteImage(_cacheLocation + cardId + fileExtension, image);
 }
Esempio n. 12
0
        public void GetCardImages(Game game)
        {
            LogManager.GetLogger().Log(game.Name, LogType.Game);

            var wc = new WebClient();

            dynamic apiSets = Json.Decode(wc.DownloadString(ApiBaseUrl + "/api/public/packs/"));

            foreach (var apiSet in apiSets)
            {
                // The maintainers of Got2 appear to be colapsing all cycle packs into a single set, so we have
                // to grab the set by the cycle number.
                string setName = apiSet.name;
                int    cycle   = apiSet.cycle_position;
                var    set     = game.Sets.SingleOrDefault(s => s.Name.StartsWith(cycle.ToString().PadLeft(2, '0')));

                if (set == null || !set.ImagesNeeded)
                {
                    if (set == null)
                    {
                        LogManager.GetLogger().Log("Unable to map set: " + setName + ".  It may not be on OCTGN yet.", LogType.Error);
                    }

                    continue;
                }

                LogManager.GetLogger().Log(set.Name + ": " + apiSet.name, LogType.Set);

                dynamic apiCards = Json.Decode(wc.DownloadString(ApiBaseUrl + "/api/public/cards/" + apiSet.code));

                foreach (var apiCard in apiCards)
                {
                    var card = set.Cards.FirstOrDefault(c => c.Id.Equals(apiCard.octgn_id));

                    if (card != null && apiCard.imagesrc != string.Empty)
                    {
                        try
                        {
                            byte[] image = _cache.GetImage(card.Id);

                            if (image == null)
                            {
                                image = wc.DownloadData(ApiBaseUrl + apiCard.imagesrc);
                                _cache.SaveImage(card.Id, ".jpg", image);
                            }

                            _imageWriter.WriteImage(OctgnPaths.CardImagePath(game.Id, set.Id, card.Id, ".jpg"), image);
                        }
                        catch (WebException ex)
                        {
                            LogManager.GetLogger().Log("Unable to find: " + card.Name, LogType.Card);

                            if (((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.NotFound)
                            {
                                throw;
                            }
                        }
                    }
                    else
                    {
                        LogManager.GetLogger().Log("Unable to find: " + apiCard.title, LogType.Card);
                    }
                }
            }
        }
Esempio n. 13
0
        public void GetCardImages(Game game)
        {
            LogManager.GetLogger().Log(game.Name, LogType.Game);

            var wc = new WebClient();

            dynamic apiSets = Json.Decode(wc.DownloadString(ApiBaseUrl + "/api/sets/"));

            foreach (var apiSet in apiSets)
            {
                string setName = apiSet.name;
                var    set     = game.Sets.FindSetByName(setName);

                if (set == null || !set.ImagesNeeded)
                {
                    if (set == null)
                    {
                        LogManager.GetLogger().Log("Unable to map set: " + setName + ".  It may not be on OCTGN yet.", LogType.Error);
                    }

                    continue;
                }

                LogManager.GetLogger().Log(set.Name, LogType.Set);

                dynamic apiCards = Json.Decode(wc.DownloadString(ApiBaseUrl + "/api/set/" + apiSet.code));

                foreach (var apiCard in apiCards)
                {
                    // Certain card names can found acrosss multiple sets.  DTDB labels them with (Ext.#).  Need to strip that out for OCTGN lookup.
                    string apiTile = Regex.Replace(apiCard.title.ToString(), @"\(Exp.[\s]*[\d]*\)", "", RegexOptions.IgnoreCase).Trim();

                    var card =
                        // Standard
                        set.Cards.FirstOrDefault(
                            c => c.Name.Equals(apiTile, StringComparison.OrdinalIgnoreCase)) ??
                        // Try appending a missing the
                        set.Cards.FirstOrDefault(
                            c => String.Concat("The ", c.Name).Equals(apiTile, StringComparison.OrdinalIgnoreCase)) ??
                        // Fun with ampersand
                        set.Cards.FirstOrDefault(
                            c => c.Name.Replace("&", " & ").Equals(apiTile, StringComparison.OrdinalIgnoreCase)) ??
                        // There is some inconsitent nameing with é between the definition files and dtdb.  Try both ways if necessary
                        set.Cards.FirstOrDefault(
                            c => c.Name.Trim().Equals(apiTile.Replace("\u00e9", "e"), StringComparison.OrdinalIgnoreCase));

                    if (card != null && apiCard.imagesrc != string.Empty)
                    {
                        try
                        {
                            byte[] image = _cache.GetImage(card.Id);

                            if (image == null)
                            {
                                image = wc.DownloadData(ApiBaseUrl + apiCard.imagesrc);
                                _cache.SaveImage(card.Id, ".jpg", image);
                            }

                            _imageWriter.WriteImage(OctgnPaths.CardImagePath(game.Id, set.Id, card.Id, ".jpg"), image);
                        }
                        catch (WebException ex)
                        {
                            LogManager.GetLogger().Log("Unable to find: " + card.Name, LogType.Card);

                            if (((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.NotFound)
                            {
                                throw;
                            }
                        }
                    }
                    else
                    {
                        LogManager.GetLogger().Log("Unable to find: " + apiCard.title, LogType.Card);
                    }
                }
            }
        }