Beispiel #1
0
    static private void CompressIntoJPEG(string rawdicom, string jpegdicom)
    {
        using (var sfcts = FileChangeTransferSyntax.New())
        {
            // Need to retrieve the actual C++ reference, to pass to
            // SimpleSubjectWatcher:
            FileChangeTransferSyntax fcts    = sfcts.__ref__();
            SimpleSubjectWatcher     watcher = new SimpleSubjectWatcher(fcts, "FileChangeTransferSyntax");
            gdcm.TransferSyntax      ts      = new TransferSyntax(TransferSyntax.TSType.JPEGBaselineProcess1);
            fcts.SetTransferSyntax(ts);
            ImageCodec ic   = fcts.GetCodec();
            JPEGCodec  jpeg = JPEGCodec.Cast(ic);
            jpeg.SetLossless(false);
            jpeg.SetQuality(50); // poor quality !

            fcts.SetInputFileName(rawdicom);
            fcts.SetOutputFileName(jpegdicom);
            fcts.Change();
        }
    }
Beispiel #2
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)));
        }
Beispiel #3
0
        private static void pluginManager_PluginsRemoved(object sender, DualityPluginEventArgs e)
        {
            // Clean globally cached type data
            ImageCodec.ClearTypeCache();
            ObjectCreator.ClearTypeCache();
            ReflectionHelper.ClearTypeCache();
            Component.RequireMap.ClearTypeCache();
            Component.ExecOrder.ClearTypeCache();

            // Clean input sources that a disposed Assembly forgot to unregister.
            foreach (CorePlugin plugin in e.Plugins)
            {
                CleanInputSources(plugin.PluginAssembly);
            }

            // Clean event bindings that are still linked to the disposed Assembly.
            foreach (CorePlugin plugin in e.Plugins)
            {
                CleanEventBindings(plugin.PluginAssembly);
            }
        }
Beispiel #4
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();
        }
        public static void Save(this IImage image, Stream stream, IFileFormat imageFormat, IImageEncoderOptions encoderOptions)
        {
            IImageEncoder encoder = ImageCodec.FromFileFormat(imageFormat);

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

            encoder.Encode(image, stream, encoderOptions);

            if (stream.CanSeek && encoderOptions.OptimizationMode != ImageOptimizationMode.None)
            {
                IImageOptimizer imageOptimizer = ImageOptimizer.FromImageFormat(imageFormat);

                if (!(imageOptimizer is null))
                {
                    stream.Seek(0, SeekOrigin.Begin);

                    imageOptimizer.Optimize(stream, encoderOptions.OptimizationMode);
                }
            }
        }
Beispiel #6
0
        /// <summary>
        /// Converts a CRN to a different type in memory
        /// </summary>
        /// <param name="crnBytes">CRN bytes</param>
        /// <param name="codec">Image Codec</param>
        /// <returns>Converted image bytes</returns>
        public static byte[] GetImageBytesFromCRN(byte[] crnBytes, ImageCodec codec, int levelSegmentCount, byte[] levelSegmentBytes)
        {
            if (IsAvailable == false)
            {
                throw new Exception("LibCRN is not available");
            }

            IntPtr            rawImageData;
            long              rawImageDataSize;
            ConversionOptions options = new ConversionOptions();

            options.Codec = codec;

            var result = ConvertCrnInMemory(
                crnBytes,
                crnBytes.Length,
                options,
                levelSegmentCount,
                levelSegmentBytes,
                levelSegmentBytes?.Length ?? 0,
                out rawImageData,
                out rawImageDataSize
                );

            if (result == false)
            {
                throw new Exception("Failed to read CRN: " + GetErrorString());
            }

            var imageData = new byte[rawImageDataSize];

            Marshal.Copy(rawImageData, imageData, 0, (int)rawImageDataSize);
            FreeMemory(rawImageData);

            return(imageData);
        }
Beispiel #7
0
 public static Tensor CreateTensorFromStream(Stream stream, ImageCodec codec, bool use_resize = false, int width = 100, int height = 100)
 {
     byte[] buff = stream.ReadAll();
     return(CreateTensorFromBuffer(buff, codec, use_resize, width, height));
 }
Beispiel #8
0
        private static void ConstructGraphToNormalizeImage(out TFGraph graph, out TFOutput input, out TFOutput output, ImageCodec codec, bool use_resize = false, int width = 100, int height = 100)
        {
            graph = new TFGraph();
            input = graph.Placeholder(TFDataType.String);

            Output decoded = graph.DecodeImage(input, codec);

            output = graph.ExpandDims(graph.Cast(decoded.NativeOutput, TFDataType.Float), graph.Const(0, "make_batch"));

            if (use_resize)
            {
                output = graph.ResizeBilinear(output, graph.Const(new int[] { width, height }, "size"));
            }
        }
        public void Save(Stream stream, ImageFormat format)
        {
            ImageCodecInfo encoder = ImageCodec.FindEncoder(ImageCodec.ImageFormatToClsid(format));

            Save(stream, encoder, null);
        }
Beispiel #10
0
        private void PrerenderTexturedBackground()
        {
            try {
                IImageCodec codec = ImageCodec.GetRead(ImageCodec.FormatPng);

                // Try to use "The Secret Files" background
                string levelPath = PathOp.Combine(DualityApp.DataDirectory, "Episodes", "secretf", "01_easter1");
                if (!DirectoryOp.Exists(levelPath))
                {
                    // Try to use "Base Game" background
                    levelPath = PathOp.Combine(DualityApp.DataDirectory, "Episodes", "prince", "03_carrot1");
                    if (!DirectoryOp.Exists(levelPath))
                    {
                        // Try to use "Holiday Hare '98" background
                        levelPath = PathOp.Combine(DualityApp.DataDirectory, "Episodes", "xmas98", "03_xmas3");
                        if (!DirectoryOp.Exists(levelPath))
                        {
                            // Try to use "Christmas Chronicles" background
                            levelPath = PathOp.Combine(DualityApp.DataDirectory, "Episodes", "xmas99", "03_xmas3");
                            if (!DirectoryOp.Exists(levelPath))
                            {
                                // Try to use "Shareware Demo" background;
                                levelPath = PathOp.Combine(DualityApp.DataDirectory, "Episodes", "share", "02_share2");
                                if (!DirectoryOp.Exists(levelPath))
                                {
                                    // No usable background found
                                    throw new FileNotFoundException();
                                }
                            }
                        }
                    }
                }

                // Load metadata
                JsonParser json = new JsonParser();
                LevelHandler.LevelConfigJson config;
                using (Stream s = FileOp.Open(PathOp.Combine(levelPath, ".res"), FileAccessMode.Read)) {
                    config = json.Parse <LevelHandler.LevelConfigJson>(s);
                }

                LevelHandler.LevelConfigJson.LayerSection layer;
                if (config.Layers.TryGetValue("Sky", out layer))
                {
                    if (layer.BackgroundColor != null && layer.BackgroundColor.Count >= 3)
                    {
                        horizonColor = new Vector4(layer.BackgroundColor[0] / 255f, layer.BackgroundColor[1] / 255f, layer.BackgroundColor[2] / 255f, 1f);
                    }

                    switch ((BackgroundStyle)layer.BackgroundStyle)
                    {
                    case BackgroundStyle.Sky:
                    default:
                        texturedBackgroundShader = ContentResolver.Current.RequestShader("TexturedBackground");
                        break;

                    case BackgroundStyle.Circle:
                        texturedBackgroundShader = ContentResolver.Current.RequestShader("TexturedBackgroundCircle");
                        break;
                    }
                }

                // Render background layer to texture
                string tilesetPath = PathOp.Combine(DualityApp.DataDirectory, "Tilesets", config.Description.DefaultTileset);

                ColorRgba[] tileMapPalette = TileSet.LoadPalette(PathOp.Combine(tilesetPath, ".palette"));
                ContentResolver.Current.ApplyBasePalette(tileMapPalette);

                TileSet levelTileset = new TileSet(config.Description.DefaultTileset);
                if (!levelTileset.IsValid)
                {
                    throw new InvalidDataException();
                }

                using (Stream s = FileOp.Open(PathOp.Combine(levelPath, "Sky.layer"), FileAccessMode.Read)) {
                    using (DeflateStream deflate = new DeflateStream(s, CompressionMode.Decompress))
                        using (BinaryReader r = new BinaryReader(deflate)) {
                            int width  = r.ReadInt32();
                            int height = r.ReadInt32();

                            TileMapLayer newLayer = new TileMapLayer();
                            newLayer.Layout = new LayerTile[width * height];

                            for (int i = 0; i < newLayer.Layout.Length; i++)
                            {
                                ushort tileType = r.ReadUInt16();

                                byte flags = r.ReadByte();
                                if (flags == 0)
                                {
                                    newLayer.Layout[i] = levelTileset.GetDefaultTile(tileType);
                                    continue;
                                }

                                bool isFlippedX        = (flags & 0x01) > 0;
                                bool isFlippedY        = (flags & 0x02) > 0;
                                bool isAnimated        = (flags & 0x04) > 0;
                                bool legacyTranslucent = (flags & 0x80) > 0;

                                // Invalid tile numbers (higher than tileset tile amount) are silently changed to empty tiles
                                if (tileType >= levelTileset.TileCount && !isAnimated)
                                {
                                    tileType = 0;
                                }

                                LayerTile tile;

                                // Copy the default tile and do stuff with it
                                tile            = levelTileset.GetDefaultTile(tileType);
                                tile.IsFlippedX = isFlippedX;
                                tile.IsFlippedY = isFlippedY;
                                tile.IsAnimated = isAnimated;

                                if (legacyTranslucent)
                                {
                                    tile.MaterialAlpha = /*127*/ 140;
                                }

                                newLayer.Layout[i] = tile;
                            }

                            newLayer.LayoutWidth = width;

                            RecreateTexturedBackground(levelTileset, ref newLayer);
                        }
                }
            } catch (Exception ex) {
                Console.WriteLine("Cannot prerender textured background: " + ex);

                cachedTexturedBackground = new Texture(new Pixmap(new PixelData(2, 2, ColorRgba.Black)));
            }
        }
Beispiel #11
0
        private void InitializeInput()
        {
            if (virtualButtons != null)
            {
                // It's already initialized...
                return;
            }

            DualityApp.Keyboard.Source = new KeyboardInputSource(this);
            //DualityApp.Gamepads.AddSource(new GamepadInputSource(this));

            const float dpadLeft       = 0.02f;
            const float dpadTop        = 0.58f;
            const float dpadWidth      = 0.2f;
            const float dpadHeight     = 0.37f;
            const float dpadThresholdX = 0.05f;
            const float dpadThresholdY = 0.09f;

            IImageCodec  imageCodec = ImageCodec.GetRead(ImageCodec.FormatPng);
            AssetManager assets     = Context.Assets;

            Material matDpad, matFire, matJump, matRun, matSwitchWeapon;

            using (Stream s = assets.Open("dpad.png")) {
                matDpad = new Material(DrawTechnique.Alpha, new Texture(new Pixmap(imageCodec.Read(s)), TextureSizeMode.NonPowerOfTwo));
            }
            using (Stream s = assets.Open("fire.png")) {
                matFire = new Material(DrawTechnique.Alpha, new Texture(new Pixmap(imageCodec.Read(s)), TextureSizeMode.NonPowerOfTwo));
            }
            using (Stream s = assets.Open("jump.png")) {
                matJump = new Material(DrawTechnique.Alpha, new Texture(new Pixmap(imageCodec.Read(s)), TextureSizeMode.NonPowerOfTwo));
            }
            using (Stream s = assets.Open("run.png")) {
                matRun = new Material(DrawTechnique.Alpha, new Texture(new Pixmap(imageCodec.Read(s)), TextureSizeMode.NonPowerOfTwo));
            }
            using (Stream s = assets.Open("switch.png")) {
                matSwitchWeapon = new Material(DrawTechnique.Alpha, new Texture(new Pixmap(imageCodec.Read(s)), TextureSizeMode.NonPowerOfTwo));
            }

            virtualButtons = new[] {
                new VirtualButton {
                    Left = dpadLeft, Top = dpadTop, Width = dpadWidth, Height = dpadHeight, Material = matDpad, CurrentPointerId = -1
                },

                new VirtualButton {
                    KeyCode = Key.Left, Left = dpadLeft - dpadThresholdX, Top = dpadTop, Width = (dpadWidth / 3) + dpadThresholdX, Height = dpadHeight, CurrentPointerId = -1
                },
                new VirtualButton {
                    KeyCode = Key.Right, Left = (dpadLeft + (dpadWidth * 2 / 3)), Top = dpadTop, Width = (dpadWidth / 3) + dpadThresholdX, Height = dpadHeight, CurrentPointerId = -1
                },
                new VirtualButton {
                    KeyCode = Key.Up, Left = dpadLeft, Top = dpadTop - dpadThresholdY, Width = dpadWidth, Height = (dpadHeight / 3) + dpadThresholdY, CurrentPointerId = -1
                },
                new VirtualButton {
                    KeyCode = Key.Down, Left = dpadLeft, Top = (dpadTop + (dpadHeight * 2 / 3)), Width = dpadWidth, Height = (dpadHeight / 3) + dpadThresholdY, CurrentPointerId = -1
                },

                new VirtualButton {
                    KeyCode = Key.Space, Left = 0.68f, Top = 0.79f, Width = 0.094f, Height = 0.168f, Material = matFire, CurrentPointerId = -1
                },
                new VirtualButton {
                    KeyCode = Key.V, Left = 0.785f, Top = 0.71f, Width = 0.094f, Height = 0.168f, Material = matJump, CurrentPointerId = -1
                },
                new VirtualButton {
                    KeyCode = Key.C, Left = 0.89f, Top = 0.64f, Width = 0.094f, Height = 0.168f, Material = matRun, CurrentPointerId = -1
                },
                new VirtualButton {
                    KeyCode = Key.X, Left = 0.83f, Top = 0.57f, Width = 0.055f, Height = 0.096f, Material = matSwitchWeapon, CurrentPointerId = -1
                },

#if DEBUG
                new VirtualButton {
                    KeyCode = Key.D, Left = 0.8f, Top = 0.1f, Width = 0.06f, Height = 0.1f, CurrentPointerId = -1
                },
                new VirtualButton {
                    KeyCode = Key.N, Left = 0.9f, Top = 0.1f, Width = 0.08f, Height = 0.16f, CurrentPointerId = -1
                },
#endif

                new VirtualButton {
                    KeyCode = Key.Enter, Left = 0.68f, Top = 0.79f, Width = 0.094f, Height = 0.17f, CurrentPointerId = -1
                },
                new VirtualButton {
                    KeyCode = Key.Enter, Left = 0.785f, Top = 0.71f, Width = 0.094f, Height = 0.17f, CurrentPointerId = -1
                },
                new VirtualButton {
                    KeyCode = Key.Enter, Left = 0.89f, Top = 0.64f, Width = 0.094f, Height = 0.17f, CurrentPointerId = -1
                },
            };

            showVirtualButtons = true;
            allowVibrations    = Preferences.Get("Vibrations", true);
        }