sharpdx / SharpDX

SharpDX GitHub Repository
http://sharpdx.org
MIT License
1.7k stars 638 forks source link

Memory Leaks after closing form something is not disposed ? #921

Open gomidas opened 7 years ago

gomidas commented 7 years ago

program.cs

using System;
using System.Diagnostics;
using System.Windows.Forms;

using SharpDX;
using SharpDX.D3DCompiler;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using SharpDX.Windows;
using Buffer = SharpDX.Direct3D11.Buffer;
using Device = SharpDX.Direct3D11.Device;
using SharpDX.RawInput;
using SharpDX.Multimedia;
using AlphaMode = SharpDX.Direct2D1.AlphaMode;
using Factory = SharpDX.DXGI.Factory;
using System.Threading;
using System.Collections.Generic;

using CubeApp.Windows;
using System.Runtime.CompilerServices;
using SharpDX.Diagnostics;

namespace CubeApp
{
    /// <summary>
    /// SharpDX MiniCube Direct3D 11 Sample
    /// </summary>
    internal static class Program
    {
        [STAThread]
        private static void Main()
        {
            new Thread(new ThreadStart(() =>
            {
                // Start clock
                Globals.clock.Start();

                var form = new RenderForm_EX(Globals.Window_Title) { Width = Globals.Window_Size.Width, Height = Globals.Window_Size.Height, AllowUserResizing = false, MinimizeBox = false };
                MouseEventListener MEListener = new  MouseEventListener(form);
                InputHandler IHandler = new InputHandler(form);
                SampleDescription SamplerDesc = new SampleDescription(8, 0);

                // SwapChain description
                var desc = new SwapChainDescription()
                {
                    BufferCount = 2,
                    ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    IsWindowed = true,
                    OutputHandle = form.Handle,
                    SampleDescription = SamplerDesc,
                    SwapEffect = SwapEffect.Discard,
                    Usage = Usage.RenderTargetOutput
                };

                var samplerStateDescription = new SamplerStateDescription
                {
                    AddressU = TextureAddressMode.Wrap,
                    AddressV = TextureAddressMode.Wrap,
                    AddressW = TextureAddressMode.Wrap,
                    Filter = Filter.MinMagMipLinear
                };
                var rasterizerStateDescription = RasterizerStateDescription.Default();
                rasterizerStateDescription.IsFrontCounterClockwise = true;

                // Used for debugging dispose object references
                Configuration.EnableObjectTracking = true;

                // Disable throws on shader compilation errors
                Configuration.ThrowOnShaderCompileError = false;

                SharpDX.DXGI.Factory factory = new SharpDX.DXGI.Factory1();
                SharpDX.DXGI.Adapter adapter = factory.GetAdapter(1);

                foreach(Adapter _adapter in factory.Adapters)
                {
                    Console.WriteLine(_adapter.Description.Description);
                }

               // Create Device and SwapChain
               Device device;
                SwapChain swapChain;
                Device.CreateWithSwapChain(adapter, DeviceCreationFlags.SingleThreaded, desc, out device, out swapChain);

                var context = device.ImmediateContext;

                //factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

                // Compile Vertex and Pixel shaders
                var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.hlsl", "VS", "vs_5_0", ShaderFlags.Debug);
                var vertexShader = new VertexShader(device, vertexShaderByteCode);

                var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.hlsl", "PS", "ps_5_0", ShaderFlags.Debug);
                var pixelShader = new PixelShader(device, pixelShaderByteCode);

                var signature = ShaderSignature.GetInputSignature(vertexShaderByteCode);

                // Layout from VertexShader input signature
                var layout = new InputLayout(device, signature, new[]
                {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0) //CORRECT

                });

                var samplerState = new SamplerState(device, samplerStateDescription);
                SharpDX.WIC.ImagingFactory2 ImagingFactory2 = new SharpDX.WIC.ImagingFactory2();

               // Create Constant Buffer
                var contantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

                // Prepare All the stages
                context.InputAssembler.InputLayout = layout;
                context.VertexShader.SetConstantBuffer(0, contantBuffer);
                context.VertexShader.Set(vertexShader);
                context.PixelShader.Set(pixelShader);
                context.PixelShader.SetSampler(0, samplerState);

                Matrix proj = Matrix.Identity;

                // Declare texture for rendering
                bool userResized = true;

                // Get the backbuffer from the swapchain
                Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); ;

                // Renderview on the backbuffer
                RenderTargetView renderView = new RenderTargetView(device, backBuffer);

                // Create the depth buffer
                Texture2D depthBuffer = new Texture2D(device, new Texture2DDescription()
                {
                    Format = Format.D32_Float_S8X24_UInt,
                    ArraySize = 1,
                    MipLevels = 1,
                    Width = form.ClientSize.Width,
                    Height = form.ClientSize.Height,
                    SampleDescription = SamplerDesc,
                    Usage = ResourceUsage.Default,
                    BindFlags = BindFlags.DepthStencil,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None
                });

                // Create the depth buffer view
                DepthStencilView depthView = new DepthStencilView(device, depthBuffer);

                // Setup handler on resize form
                form.UserResized += (sender, args) => userResized = true;

                // Setup full screen mode change F5 (Full) F4 (Window)
                form.KeyUp += (sender, args) =>
                {
                    if (args.KeyCode == Keys.F5)
                    swapChain.SetFullscreenState(true, null);
                    else if (args.KeyCode == Keys.F4)
                        swapChain.SetFullscreenState(false, null);
                    else if (args.KeyCode == Keys.Escape)
                        form.Close();
                };

                //CREATE DEPTH STENCIL DESCRIPTION
                DepthStencilStateDescription depthSSD = new DepthStencilStateDescription();
                depthSSD.IsDepthEnabled = false;
                depthSSD.DepthComparison = Comparison.LessEqual;
                depthSSD.DepthWriteMask = DepthWriteMask.Zero;
                DepthStencilState DSState = new DepthStencilState(device, depthSSD);

                Camera camera = new Camera();
                camera.eye = new Vector3(0, 2, -5);
                camera.target = new Vector3(0, 0, 0);
                Camera camera2 = new Camera();
                camera2.eye = new Vector3(0, 0, -9);
                camera2.target = new Vector3(0, 0, 0);

                Globals.Render = true;
                /*void DrawEmptyCircle(Vector3 startPoint, Vector2 radius, Color color)
                {
                    List<VertexPositionColor> circle = new List<VertexPositionColor>();
                    float X, Y;

                    var stepDegree = 0.3f;
                    for (float angle = 0; angle <= 360; angle += stepDegree)
                    {
                        X = startPoint.X + radius.X * (float)Math.Cos((angle));
                        Y = startPoint.Y + radius.Y * (float)Math.Sin((angle));
                        Vector3 point = new Vector3(X, Y, 0);
                        circle.Add(new VertexPositionColor(point, color));
                    }
                }*/
                CubeApp.Windows.SystemInformation.Print(CubeApp.Windows.SystemInformation.GetSystemInformation());
                HardwareInformation.GetHardwareInformation("Win32_DisplayConfiguration", "Description");

                //WorldViewLayers
                Layer layer0 = new Layer(proj,camera,form, "WorldMeshes_Layer", true) {/*LAYER CAMERA*/ Camera = /*MAIN CAMERA FOR LAYER_0*/ camera  };
                Layer layer1 = new Layer(proj, camera2, form, "FPS_Layer", false);

                Mesh mesh1 = new Mesh("mesh1", "", layer0, form, device, ImagingFactory2, "1459761_189172854608778_51355805_n.jpg") { IsSelected = true };
                Mesh mesh2 = new Mesh("mesh2", "", layer0, form, device, ImagingFactory2, "1_Purple.jpg") { IsSelected = false };
                Mesh mesh3 = new Mesh("mesh3", "", layer1, form, device, ImagingFactory2, "RedOctober.png") { IsSelected = false };

                FPS fps = new FPS() { /*mesh = mesh3*/ };

                //MenuCreator menu1 = new MenuCreator(device,new[] {new Vector4(0, 0, 0, 0) });
                Viewport viewPort = new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f);

                //COORDINATE CONVERTER
                CoordinateConverter CoordConverter = new CoordinateConverter();
                // Main loop
                RenderLoop.Run(form, () =>
                {
                    fps.Count();
                    fps.setFormHeader(form);

                    // Prepare matrices
                    if (Globals.Render)
                    {
                        //var view =  layer0.Camera.getView();
                    // If Form resized
                    if (userResized)
                    {

                            // Resize the backbuffer
                            //swapChain.ResizeBuffers(desc.BufferCount, form.ClientSize.Width, form.ClientSize.Height, Format.Unknown, SwapChainFlags.None);

                            // Setup targets and viewport for rendering
                            context.Rasterizer.SetViewport(viewPort);
                            //context.OutputMerger.SetDepthStencilState(DSState);
                            context.OutputMerger.SetTargets(depthView, renderView);
                            // Setup new projection matrix with correct aspect ratio
                            proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f);
                            // We are done resizing
                            userResized = false;
                        }
                        var time = Globals.clock.ElapsedMilliseconds / 1000.0f;

                        // Clear views
                        context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0);
                        context.ClearRenderTargetView(renderView, Color.WhiteSmoke);

                        //Update Camera Position
                        foreach (Layer layer in form.Layers)
                        {
                            if (layer.HandleKeys == true) {

                                Vector3 _camEye = layer.Camera.eye;
                                Vector3 _camTarget = layer.Camera.target;

                                if (IHandler.KeyW)
                                {
                                    _camEye.Z+= 0.050f; _camTarget.Z += 0.050f;
                                }
                                if (IHandler.KeyS)
                                {
                                    _camEye.Z -= 0.050f; _camTarget.Z -= 0.050f;
                                }
                                if (IHandler.KeyA)
                                {
                                    _camEye.X -= 0.050f; _camTarget.X -= 0.050f;
                                }
                                if (IHandler.KeyD)
                                {
                                    _camTarget.X += 0.050f;
                                    _camEye.X += 0.050f;
                                }
                                layer.Camera.eye = _camEye;
                                layer.Camera.target = _camTarget;
                            }
                            layer.Camera.updateView();
                        }

                        // Draw the cube
                        for (int _iM = 0, iL=0; _iM <  Meshes.MeshCollection.Count; _iM++)
                        {
                            var _M = Meshes.MeshCollection[_iM];
                            var viewProj = Matrix.Multiply(_M.ViewLayer.Camera.getView(), proj);

                            if (_M.IsSelected )
                            {
                                if (IHandler.KeyRight) { _M.Position.X += 0.050f; }
                                if (IHandler.KeyLeft) { _M.Position.X -= 0.050f;  }
                                if (IHandler.KeyUp) { _M.Position.Z += 0.050f;    }
                                if (IHandler.KeyDown) { _M.Position.Z -= 0.050f;  }
                                if (IHandler.KeyQ) { _M.Position.Y -= 0.050f;     }
                                if (IHandler.KeyE) { _M.Position.Y += 0.050f;     }
                            }

                            if (_M.ViewLayer.Number> iL)
                            {
                                context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0);
                                iL++;
                            }
                            _M.Render(contantBuffer, device, viewProj);
                        }

                        if (MEListener.MouseDown)
                        {
                            var viewProj = Matrix.Multiply(Meshes.MeshCollection[0].ViewLayer.Camera.getView(), proj);

                            or (int _iV = 0; _iV < Meshes.MeshCollection[0].VertexData.Length; _iV++)
                            {
                                CoordConverter.Convert_3Dto2D((Vector3)mesh1.VertexData[_iV].Position + mesh1.Position, viewProj, form);
                            }
                        }

                        // Present!
                        swapChain.Present(0, PresentFlags.None);
                    }
                });

                // Release all resources
                foreach (Mesh msh in Meshes.MeshCollection)
                {
                    if (msh.VerticesBuffer != null) if(!msh.VerticesBuffer.IsDisposed) msh.VerticesBuffer.Dispose();
                    if (msh.T2D_DiffuseMap != null) if(!msh.T2D_DiffuseMap.IsDisposed)     msh.T2D_DiffuseMap.Dispose();
                    if (msh.textureView    != null) if (!msh.textureView.IsDisposed)   msh.textureView.Dispose();
                }

            signature.Dispose();
            vertexShaderByteCode.Dispose();
            vertexShader.Dispose();
            pixelShaderByteCode.Dispose();
            pixelShader.Dispose();
            layout.Dispose();
            contantBuffer.Dispose();
            depthBuffer.Dispose();
            depthView.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            ImagingFactory2.Dispose();
            device.Dispose();
            context.Dispose();
            swapChain.Dispose();
            factory.Dispose();
            adapter.Dispose();
            DSState.Dispose();
            samplerState.Dispose();
            form.Dispose();

                Console.WriteLine(ObjectTracker.ReportActiveObjects());
            })).Start();
        }
    }

    public class RenderForm_EX : RenderForm
    {
        public List<Layer> Layers = new List<Layer>();
        public RenderForm_EX(string FormTitle)
        {
            Text = FormTitle;
        }
    }
}

Mesh.cs

using ChamberLib.Content;
using SharpDX;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using SharpDX.WIC;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using static CubeApp.Geometry;
using FBX = FbxSharp;
using FBXCL = ChamberLib;

namespace CubeApp
{
    public class Mesh : IDisposable, INotifyPropertyChanged
    {
        public string File;
        public string Name;
        public Vertex[] VertexData { get; set; }
        public int VerticesCount=0;
        public Vector3 Position = new Vector3(0,0,0); //BASED ON PIVOT
        public Vector3 Rotation =new Vector3 (0,0,0);
        public Vector3 Scale = new Vector3(1, 1, 1); //BASED ON PIVOT
        public Vector3 PivotPosition; //MOVE MESH BASED ON THIS POSITION
        public Matrix WorldViewMatrix;
        public SharpDX.Direct3D11.Buffer VerticesBuffer; //protected
        private Layer _ViewLayer;
        public RenderForm_EX Form;

        public Layer ViewLayer {

            get
            {
                return _ViewLayer;
            }
            set
            {
                _ViewLayer = value;
                // Call OnPropertyChanged whenever the property is updated
                OnPropertyChanged("ViewLayer");
            }

        }

        public bool IsDisposed=false;
        public bool IsSelected = false;
        public int Triangles;
        public string DiffuseMap;

        /* FBX PART
        static IContentImporter importer;
        static FBXCL.ISubsystem subsystem;
        static FBXCL.IModel model;
        static ChamberLib.DirectionalLight _light =
            new ChamberLib.DirectionalLight(
                direction: new FBXCL.Vector3(-1, -1, 0).Normalized(),
                diffuseColor: new FBXCL.Vector3(0.9f, 0.8f, 0.7f),
                specularColor: FBXCL.Vector3.Zero,
                enabled: true);

        public static void Load()
        {
            model = subsystem.ContentManager.LoadModel("model.fbx");
            model.SetAmbientLightColor(new FBXCL.Vector3(0.3f, 0.3f, 0.3f));
            model.SetDirectionalLight(_light, 0);
        }*/
        public ShaderResourceView textureView; //private
        public Texture2D T2D_DiffuseMap; //private
        public struct Error { public string Code; public string Description; }
        public List<Error> Errors = new List<Error>();
        public Mesh(string _name,  string _file, Layer _viewLayer, RenderForm_EX _form, SharpDX.Direct3D11.Device device, ImagingFactory2 imagingFactory2, string _DiffuseMapFile = "")
        {
            CheckForErrors(_name);
            if (Errors.Count == 0) {
                Form = _form;
                VertexData =new Vertex[]
                {
                                  // 3D coordinates                                                UV Texture coordinates
                    new Vertex(){ Position = new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), TextureUV = new Vector2(0.0f, 1.0f)},     // Front
                    new Vertex(){ Position = new Vector4(-1.0f,  1.0f, -1.0f, 1.0f), TextureUV = new Vector2(0.0f, 0.0f)},
                    new Vertex(){ Position = new Vector4(1.0f,   1.0f, -1.0f, 1.0f), TextureUV = new Vector2(1.0f, 0.0f)},
                    new Vertex(){ Position = new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), TextureUV = new Vector2(0.0f, 1.0f)},
                    new Vertex(){ Position = new Vector4(1.0f,   1.0f, -1.0f, 1.0f), TextureUV = new Vector2(1.0f, 0.0f)},
                    new Vertex(){ Position = new Vector4(1.0f,  -1.0f, -1.0f, 1.0f), TextureUV = new Vector2(1.0f, 1.0f)},

                    new Vertex(){ Position = new Vector4(- 1.0f, -1.0f,  1.0f, 1.0f), TextureUV = new Vector2(1.0f, 0.0f)}, // BACK
                    new Vertex(){ Position = new Vector4(  1.0f,  1.0f,  1.0f, 1.0f), TextureUV = new Vector2(0.0f, 1.0f)},
                    new Vertex(){ Position = new Vector4( -1.0f,  1.0f,  1.0f, 1.0f), TextureUV = new Vector2(1.0f, 1.0f)},
                    new Vertex(){ Position = new Vector4( -1.0f, -1.0f,  1.0f, 1.0f), TextureUV = new Vector2(1.0f, 0.0f)},
                    new Vertex(){ Position = new Vector4(  1.0f, -1.0f,  1.0f, 1.0f), TextureUV = new Vector2(0.0f, 0.0f)},
                    new Vertex(){ Position = new Vector4(  1.0f,  1.0f,  1.0f, 1.0f), TextureUV = new Vector2(0.0f, 1.0f)},

                    new Vertex(){ Position = new Vector4(-1.0f, 1.0f, -1.0f,  1.0f), TextureUV = new Vector2(0.0f, 1.0f)}, // Top
                    new Vertex(){ Position = new Vector4(-1.0f, 1.0f,  1.0f,  1.0f), TextureUV = new Vector2(0.0f, 0.0f)},
                    new Vertex(){ Position = new Vector4( 1.0f, 1.0f,  1.0f,  1.0f), TextureUV = new Vector2(1.0f, 0.0f)},
                    new Vertex(){ Position = new Vector4(-1.0f, 1.0f, -1.0f,  1.0f), TextureUV = new Vector2(0.0f, 1.0f)},
                    new Vertex(){ Position = new Vector4( 1.0f, 1.0f,  1.0f,  1.0f), TextureUV = new Vector2(1.0f, 0.0f)},
                    new Vertex(){ Position = new Vector4( 1.0f, 1.0f, -1.0f,  1.0f), TextureUV = new Vector2(1.0f, 1.0f)},

                    new Vertex(){ Position = new Vector4(-1.0f,-1.0f, -1.0f,  1.0f), TextureUV = new Vector2(1.0f, 0.0f)}, // Bottom
                    new Vertex(){ Position = new Vector4( 1.0f,-1.0f,  1.0f,  1.0f), TextureUV = new Vector2(0.0f, 1.0f)},
                    new Vertex(){ Position = new Vector4(-1.0f,-1.0f,  1.0f,  1.0f), TextureUV = new Vector2(1.0f, 1.0f)},
                    new Vertex(){ Position = new Vector4(-1.0f,-1.0f, -1.0f,  1.0f), TextureUV = new Vector2(1.0f, 0.0f)},
                    new Vertex(){ Position = new Vector4( 1.0f,-1.0f, -1.0f,  1.0f), TextureUV = new Vector2(0.0f, 0.0f)},
                    new Vertex(){ Position = new Vector4( 1.0f,-1.0f,  1.0f,  1.0f), TextureUV = new Vector2(0.0f, 1.0f)},

                    new Vertex(){ Position = new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), TextureUV = new Vector2(0.0f, 1.0f)}, // Left
                    new Vertex(){ Position = new Vector4(-1.0f, -1.0f,  1.0f, 1.0f), TextureUV = new Vector2(0.0f, 0.0f)},
                    new Vertex(){ Position = new Vector4(-1.0f,  1.0f,  1.0f, 1.0f), TextureUV = new Vector2(1.0f, 0.0f)},
                    new Vertex(){ Position = new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), TextureUV = new Vector2(0.0f, 1.0f)},
                    new Vertex(){ Position = new Vector4(-1.0f,  1.0f,  1.0f, 1.0f), TextureUV = new Vector2(1.0f, 0.0f)},
                    new Vertex(){ Position = new Vector4(-1.0f,  1.0f, -1.0f, 1.0f), TextureUV = new Vector2(1.0f, 1.0f)},

                    new Vertex(){ Position = new Vector4(1.0f, -1.0f, -1.0f, 1.0f), TextureUV = new Vector2(1.0f, 0.0f)}, // Right
                    new Vertex(){ Position = new Vector4(1.0f,  1.0f,  1.0f, 1.0f), TextureUV = new Vector2(0.0f, 1.0f)},
                    new Vertex(){ Position = new Vector4(1.0f, -1.0f,  1.0f, 1.0f), TextureUV = new Vector2(1.0f, 1.0f)},
                    new Vertex(){ Position = new Vector4(1.0f, -1.0f, -1.0f, 1.0f), TextureUV = new Vector2(1.0f, 0.0f)},
                    new Vertex(){ Position = new Vector4(1.0f,  1.0f, -1.0f, 1.0f), TextureUV = new Vector2(0.0f, 0.0f)},
                    new Vertex(){ Position = new Vector4(1.0f,  1.0f,  1.0f, 1.0f), TextureUV = new Vector2(0.0f, 1.0f)}
                };
                //d3dDevice = _device;

                //_vertices = Vertices;
                VerticesCount = VertexData.Count();
                VerticesBuffer = SharpDX.Direct3D11.Buffer.Create(device, BindFlags.VertexBuffer, VertexData.ToArray());

            //IndexBuffer =  SharpDX.Direct3D11.Buffer.Create(_device, BindFlags.IndexBuffer, indices);

            T2D_DiffuseMap = TextureLoader.CreateTexture2DFromBitmap(device, TextureLoader.LoadBitmap(imagingFactory2, _DiffuseMapFile));
            textureView = new ShaderResourceView(device, T2D_DiffuseMap);

            DiffuseMap = _DiffuseMapFile;
            Name = _name;
            File = _file;
            ViewLayer = _viewLayer;
            device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(VerticesBuffer, Utilities.SizeOf<float>() * 6, 0));
            //d3dDevice.ImmediateContext.InputAssembler.SetIndexBuffer(IndexBuffer, Format.R16_UNorm, 0);
            Meshes.Add(this);
            Console.WriteLine("[Mesh]{Name='"+Name+"', Layer='Number: "+ViewLayer.Number+", Description: "+ViewLayer.Description+"', Textures='Diffuse: "+_DiffuseMapFile+"'} Mesh created with name "+Name);
            }
        }

        private void CheckForErrors(string _name)
        {
            foreach (Mesh _mesh in Meshes.MeshCollection)
            {
                if (_mesh.Name == _name)
                {
                    Errors.Add(new Error { Code = "msh_000000", Description = "[WARNING: Mesh with name '" + _name + "' Already found. Try an unique name.]" });
                    Console.WriteLine("[WARNING: Mesh with name '" + _name + "' Already found. Try an unique name.]");
                }
            }
        }

        // Flag: Has Dispose already been called?
        bool disposed = false;
        // Instantiate a SafeHandle instance.
        SafeHandle handle = new Microsoft.Win32.SafeHandles.SafeFileHandle(IntPtr.Zero, true);

        // Public implementation of Dispose pattern callable by consumers.
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        // Protected implementation of Dispose pattern.
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
                return;

            if (disposing)
            {
                handle.Dispose();
                // Free any other managed objects here.
                //
            }

            // Free any unmanaged objects here.
            if (VerticesBuffer != null) if (!VerticesBuffer.IsDisposed) VerticesBuffer.Dispose();
            if (T2D_DiffuseMap != null) if (!T2D_DiffuseMap.IsDisposed) T2D_DiffuseMap.Dispose();
            if (textureView != null) if (!textureView.IsDisposed) textureView.Dispose();
            //
            disposed = true;
        }

        //HANDLE EVENTS
        public event PropertyChangedEventHandler PropertyChanged;
        // Create the OnPropertyChanged method to raise the event
        protected void OnPropertyChanged(string _vLayer)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(_vLayer));
                Meshes.MeshCollection.OrderBy( x=> x.ViewLayer );
            }
        }

        //RENDERING OPERATIONS
        public void Render(SharpDX.Direct3D11.Buffer contantBuffer, SharpDX.Direct3D11.Device device, Matrix viewProj)
        {
            // Update WorldViewProj Matrix
            WorldViewMatrix = Matrix.Translation(Position.X, Position.Y, Position.Z) * Matrix.Scaling(Scale) * Matrix.RotationX(Rotation.X) * Matrix.RotationY(Rotation.Y) * Matrix.RotationZ(Rotation.Z) * viewProj;
            WorldViewMatrix.Transpose();
            device.ImmediateContext.UpdateSubresource(ref WorldViewMatrix, contantBuffer);
            device.ImmediateContext.PixelShader.SetShaderResource(0, textureView); //SET SHADER RESOURCE EVERYTIME
            device.ImmediateContext.Draw(VerticesCount,0);
        }
    }
}

I feel like something is causing memory leak something is not disposed ?! What am I doing wrong ? How can I check if there are something not disposed, causing memory leak after I exit application ?

gomidas commented 7 years ago

I think that I did mistake here:

                SharpDX.DXGI.Factory factory = new SharpDX.DXGI.Factory1();
                SharpDX.DXGI.Adapter adapter = factory.GetAdapter(1);

                foreach(Adapter _adapter in factory.Adapters)
                {
                    Console.WriteLine(_adapter.Description.Description);
                }

After Tracking it with object tracker I had a notepad pring and that says there are 3 adapters remaining because I wanted to display adapter information at console but I re-created them and did not dispose I think (in foreach loop) I replaced my code:

                SharpDX.DXGI.Factory factory = new SharpDX.DXGI.Factory1();
                SharpDX.DXGI.Adapter adapter = factory.GetAdapter(1);

                for(int iA=0; iA< adapter.GetOutputCount();iA++)
                {
                    Console.WriteLine(factory.GetAdapter(iA).Description.Description);
                }

And I got result : "Count per Type:" so I only got this text before I got stacks about my 3 device. I think now I can develop my Geometry class without any memory leak.