SimpleGcMemoryAllocator

We found 10 examples in language CSharp for this search. You will see 24 fragments of code.

Other methods


        public void Resize(string source, string destination, int height)
        {
            if (!_enabled)
            {
                return;
            }

            try
            {
                using (var image = Image.Load(source))
                {
                    image.Mutate(x => x.Resize(0, height));
                    image.Save(destination);
                }
            }
            catch
            {
                if (_diskProvider.FileExists(destination))
                {
                    _diskProvider.DeleteFile(destination);
                }

                throw;
            }
        }

        /// <inheritdoc />
        public override IMemoryOwner<T> Allocate<T>(int length, AllocationOptions options = AllocationOptions.None)
        {
            Guard.MustBeGreaterThanOrEqualTo(length, 0, nameof(length));

            return new BasicArrayBuffer<T>(new T[length]);
        }

        /// <inheritdoc />
        public override IManagedByteBuffer AllocateManagedByteBuffer(int length, AllocationOptions options = AllocationOptions.None)
        {
            Guard.MustBeGreaterThanOrEqualTo(length, 0, nameof(length));

            return new BasicByteBuffer(new byte[length]);
        }


        public void Resize(string source, string destination, int height)
        {
            if (!_enabled)
            {
                return;
            }

            try
            {
                using (var image = Image.Load(source))
                {
                    image.Mutate(x => x.Resize(0, height));
                    image.Save(destination);
                }
            }
            catch
            {
                if (_diskProvider.FileExists(destination))
                {
                    _diskProvider.DeleteFile(destination);
                }

                throw;
            }
        }


        public void Resize(string source, string destination, int height)
        {
            if (!_enabled)
            {
                return;
            }

            try
            {
                using (var image = Image.Load(source))
                {
                    image.Mutate(x => x.Resize(0, height));
                    image.Save(destination);
                }
            }
            catch
            {
                if (_diskProvider.FileExists(destination))
                {
                    _diskProvider.DeleteFile(destination);
                }

                throw;
            }
        }


        public void Resize(string source, string destination, int height)
        {
            if (!_enabled)
            {
                return;
            }

            try
            {
                using (var image = Image.Load(source))
                {
                    image.Mutate(x => x.Resize(0, height));
                    image.Save(destination);
                }
            }
            catch
            {
                if (_diskProvider.FileExists(destination))
                {
                    _diskProvider.DeleteFile(destination);
                }

                throw;
            }
        }


        public void Resize(string source, string destination, int height)
        {
            if (!_enabled)
            {
                return;
            }

            try
            {
                using (var image = Image.Load(source))
                {
                    image.Mutate(x => x.Resize(0, height));
                    image.Save(destination);
                }
            }
            catch
            {
                if (_diskProvider.FileExists(destination))
                {
                    _diskProvider.DeleteFile(destination);
                }

                throw;
            }
        }

        #region factory

        private static Configuration _CreateFactoryCfg()
        {
            var cfg = Configuration.Default.ShallowCopy();

            cfg.MemoryAllocator = new SixLabors.Memory.SimpleGcMemoryAllocator();

            #if DEBUG
            Configuration.Default.MemoryAllocator = null; // invalidate default configuration to signal inproper calls
            #endif

            return cfg;
        }

        public static Image<TPixel> CreateImage<TPixel>(this Size size) where TPixel : struct, IPixel<TPixel>
        {
            if (size.Area() <= 0) throw new ArgumentException(nameof(size));

            return new Image<TPixel>(_DefaultConfiguration, size.Width, size.Height);
        }

        public static Image<TPixel> CreateImage<TPixel>(this Size size, TPixel[] data) where TPixel : struct, IPixel<TPixel>
        {
            if (size.Area() <= 0) throw new ArgumentException(nameof(size));
            if (data == null) throw new ArgumentNullException(nameof(data));            
            if (data.Length < size.Area()) throw new ArgumentException(nameof(data));

            return Image.LoadPixelData(_DefaultConfiguration, data, size.Width,size.Height);
        }

        public static Image<TPixel> CreateImage<TPixel>(this TPixel[] data, int width, int height) where TPixel : struct, IPixel<TPixel>
        {
            return new Size(width, height).CreateImage(data);
        }

        #endregion

        #region extensions

        public static Byte[] SaveAsBytes<TPixel>(this Image<TPixel> image, IImageEncoder encoder) where TPixel : struct, IPixel<TPixel>
        {
            using (var s = new System.IO.MemoryStream())
            {
                image.Save(s, encoder);
                s.Flush();
                return s.ToArray();
            }
        }

        /// <inheritdoc />
        protected internal override int GetBufferCapacityInBytes() => int.MaxValue;

        /// <inheritdoc />
        public override IMemoryOwner<T> Allocate<T>(int length, AllocationOptions options = AllocationOptions.None)
        {
            Guard.MustBeGreaterThanOrEqualTo(length, 0, nameof(length));

            return new BasicArrayBuffer<T>(new T[length]);
        }


    public static Memory<byte> LoadCachedTexture(Texture2D texture, bool useDirectXTex) {
        var memory = CachedData.GetOrAdd(
            texture.GetCompositeId(),
            static (_, arg) => {
                var (texture, useDirectXTex) = arg;
                texture.Deserialize(ObjectDeserializationOptions.Default);
                var data = Texture2DConverter.ToRGBA(texture, useDirectXTex && Environment.OSVersion.Platform == PlatformID.Win32NT);
                return data;
            },
            (texture, useDirectXTex));
        var newMemory = new Memory<byte>(new byte[memory.Length]);
        memory.CopyTo(newMemory);
        return newMemory;
    }

    public static void ClearMemory() {
        CachedData.Clear();
        CachedData = new ConcurrentDictionary<(long, string), ReadOnlyMemory<byte>>();
        Configuration.Default.MemoryAllocator.ReleaseRetainedResources();
    }

    public static string Save(Texture2D texture, string path, SnuggleExportOptions options, bool flip) {
        var dir = Path.GetDirectoryName(path);
        if (!string.IsNullOrWhiteSpace(dir) && !Directory.Exists(dir)) {
            Directory.CreateDirectory(dir);
        }

        var writeDds = options.WriteNativeTextures && texture.TextureFormat.CanSupportDDS();

        if (writeDds) {
            path = Path.ChangeExtension(path, ".dds");
            SaveNative(texture, path);
            return path;
        }

        path = Path.ChangeExtension(path, ".png");
        SavePNG(texture, path, flip, options.UseDirectTex);
        return path;
    }

    public static void SavePNG(Texture2D texture, string path, bool flip, bool useDirectXTex) {
        if (File.Exists(path)) {
            return;
        }

        using var image = ConvertImage(texture, flip, useDirectXTex);
        image.SaveAsPng(path);
    }

    public static Image<Rgba32> ConvertImage(Texture2D texture, bool flip, bool useDirectXTex) {
        var data = LoadCachedTexture(texture, useDirectXTex);
        if (data.IsEmpty) {
            return new Image<Rgba32>(1, 1, new Rgba32(0));
        }

        Image image;
        if (texture.TextureFormat.IsAlphaFirst()) {
            image = Image.WrapMemory<Argb32>(data, texture.Width, texture.Height);
        } else if (texture.TextureFormat.IsBGRA(useDirectXTex)) {
            image = Image.WrapMemory<Bgra32>(data, texture.Width, texture.Height);
        } else {
            image = Image.WrapMemory<Rgba32>(data, texture.Width, texture.Height);
        }

        if (flip) {
            image.Mutate(context => context.Flip(FlipMode.Vertical));
        }

        var cloned = image.CloneAs<Rgba32>();
        image.Dispose();
        return cloned;
    }

    public static void SaveNative(Texture2D texture, string path) {
        if (!texture.TextureFormat.CanSupportDDS()) {
            return;
        }

        if (File.Exists(path)) {
            return;
        }

        using var fs = File.OpenWrite(path);
        fs.SetLength(0);
        fs.Write(Texture2DConverter.ToDDS(texture));
    }


        public static int Main(string[] args)
        {
            return CommandLineApplication.Execute<Program>(args);
        }

        public int OnExecute()
        {
            _cellSize = LowResolution ? LowResCellSize : HighResCellSize;
            _worldSize = new Vector2(Width, Height);

            Configuration.Default.MemoryAllocator = new SixLabors.Memory.SimpleGcMemoryAllocator();
            int width = (int)(_worldSize.X * _cellSize);
            int height = (int)(_worldSize.Y * _cellSize);
            WindowCreateInfo wci = new WindowCreateInfo(50, 50, width, height, WindowState.Normal, "Snake");
            GraphicsDeviceOptions options = new GraphicsDeviceOptions();
            _window = new Sdl2Window("Snake", 50, 50, width, height, SDL_WindowFlags.OpenGL, false);
#if DEBUG
            options.Debug = true;
#endif
            options.SyncToVerticalBlank = true;
            options.ResourceBindingModel = ResourceBindingModel.Improved;
            _gd = VeldridStartup.CreateGraphicsDevice(_window, options);
            _cl = _gd.ResourceFactory.CreateCommandList();
            _spriteRenderer = new SpriteRenderer(_gd);

            _window.Resized += () => _gd.ResizeMainWindow((uint)_window.Width, (uint)_window.Height);

            _world = new World(_worldSize, _cellSize);
            _snake = new Snake(_world);
            _textRenderer = new TextRenderer(_gd);
            _textRenderer.DrawText("0");
            _snake.ScoreChanged += () => _textRenderer.DrawText(_snake.Score.ToString());
            _snake.ScoreChanged += () => _highScore = Math.Max(_highScore, _snake.Score);

            Stopwatch sw = Stopwatch.StartNew();
            double previousTime = sw.Elapsed.TotalSeconds;
            while (_window.Exists)
            {
                InputSnapshot snapshot = _window.PumpEvents();
                Input.UpdateFrameInput(snapshot);

                double newTime = sw.Elapsed.TotalSeconds;
                double elapsed = newTime - previousTime;
                previousTime = newTime;
                Update(elapsed);

                if (_window.Exists)
                {
                    DrawFrame();
                }
            }

            _gd.Dispose();

            Console.WriteLine($"Thanks for playing! Your high score was {_highScore}.");
            return _snake.Score;
        }

        private void Update(double deltaSeconds)
        {
            _snake.Update(deltaSeconds);

            if (_snake.Dead && Input.GetKeyDown(Key.Space))
            {
                _snake.Revive();
                _world.CollectFood();
            }
        }

        private void DrawFrame()
        {
            _cl.Begin();
            _cl.SetFramebuffer(_gd.MainSwapchain.Framebuffer);
            _cl.ClearColorTarget(0, _clearColor);

            _snake.Render(_spriteRenderer);
            _world.Render(_spriteRenderer);
            _spriteRenderer.Draw(_gd, _cl);
            Texture targetTex = _textRenderer.TextureView.Target;
            Vector2 textPos = new Vector2(
                (_window.Width / 2f) - targetTex.Width / 2f,
                _window.Height - targetTex.Height - 10f);

            _spriteRenderer.RenderText(_gd, _cl, _textRenderer.TextureView, textPos);

            _cl.End();
            _gd.SubmitCommands(_cl);
            _gd.SwapBuffers(_gd.MainSwapchain);
        }

SixLabors.ImageSharp.Memory.SimpleGcMemoryAllocator : MemoryAllocator

Constructors :

public SimpleGcMemoryAllocator()

Methods :

public IMemoryOwner<T> Allocate(Int32 length = , AllocationOptions options = None)
public IManagedByteBuffer AllocateManagedByteBuffer(Int32 length = , AllocationOptions options = None)
public Void ReleaseRetainedResources()
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()

Other methods