Exemplo n.º 1
0
        public static Task <FromImageT> TranslateAsync <FromImageT, ToImageT>(this IImageCodec <FromImageT, ToImageT> codec, ToImageT image, IProgress prog)
        {
            if (codec is null)
            {
                throw new ArgumentNullException(nameof(codec));
            }

            return(Task.Run(() => codec.Translate(image, prog)));
        }
Exemplo n.º 2
0
        public static ToImageT Translate <FromImageT, ToImageT>(this IImageCodec <FromImageT, ToImageT> codec, FromImageT image)
        {
            if (codec is null)
            {
                throw new ArgumentNullException(nameof(codec));
            }

            return(codec.Translate(image, null));
        }
Exemplo n.º 3
0
        public EpisodeSelectSection()
        {
            JsonParser  jsonParser = new JsonParser();
            IImageCodec imageCodec = ImageCodec.GetRead(ImageCodec.FormatPng);

            foreach (string episode in DirectoryOp.GetDirectories(PathOp.Combine(DualityApp.DataDirectory, "Episodes")))
            {
                string pathAbsolute = PathOp.Combine(episode, ".res");
                if (FileOp.Exists(pathAbsolute))
                {
                    Episode json;
                    using (Stream s = DualityApp.SystemBackend.FileSystem.OpenFile(pathAbsolute, FileAccessMode.Read)) {
                        json = jsonParser.Parse <Episode>(s);
                    }
                    json.Token = PathOp.GetFileName(episode);

                    if (!DirectoryOp.Exists(PathOp.Combine(episode, json.FirstLevel)))
                    {
                        continue;
                    }

                    EpisodeEntry entry;
                    entry.Episode = json;
                    if (json.PreviousEpisode != null)
                    {
                        int time = Preferences.Get <int>("EpisodeEnd_Time_" + json.PreviousEpisode);
                        entry.IsAvailable = (time > 0);
                    }
                    else
                    {
                        entry.IsAvailable = true;
                    }

                    entry.CanContinue = Preferences.Get <byte[]>("EpisodeContinue_Misc_" + entry.Episode.Token) != null;

                    string logoPath = PathOp.Combine(episode, ".png");
                    if (FileOp.Exists(logoPath))
                    {
                        PixelData pixelData;
                        using (Stream s = FileOp.Open(logoPath, FileAccessMode.Read)) {
                            pixelData = imageCodec.Read(s);
                        }

                        Texture texture = new Texture(new Pixmap(pixelData), TextureSizeMode.NonPowerOfTwo);
                        entry.Logo = new Material(DrawTechnique.Alpha, texture);
                    }
                    else
                    {
                        entry.Logo = null;
                    }

                    episodes.Add(entry);
                }
            }

            episodes.Sort((x, y) => x.Episode.Position.CompareTo(y.Episode.Position));
        }
Exemplo n.º 4
0
        public static void Encode(this IImageCodec imageCodec, IImage image, string filePath, IImageEncoderOptions options)
        {
            if (!imageCodec.IsSupportedFileFormat(filePath))
            {
                throw new FileFormatException(IO.Properties.ExceptionMessages.UnsupportedFileFormat);
            }

            using (FileStream fs = File.Open(filePath, FileMode.OpenOrCreate))
                imageCodec.Encode(image, fs, options);
        }
Exemplo n.º 5
0
        public static IImage Decode(this IImageCodec imageCodec, string filePath)
        {
            if (!imageCodec.IsSupportedFileFormat(filePath))
            {
                throw new FileFormatException(IO.Properties.ExceptionMessages.UnsupportedFileFormat);
            }

            using (FileStream fs = File.OpenRead(filePath))
                return(imageCodec.Decode(fs));
        }
Exemplo n.º 6
0
        public async Task <T> GetIconAsync <T>(IImageCodec <T> decoder)
        {
            var request = HttpWebRequestExt.Create(IconURL);

            using var response = await request
                                 .GetAsync()
                                 .ConfigureAwait(false);

            return(decoder.Deserialize(response));
        }
Exemplo n.º 7
0
        // ToDo: Move parameters to .config file, rework .config file format
        public BitmapFont(Canvas canvas, string path, int width, int height, int cols, int first, int last, int defaultSpacing)
        {
            this.canvas = canvas;

#if UNCOMPRESSED_CONTENT
            string png = PathOp.Combine(DualityApp.DataDirectory, "Animations", path + ".png");
#else
            string png = PathOp.Combine(DualityApp.DataDirectory, ".dz", "Animations", path + ".png");
#endif
            string config = png + ".config";

            IImageCodec imageCodec = ImageCodec.GetRead(ImageCodec.FormatPng);
            using (Stream s = FileOp.Open(png, FileAccessMode.Read)) {
                PixelData pixelData = imageCodec.Read(s);

                ColorRgba[] palette = ContentResolver.Current.Palette.Res.BasePixmap.Res.PixelData[0].Data;

                ColorRgba[] data = pixelData.Data;
                Parallel.ForEach(Partitioner.Create(0, data.Length), range => {
                    for (int i = range.Item1; i < range.Item2; i++)
                    {
                        int colorIdx = data[i].R;
                        data[i]      = palette[colorIdx].WithAlpha(palette[colorIdx].A * data[i].A / (255f * 255f));
                    }
                });

                Texture texture = new Texture(new Pixmap(pixelData), TextureSizeMode.NonPowerOfTwo, TextureMagFilter.Linear, TextureMinFilter.Linear);

                materialPlain = new Material(DrawTechnique.Alpha, texture);
                materialColor = new Material(ContentResolver.Current.RequestShader("Colorize"), texture);
            }

            byte[] widthFromFileTable = new byte[256];
            using (Stream s = FileOp.Open(config, FileAccessMode.Read)) {
                s.Read(widthFromFileTable, 0, widthFromFileTable.Length);
            }

            this.height = height;
            spacing     = defaultSpacing;

            uint charCode = 0;
            for (int i = first; i < last; i++, charCode++)
            {
                chars[i] = new Rect(
                    (float)((i - first) % cols) / cols,
                    (float)((i - first) / cols) / cols,
                    widthFromFileTable[charCode],
                    height);

                if (charCode > last || i >= 255)
                {
                    break;
                }
            }
        }
Exemplo n.º 8
0
        public MagickImage(ImageMagick.MagickImage image, IImageCodec codec)
        {
            if (image is null)
            {
                throw new ArgumentNullException(nameof(image));
            }

            this.image = image;
            Format     = GetImageFormatFromMagickFormat(image.Format);
            Codec      = codec;
        }
Exemplo n.º 9
0
        public static IImage FromFile(string filePath)
        {
            IImageCodec imageCodec = ImageCodec.FromFileExtension(filePath);

            if (imageCodec is null)
            {
                throw new UnsupportedFileFormatException();
            }

            return(imageCodec.Decode(filePath));
        }
Exemplo n.º 10
0
        private void CreateReferenceImage(string name, int width, int height, Action <Canvas> renderMethod)
        {
            PixelData image = this.RenderToTexture(width, height, renderMethod);

            string      formatId = ImageCodec.FormatPng;
            IImageCodec codec    = ImageCodec.GetWrite(formatId);

            using (Stream stream = File.Open(TestHelper.GetEmbeddedResourcePath(name, ".png"), FileMode.Create))
            {
                codec.Write(stream, image, formatId);
            }
        }
Exemplo n.º 11
0
        public void SetIO(CachingStrategy cache, IImageCodec <Texture2D> codec)
        {
            this.cache = cache;
            this.codec = codec;
            var existing = GetComponentsInChildren <Photosphere>();

            foreach (var photo in existing)
            {
                photo.Deactivate();
                Initialize(photo);
            }
        }
Exemplo n.º 12
0
        internal static void InitDefaultContent()
        {
            IImageCodec codec = ImageCodec.GetRead(ImageCodec.FormatPng);

            if (codec == null)
            {
                Log.Core.WriteError(
                    "Unable to retrieve image codec for format '{0}'. Can't initialize default {1} Resources.",
                    ImageCodec.FormatPng,
                    typeof(Pixmap).Name);
                return;
            }
            InitDefaultContent <Pixmap>(".png", stream => new Pixmap(codec.Read(stream)));
        }
Exemplo n.º 13
0
        public override void Init()
        {
            base.Init();

            jpegDecoder = new TranscoderCodec <BitMiracle.LibJpeg.JpegImage, ImageData>(
                new LibJpegNETCodec(80),
                new LibJpegNETImageDataTranscoder());

            pngDecoder = new TranscoderCodec <Hjg.Pngcs.ImageLines, ImageData>(
                new HjgPngcsCodec(),
                new HjgPngcsImageDataTranscoder());

            metadataDecoder  = new JsonFactory <MetadataResponse>();
            geocodingDecoder = new JsonFactory <GeocodingResponse>();
        }
Exemplo n.º 14
0
        public GdiImage(System.Drawing.Image image, IFileFormat imageFormat, IImageCodec imageCodec)
        {
            if (image is null)
            {
                throw new ArgumentNullException(nameof(image));
            }

            if (imageFormat is null)
            {
                imageFormat = GetImageFormatFromImageFormat(image.RawFormat);
            }

            this.image  = image;
            this.Format = imageFormat;
            this.Codec  = imageCodec ?? (imageFormat is null ? new GdiImageCodec() : new GdiImageCodec(imageFormat));
        }
Exemplo n.º 15
0
        public TileMap(ILevelHandler levelHandler, string tilesetPath, bool hasPit)
        {
            this.levelHandler = levelHandler;
            this.hasPit       = hasPit;

            IImageCodec codec = ImageCodec.GetRead(ImageCodec.FormatPng);

            tileset = new TileSet(tilesetPath);

            if (!tileset.IsValid)
            {
                throw new InvalidDataException("Tileset is corrupted");
            }

            triggerState = new BitArray(TriggerCount);
        }
Exemplo n.º 16
0
        public IImage FromStream(Stream stream, IFileFormat imageFormat = null)
        {
            if (imageFormat is null)
            {
                stream = FileFormatFactory.Default.FromStream(stream, out imageFormat);
            }

            IImageCodec imageCodec = imageCodecFactory.FromFileFormat(imageFormat);

            if (imageCodec is null)
            {
                throw new FileFormatException(IO.Properties.ExceptionMessages.UnsupportedFileFormat);
            }

            return(imageCodec.Decode(stream));
        }
Exemplo n.º 17
0
        void ISerializeExplicit.ReadData(IDataReader reader)
        {
            int version;

            try { reader.ReadValue("version", out version); }
            catch (Exception) { version = Serialize_Version_Unknown; }

            string formatId;

            if (version == Serialize_Version_FormatId)
            {
                reader.ReadValue("formatId", out formatId);
            }
            else if (version == Serialize_Version_LayerPng)
            {
                formatId = ImageCodec.FormatPng;
            }
            else
            {
                throw new NotSupportedException(string.Format(
                                                    "Unknown PixelData serialization version '{0}'. Can't load image data.",
                                                    version));
            }

            IImageCodec codec = ImageCodec.GetRead(formatId);

            if (codec == null)
            {
                throw new NotSupportedException(string.Format(
                                                    "Unable to retrieve image codec for format '{0}'. Can't load image data.",
                                                    formatId));
            }

            byte[] dataBlock;
            reader.ReadValue("pixelData", out dataBlock);
            using (MemoryStream stream = new MemoryStream(dataBlock))
            {
                PixelData pixelData = codec.Read(stream);
                this.data   = pixelData.data;
                this.width  = pixelData.width;
                this.height = pixelData.height;
                pixelData   = null;
            }
        }
Exemplo n.º 18
0
        private static IEnumerable <IImageCodec> GetImageCodecs(IFileFormat imageFormat)
        {
            List <IImageCodec> imageCodecs = new List <IImageCodec>();

            foreach (IImageCodec imageCodec in ImagingPluginLoader.GetImageCodecs())
            {
                IImageCodec nextImageCodec     = imageCodec;
                Type        nextImageCodecType = imageCodec.GetType();

                if (!(nextImageCodec is null) && !(imageFormat is null) && nextImageCodec.IsSupportedFileFormat(imageFormat) && nextImageCodecType.GetConstructor(new[] { typeof(IFileFormat) }) != null)
                {
                    nextImageCodec = (IImageCodec)Activator.CreateInstance(nextImageCodecType, new object[] { imageFormat });
                }

                imageCodecs.Add(nextImageCodec);
            }

            return(imageCodecs);
        }
Exemplo n.º 19
0
        internal static void InitDefaultContent()
        {
            IImageCodec codec = ImageCodec.GetRead(ImageCodec.FormatPng);

            if (codec == null)
            {
                Logs.Core.WriteError(
                    "Unable to retrieve image codec for format '{0}'. Can't initialize default {1} Resources.",
                    ImageCodec.FormatPng,
                    typeof(Pixmap).Name);

                // Initialize default content with generic error instances, so
                // everything else can still work as expected. We logged the error,
                // and there's nothing anyone can do about this at runtime, so just
                // fail gracefully without causing more trouble.
                DefaultContent.InitType <Pixmap>(name => new Pixmap(new PixelData(1, 1, new ColorRgba(255, 0, 255))));

                return;
            }
            DefaultContent.InitType <Pixmap>(".png", stream => new Pixmap(codec.Read(stream)));
        }
Exemplo n.º 20
0
        void ISerializeExplicit.WriteData(IDataWriter writer)
        {
            string formatId = ImageCodec.FormatPng;

            writer.WriteValue("version", Serialize_Version_FormatId);
            writer.WriteValue("formatId", formatId);

            IImageCodec codec = ImageCodec.GetWrite(formatId);

            if (codec == null)
            {
                throw new NotSupportedException(string.Format(
                                                    "Unable to retrieve image codec for format '{0}'. Can't save image data.",
                                                    formatId));
            }

            using (MemoryStream str = new MemoryStream(1024 * 64))
            {
                codec.Write(str, this, formatId);
                writer.WriteValue("pixelData", str.ToArray());
            }
        }
Exemplo n.º 21
0
        private ContentResolver()
        {
            jsonParser = new JsonParser();
            imageCodec = ImageCodec.GetRead(ImageCodec.FormatPng);

#if !UNCOMPRESSED_CONTENT
            string dz = PathOp.Combine(DualityApp.DataDirectory, ".dz");
            PathOp.Mount(dz, new CompressedContent(dz));
#endif

            defaultNormalMap = new Texture(new Pixmap(new PixelData(2, 2, new ColorRgba(0.5f, 0.5f, 1f))), TextureSizeMode.Default, TextureMagFilter.Nearest, TextureMinFilter.Nearest);

            cachedMetadata = new Dictionary <string, Metadata>();
            cachedGraphics = new Dictionary <string, GenericGraphicResource>();
            cachedShaders  = new Dictionary <string, ContentRef <DrawTechnique> >();
            //cachedSounds = new Dictionary<string, ContentRef<Sound>>();

            basicNormal   = RequestShader("BasicNormal");
            paletteNormal = RequestShader("PaletteNormal");

            AllowAsyncLoading();
        }
Exemplo n.º 22
0
        private static void GatherAvailable()
        {
            availableCodecs = new List <IImageCodec>();
            foreach (TypeInfo imageCodecType in DualityApp.GetAvailDualityTypes(typeof(IImageCodec)))
            {
                if (imageCodecType.IsAbstract)
                {
                    continue;
                }
                if (imageCodecType.IsInterface)
                {
                    continue;
                }

                IImageCodec codec = imageCodecType.CreateInstanceOf() as IImageCodec;
                if (codec != null)
                {
                    availableCodecs.Add(codec);
                }
            }
            availableCodecs.StableSort((a, b) => b.Priority > a.Priority ? 1 : -1);
        }
Exemplo n.º 23
0
        private static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ThreadException += Application_ThreadException;

            var metadataDecoder   = new JsonFactory <MetadataResponse>();
            var geocodingDecoder  = new JsonFactory <GeocodingResponse>();
            var userProfile       = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            var assetsRoot        = Path.Combine(userProfile, "Box", "VR Initiatives", "Engineering", "Assets");
            var keyFileName       = Path.Combine(assetsRoot, "DevKeys", "google-streetview.txt");
            var gmapsCacheDirName = Path.Combine(assetsRoot, "GoogleMaps");
            var gmapsCacheDir     = new DirectoryInfo(gmapsCacheDirName);
            var cache             = new CachingStrategy
            {
                new FileCacheLayer(gmapsCacheDir)
            };

            var lines      = File.ReadAllLines(keyFileName);
            var apiKey     = lines[0];
            var signingKey = lines[1];

            gmaps = new GoogleMapsClient <MetadataResponse>(
                apiKey, signingKey,
                metadataDecoder, geocodingDecoder,
                cache);

            imageDecoder = new GDICodec(MediaType.Image.Jpeg);

            form = new ImageViewer();
            form.LocationSubmitted += Form_LocationSubmitted;
            form.LatLngSubmitted   += Form_LatLngSubmitted;
            form.PanoSubmitted     += Form_PanoSubmitted;
            using (form)
            {
                Application.Run(form);
            }
        }
Exemplo n.º 24
0
 public bool TryGetValue(MediaType key, out IImageCodec <ImageData> value)
 {
     return(decoders.TryGetValue(key, out value));
 }
Exemplo n.º 25
0
 public static void Encode(this IImageCodec imageCodec, IImage image, Stream stream)
 {
     imageCodec.Encode(image, stream, ImageEncoderOptions.Default);
 }
Exemplo n.º 26
0
 public static void Encode(this IImageCodec imageCodec, IImage image, string filePath)
 {
     imageCodec.Encode(image, filePath, ImageEncoderOptions.Default);
 }
Exemplo n.º 27
0
        public override void Awake()
        {
            base.Awake();

            processor = new UnityTexture2DProcessor();

            Find.Any(out loadingBar);
            Find.Any(out gps);
            if (!this.FindClosest(out photospheres))
            {
                photospheres = this.Ensure <PhotosphereManager>();
            }

            Find.Any(out avatar);
            navPlane = avatar.GroundPlane.Ensure <Clickable>();
            navPlane.Activate();
            navPointer = transform.Find("NavPointer");
            if (navPointer != null)
            {
                navPointer.Deactivate();
            }

            Find.Any(out input);

            cache = new CachingStrategy();

#if UNITY_EDITOR
            this.ReceiveCredentials();

            locationInput = this.Ensure <EditorTextInput>();
            locationInput.OnSubmit.AddListener(new UnityAction <string>(SetLocation));
            if (!string.IsNullOrEmpty(locationInput.value))
            {
                SetLocation(locationInput.value);
            }
            else if (gps != null && gps.HasCoord)
            {
                SetLocation(gps.Coord.ToString());
            }

            var userProfile    = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            var assetsRoot     = Path.Combine(userProfile, "Box", "VR Initiatives", "Engineering", "Assets");
            var oldCubemapPath = Path.Combine(assetsRoot, "GoogleMaps");
            var oldGmapsPath   = Path.Combine(oldCubemapPath, "streetview", "maps", "api");

            cache.AddBackup(new FileCacheLayer(oldCubemapPath));
            cache.AddBackup(new FileCacheLayer(oldGmapsPath));
#else
            if (gps != null && gps.HasCoord)
            {
                SetLocation(gps.Coord.ToString());
            }
#endif

            var newGmapsPath = Path.Combine(CachePrefix, "Google", "StreetView");
            cache.Add(new StreamingAssetsCacheLayer(newGmapsPath));
            codec = new UnityTexture2DCodec(MediaType.Image.Jpeg);

            var metadataDecoder  = new JsonFactory <MetadataTypeT>();
            var geocodingDecoder = new JsonFactory <GeocodingResponse>();

            gmaps = new GoogleMapsClient <MetadataTypeT>(gmapsApiKey, gmapsSigningKey, metadataDecoder, geocodingDecoder, cache);

            photospheres.CubemapNeeded += Photosphere_CubemapNeeded;

            photospheres.SetIO(cache, codec);
            photospheres.SetDetailLevels(searchFOVs);
        }
Exemplo n.º 28
0
 public static IImage CreateImageFromBitmap(Image bitmap, IFileFormat imageFormat, IImageCodec imageCodec)
 {
     return(new GdiImage(bitmap, imageFormat, imageCodec));
 }
Exemplo n.º 29
0
 public static IImageFactory <ToImageT> Pipe <FromImageT, ToImageT>(this IImageFactory <FromImageT> factory, IImageCodec <FromImageT, ToImageT> codec)
 {
     return(new ImageCodec <FromImageT, ToImageT>(factory, codec));
 }
Exemplo n.º 30
0
 public void Add(MediaType key, IImageCodec <ImageData> value)
 {
     decoders.Add(key, value);
 }