/// <summary>
		/// 
		/// </summary>
		/// <param name="device"></param>
		/// <param name="size"></param>
		/// <param name="count"></param>
		/// <param name="format"></param>
		/// <param name="mips"></param>
		public TextureCubeArray ( GraphicsDevice device, int size, int count, ColorFormat format, bool mips ) : base(device)
		{
			if (count>2048/6) {
				throw new GraphicsException("Too much elements in texture array");
			}

			this.Width		=	size;
			this.Depth		=	1;
			this.Height		=	size;
			this.MipCount	=	mips ? ShaderResource.CalculateMipLevels(Width,Height) : 1;

			var texDesc = new Texture2DDescription();

			texDesc.ArraySize		=	6 * count;
			texDesc.BindFlags		=	BindFlags.ShaderResource;
			texDesc.CpuAccessFlags	=	CpuAccessFlags.None;
			texDesc.Format			=	MakeTypeless( Converter.Convert( format ) );
			texDesc.Height			=	Height;
			texDesc.MipLevels		=	0;
			texDesc.OptionFlags		=	ResourceOptionFlags.TextureCube;
			texDesc.SampleDescription.Count	=	1;
			texDesc.SampleDescription.Quality	=	0;
			texDesc.Usage			=	ResourceUsage.Default;
			texDesc.Width			=	Width;


			texCubeArray	=	new D3D.Texture2D( device.Device, texDesc );
			SRV				=	new ShaderResourceView( device.Device, texCubeArray );
		}
Example #2
0
        public void OnDeviceInitInternal()
        {
            {
                Texture2DDescription desc = new Texture2DDescription();
                desc.Width = Size.X;
                desc.Height = Size.Y;
                desc.Format = m_resourceFormat;
                desc.ArraySize = 1;
                desc.MipLevels = m_mipmapLevels;
                desc.BindFlags = m_bindFlags;
                desc.Usage = m_resourceUsage;
                desc.CpuAccessFlags = m_cpuAccessFlags;
                desc.SampleDescription.Count = m_samplesCount;
                desc.SampleDescription.Quality = m_samplesQuality;
                desc.OptionFlags = m_roFlags;
                m_resource = new Texture2D(MyRender11.Device, desc);
            }
            {
                ShaderResourceViewDescription desc = new ShaderResourceViewDescription();
                desc.Format = m_srvFormat;
                desc.Dimension = ShaderResourceViewDimension.Texture2D;
                desc.Texture2D.MipLevels = m_mipmapLevels;
                desc.Texture2D.MostDetailedMip = 0;
                m_srv = new ShaderResourceView(MyRender11.Device, m_resource, desc);
            }

            m_resource.DebugName = m_name;
            m_srv.DebugName = m_name;
        }
Example #3
0
        internal MyTextureArray(TexId[] mergeList)
        {
            var srcDesc = MyTextures.GetView(mergeList[0]).Description;
            Size = MyTextures.GetSize(mergeList[0]);
            ArrayLen = mergeList.Length;

            Texture2DDescription desc = new Texture2DDescription();
            desc.ArraySize = ArrayLen;
            desc.BindFlags = BindFlags.ShaderResource;
            desc.CpuAccessFlags = CpuAccessFlags.None;
            desc.Format = srcDesc.Format;
            desc.Height = (int)Size.Y;
            desc.Width = (int)Size.X;
            desc.MipLevels = 0;
            desc.SampleDescription.Count = 1;
            desc.SampleDescription.Quality = 0;
            desc.Usage = ResourceUsage.Default;
            m_resource = new Texture2D(MyRender11.Device, desc);

            // foreach mip
            var mipmaps = (int)Math.Log(Size.X, 2) + 1;

            for (int a = 0; a < ArrayLen; a++)
            {
                for (int m = 0; m < mipmaps; m++)
                {
                    MyRender11.Context.CopySubresourceRegion(MyTextures.Textures.Data[mergeList[a].Index].Resource, Resource.CalculateSubResourceIndex(m, 0, mipmaps), null, Resource,
                        Resource.CalculateSubResourceIndex(m, a, mipmaps));
                }
            }

            ShaderView = new ShaderResourceView(MyRender11.Device, Resource);
        }
Example #4
0
        /// <summary>
        /// Takes a scala field as input anf generates a 2D texture.
        /// </summary>
        /// <param name="device"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public static Texture2D GenerateTextureFromField(Device device, Field field, Texture2DDescription? description = null)
        {
            System.Diagnostics.Debug.Assert(field.Size.Length == 2);

            Texture2DDescription desc;

            // Either use the given description, or create a render target/shader resource bindable one.
            if (description == null)
                desc = new Texture2DDescription
                {
                    ArraySize = 1,
                    BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    CpuAccessFlags = CpuAccessFlags.None,
                    Format = Format.R32_Float,
                    Width = field.Size[0],
                    Height = field.Size[1],
                    MipLevels = 1,
                    OptionFlags = ResourceOptionFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage = ResourceUsage.Default
                };
            else
                desc = (Texture2DDescription)description;

            // Put field data into stream/rectangle object
            DataRectangle texData = new DataRectangle(field.Size[0] * sizeof(float), field.GetDataStream());

            // Create texture.
            Texture2D tex = new Texture2D(device, desc, texData);

            return tex;
        }
Example #5
0
        public DX11CubeDepthStencil(DX11RenderContext context, int size, SampleDescription sd, Format format)
        {
            this.context = context;

            var texBufferDesc = new Texture2DDescription
            {
                ArraySize = 6,
                BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = DepthFormatsHelper.GetGenericTextureFormat(format),
                Height = size,
                Width = size,
                OptionFlags = ResourceOptionFlags.TextureCube,
                SampleDescription = sd,
                Usage = ResourceUsage.Default,
                MipLevels = 1
            };

            this.Resource = new Texture2D(context.Device, texBufferDesc);

            this.desc = texBufferDesc;

            //Create faces SRV/RTV
            this.SliceDSV = new DX11SliceDepthStencil[6];

            ShaderResourceViewDescription svd = new ShaderResourceViewDescription()
            {
                Dimension = ShaderResourceViewDimension.TextureCube,
                Format = DepthFormatsHelper.GetSRVFormat(format),
                MipLevels = 1,
                MostDetailedMip = 0,
                First2DArrayFace = 0
            };

            DepthStencilViewDescription dsvd = new DepthStencilViewDescription()
            {
                ArraySize= 6,
                Dimension = DepthStencilViewDimension.Texture2DArray,
                FirstArraySlice = 0,
                Format = DepthFormatsHelper.GetDepthFormat(format),
                MipSlice = 0
            };

            this.DSV = new DepthStencilView(context.Device, this.Resource, dsvd);

            if (context.IsFeatureLevel11)
            {
                dsvd.Flags = DepthStencilViewFlags.ReadOnlyDepth;
                if (format == Format.D24_UNorm_S8_UInt) { dsvd.Flags |= DepthStencilViewFlags.ReadOnlyStencil; }

                this.ReadOnlyDSV = new DepthStencilView(context.Device, this.Resource, dsvd);
            }

            this.SRV = new ShaderResourceView(context.Device, this.Resource, svd);

            for (int i = 0; i < 6; i++)
            {
                this.SliceDSV[i] = new DX11SliceDepthStencil(context, this, i, DepthFormatsHelper.GetDepthFormat(format));
            }
        }
        public void EnumerateColorAttachments()
        {
            Texture2DDescription description = new Texture2DDescription(1, 1, TextureFormat.RedGreenBlue8, false);

            using (GraphicsWindow window = Device.CreateWindow(1, 1))
            using (Framebuffer framebuffer = window.Context.CreateFramebuffer())
            using (Texture2D color0 = Device.CreateTexture2D(description))
            using (Texture2D color1 = Device.CreateTexture2D(description))
            using (Texture2D color2 = Device.CreateTexture2D(description))
            {
                framebuffer.ColorAttachments[0] = color0;
                framebuffer.ColorAttachments[1] = color1;
                framebuffer.ColorAttachments[2] = color2;
                Assert.AreEqual(3, framebuffer.ColorAttachments.Count);

                framebuffer.ColorAttachments[1] = null;
                Assert.AreEqual(2, framebuffer.ColorAttachments.Count);

                framebuffer.ColorAttachments[1] = color1;
                Assert.AreEqual(3, framebuffer.ColorAttachments.Count);

                int count = 0;
                foreach (Texture2D texture in framebuffer.ColorAttachments)
                {
                    Assert.AreEqual(description, texture.Description);
                    ++count;
                }
                Assert.AreEqual(framebuffer.ColorAttachments.Count, count);
            }
        }
Example #7
0
        public DX11RenderMip2D(DX11RenderContext context, int w, int h, Format format)
        {
            this.context = context;
            int levels = this.CountMipLevels(w,h);
            var texBufferDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = format,
                Height = h,
                Width = w,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                MipLevels = levels,
            };

            
            this.Resource = new Texture2D(context.Device, texBufferDesc);
            this.desc = this.Resource.Description;

            this.SRV = new ShaderResourceView(context.Device, this.Resource);

            this.Slices = new DX11MipSliceRenderTarget[levels];

            int sw = w;
            int sh = h;

            for (int i = 0; i < levels; i++)
            {
                this.Slices[i] = new DX11MipSliceRenderTarget(this.context, this, i, w, h);
                w /= 2; h /= 2;
            }
        }
Example #8
0
        public void Texture2D()
        {
            BlittableRGBA[] pixels = new BlittableRGBA[]
            {
                new BlittableRGBA(Color.Red), 
                new BlittableRGBA(Color.Green)
            };
            int sizeInBytes = ArraySizeInBytes.Size(pixels);
            Texture2DDescription description = new Texture2DDescription(2, 1, TextureFormat.RedGreenBlueAlpha8, false);

            using (GraphicsWindow window = Device.CreateWindow(1, 1))
            using (WritePixelBuffer writePixelBuffer = Device.CreateWritePixelBuffer(PixelBufferHint.Stream, sizeInBytes))
            using (Texture2D texture = Device.CreateTexture2D(description))
            {
                writePixelBuffer.CopyFromSystemMemory(pixels);

                //
                // Create texture with pixel buffer
                //
                texture.CopyFromBuffer(writePixelBuffer, BlittableRGBA.Format, BlittableRGBA.Datatype);

                //
                // Read back pixels
                //
                using (ReadPixelBuffer readPixelBuffer = texture.CopyToBuffer(BlittableRGBA.Format, BlittableRGBA.Datatype))
                {
                    BlittableRGBA[] readPixels = readPixelBuffer.CopyToSystemMemory<BlittableRGBA>();

                    Assert.AreEqual(sizeInBytes, readPixelBuffer.SizeInBytes);
                    Assert.AreEqual(pixels[0], readPixels[0]);
                    Assert.AreEqual(pixels[1], readPixels[1]);
                    Assert.AreEqual(description, texture.Description);
                }
            }
        }
Example #9
0
        public static Texture2D TextureFromBitmap(Bitmap image)
        {
            BitmapData data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
                                             ImageLockMode.ReadWrite, image.PixelFormat);
            int bytes = data.Stride*image.Height;
            DataStream stream = new DataStream(bytes, true, true);
            stream.WriteRange(data.Scan0, bytes);
            stream.Position = 0;
            DataRectangle dRect = new DataRectangle(data.Stride, stream);

            Texture2DDescription texDesc = new Texture2DDescription
                                               {
                                                   ArraySize = 1,
                                                   MipLevels = 1,
                                                   SampleDescription = new SampleDescription(1, 0),
                                                   Format = Format.B8G8R8A8_UNorm,
                                                   CpuAccessFlags = CpuAccessFlags.None,
                                                   BindFlags = BindFlags.ShaderResource,
                                                   Usage = ResourceUsage.Immutable,
                                                   Height = image.Height,
                                                   Width = image.Width
                                               };

            image.UnlockBits(data);
            image.Dispose();
            Texture2D texture = new Texture2D(Game.Context.Device, texDesc, dRect);
            stream.Dispose();
            return texture;
        }
Example #10
0
        void OnResize(object sender, EventArgs args)
        {
            var texDesc = new Texture2DDescription
            {
                ArraySize = 1, BindFlags = BindFlags.None,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                Height = ClientSize.Height,
                Width = ClientSize.Width,
                Usage = ResourceUsage.Default,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                OptionFlags = ResourceOptionFlags.None,
                MipLevels = 1
            };

            if (mResolveTexture != null)
                mResolveTexture.Dispose();

            mResolveTexture = new Texture2D(WorldFrame.Instance.GraphicsContext.Device, texDesc);

            if (mMapTexture != null) mMapTexture.Dispose();

            texDesc.CpuAccessFlags = CpuAccessFlags.Read;
            texDesc.Usage = ResourceUsage.Staging;
            mMapTexture = new Texture2D(WorldFrame.Instance.GraphicsContext.Device, texDesc);

            mTarget.Resize(ClientSize.Width, ClientSize.Height, true);
            mCamera.SetAspect((float) ClientSize.Width / ClientSize.Height);
        }
 internal void Init(string name, Texture2DDescription desc, Vector2I size, int bytes)
 {
     m_name = name;
     m_size = size;
     m_desc = desc;
     m_bytes = bytes;
 }
Example #12
0
        /// <summary>
        /// Creates a default D3D11 Texture with forced Shared-Flag
        /// </summary>
        /// <param name="device"></param>
        /// <param name="description"></param>
        /// <param name="D3D10Dev"> </param>
        /// <param name="D2DFactory"> </param>
        public SharedTexture(D2DInteropHandler handler, Texture2DDescription description)
        {
            As11Tex = new Texture2D(handler.D3DDevice11, new Texture2DDescription()
                {
                    ArraySize = description.ArraySize,
                    BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    CpuAccessFlags = description.CpuAccessFlags,
                    Format = description.Format,
                    Height = description.Height,
                    MipLevels = description.MipLevels,
                    OptionFlags = ResourceOptionFlags.KeyedMutex,
                    SampleDescription = description.SampleDescription,
                    Usage = description.Usage,
                    Width = description.Width
                });

            Mutex11 = new KeyedMutex(As11Tex);
            AsResource = new SlimDX.DXGI.Resource(As11Tex);

            As10Tex = handler.D3DDevice10.OpenSharedResource<SlimDX.Direct3D10.Texture2D>(AsResource.SharedHandle);
            Mutex10 = new KeyedMutex(As10Tex);
            AsSurface = As10Tex.AsSurface();
            As2DTarget = SlimDX.Direct2D.RenderTarget.FromDXGI(handler.D2DFactory, AsSurface, new RenderTargetProperties()
                                                                                                            {
                                                                                                                MinimumFeatureLevel = FeatureLevel.Direct3D10,
                                                                                                                Usage = RenderTargetUsage.None,
                                                                                                                Type = RenderTargetType.Hardware,
                                                                                                                PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)
                                                                                                            });
        }
Example #13
0
        void BuildVertexBuffer(Texture2DDescription textureDesc)
        {
            var game = Game.Instance;
            var clientSize = game.RenderViewSize;
            var texWidth = textureDesc.Width;
            var texHeight = textureDesc.Height;

            var clientRatio = clientSize.Width / (float)clientSize.Height;
            var textureRatio = texWidth / (float)texHeight;

            float w = 1f;
            float h = 1f;

            if (clientRatio > textureRatio)
            {
                if (texHeight > clientSize.Height)
                {
                    w = h * textureRatio / clientRatio;
                }
                else
                {
                    h = texHeight / (float)clientSize.Height;
                    w = texWidth / (float)clientSize.Width;
                }
            }
            else
            {
                if (texWidth > clientSize.Width)
                {
                    h = w * clientRatio / textureRatio;
                }
                else
                {
                    h = texHeight / (float)clientSize.Height;
                    w = texWidth / (float)clientSize.Width;
                }
            }

            int start = 0;
            DefineVertex(ref start, w, -h, 1, 1);
            DefineVertex(ref start, -w, -h, 0, 1);
            DefineVertex(ref start, w, h, 1, 0);

            DefineVertex(ref start, w, h, 1, 0);
            DefineVertex(ref start, -w, -h, 0, 1);
            DefineVertex(ref start, -w, h, 0, 0);

            var desc = new BufferDescription();
            desc.BindFlags = BindFlags.VertexBuffer;
            desc.Usage = ResourceUsage.Default;
            desc.CpuAccessFlags = CpuAccessFlags.None;
            desc.SizeInBytes = Utilities.SizeOf<float>() * vertices.Length;
            desc.StructureByteStride = 0;
            desc.OptionFlags = ResourceOptionFlags.None;

            vertexBuffer = Buffer.Create(game.Device, vertices, desc);
            vertexBuffer.DebugName = "Preview(Texture2D)";

            vertexBufferBinding = new VertexBufferBinding(vertexBuffer, Utilities.SizeOf<float>() * VERTEX_FLOAT_COUNT, 0);
        }
Example #14
0
        public RenderTexture(Device device, Vector2I screenSize)
        {
            var textureDesc = new Texture2DDescription()
            {
                Width = screenSize.X,
                Height = screenSize.Y,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.R32G32B32A32_Float,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            };

            _renderTargetTexture = new Texture2D(device, textureDesc);

            _renderTargetView = new RenderTargetView(device, _renderTargetTexture,
                new RenderTargetViewDescription
                {
                    Format = textureDesc.Format,
                    Dimension = RenderTargetViewDimension.Texture2D,
                    Texture2D = {MipSlice = 0},
                });

            // Create the render target view.
            ShaderResourceView = new ShaderResourceView(device, _renderTargetTexture,
                new ShaderResourceViewDescription
                {
                    Format = textureDesc.Format,
                    Dimension = ShaderResourceViewDimension.Texture2D,
                    Texture2D = { MipLevels = 1, MostDetailedMip = 0 },
                });
        }
        /// <summary>
        /// Constructor
        /// Creates the texture we will render to based on the supplied width and height
        /// </summary>
        /// <param name="device">The device we will create the texture with</param>
        /// <param name="texWidth"></param>
        /// <param name="texHeight"></param>
        public RenderTexture(Device device, int texWidth, int texHeight)
        {
            Texture2DDescription textureDescription = new Texture2DDescription()
                {
                    Width = texWidth,
                    Height = texHeight,
                    MipLevels = 1,
                    ArraySize = 1,
                    Format = SlimDX.DXGI.Format.R32G32B32A32_Float,
                    SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0),
                    BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None,
                    Usage = ResourceUsage.Default,
                };
            Texture = new Texture2D(device, textureDescription);
            RenderTargetViewDescription renderTargetViewDescription = new RenderTargetViewDescription()
            {
                Format = textureDescription.Format,
                Dimension = RenderTargetViewDimension.Texture2D,
                MipSlice = 0,
            };

            renderTargetView = new RenderTargetView(device, Texture, renderTargetViewDescription);

            ShaderResourceViewDescription shaderResourceViewDescription = new ShaderResourceViewDescription()
            {
                Format = textureDescription.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
                MostDetailedMip = 0,
                MipLevels = 1
            };

            shaderResourceView = new ShaderResourceView(device, Texture, shaderResourceViewDescription);
        }
        public RenderStereoTextureCommand(int width, int height, StereoRenderer stereoRenderer)
            : base(width, height, stereoRenderer.Scene)
        {
            this.CommandAttributes |= CommandAttributes.StereoRendering;
            this.sceneManager = stereoRenderer.Scene;
            this.stereoRenderer = stereoRenderer;
            this.stereoCamera = (StereoCamera)stereoRenderer.Camera;
            this.stereoCamera.StereoParametersChanged += RequestUpdate;

            Texture2DDescription StereoTextureDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.R8G8B8A8_UNorm,
                Width = 2 * width,
                Height = height,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };

            Texture = new Texture2D(Game.Context.Device, StereoTextureDesc);
        }
Example #17
0
 public static bool CheckTexturesConsistency(Texture2DDescription desc1, Texture2DDescription desc2)
 {
     return desc1.Format == desc2.Format
         && desc1.MipLevels == desc2.MipLevels
         && desc1.Width == desc2.Width
         && desc1.Height == desc2.Height;
 }
Example #18
0
        void InitD3D()
        {
            D3DDevice = new Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_0);

            Texture2DDescription colordesc = new Texture2DDescription();
            colordesc.BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource;
            colordesc.Format = Format.B8G8R8A8_UNorm;
            colordesc.Width = WindowWidth;
            colordesc.Height = WindowHeight;
            colordesc.MipLevels = 1;
            colordesc.SampleDescription = new SampleDescription(1, 0);
            colordesc.Usage = ResourceUsage.Default;
            colordesc.OptionFlags = ResourceOptionFlags.Shared;
            colordesc.CpuAccessFlags = CpuAccessFlags.None;
            colordesc.ArraySize = 1;

            Texture2DDescription depthdesc = new Texture2DDescription();
            depthdesc.BindFlags = BindFlags.DepthStencil;
            depthdesc.Format = Format.D32_Float_S8X24_UInt;
            depthdesc.Width = WindowWidth;
            depthdesc.Height = WindowHeight;
            depthdesc.MipLevels = 1;
            depthdesc.SampleDescription = new SampleDescription(1, 0);
            depthdesc.Usage = ResourceUsage.Default;
            depthdesc.OptionFlags = ResourceOptionFlags.None;
            depthdesc.CpuAccessFlags = CpuAccessFlags.None;
            depthdesc.ArraySize = 1;

            SharedTexture = new Texture2D(D3DDevice, colordesc);
            DepthTexture = new Texture2D(D3DDevice, depthdesc);
            SampleRenderView = new RenderTargetView(D3DDevice, SharedTexture);
            SampleDepthView = new DepthStencilView(D3DDevice, DepthTexture);
            SampleEffect = Effect.FromFile(D3DDevice, "MiniTri.fx", "fx_4_0");
            EffectTechnique technique = SampleEffect.GetTechniqueByIndex(0); ;
            EffectPass pass = technique.GetPassByIndex(0);
            SampleLayout = new InputLayout(D3DDevice, pass.Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) 
            });

            SampleStream = new DataStream(3 * 32, true, true);
            SampleStream.WriteRange(new[] {
                new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f)
            });
            SampleStream.Position = 0;

            SampleVertices = new Buffer(D3DDevice, SampleStream, new BufferDescription()
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = 3 * 32,
                Usage = ResourceUsage.Default
            });

            D3DDevice.Flush();
        }
        public DX11RenderTextureArray(DX11RenderContext context, int w, int h, int elemcnt, Format format)
        {
            this.context = context;

            var texBufferDesc = new Texture2DDescription
            {
                ArraySize = elemcnt,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = format,
                Height = h,
                Width = w,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1,0),
                Usage = ResourceUsage.Default,
            };

            this.Resource = new Texture2D(context.Device, texBufferDesc);

            RenderTargetViewDescription rtd = new RenderTargetViewDescription()
            {
                ArraySize = elemcnt,
                FirstArraySlice = 0,
                Dimension = RenderTargetViewDimension.Texture2DArray,
                Format = format
            };

            ShaderResourceViewDescription srvd = new ShaderResourceViewDescription()
            {
                ArraySize = elemcnt,
                FirstArraySlice = 0,
                Dimension = ShaderResourceViewDimension.Texture2DArray,
                Format = format,
                MipLevels = 1,
                MostDetailedMip = 0
            };

            this.SRV = new ShaderResourceView(context.Device, this.Resource, srvd);
            this.RTV = new RenderTargetView(context.Device, this.Resource, rtd);

            this.SRVArray = new ShaderResourceView[elemcnt];

            ShaderResourceViewDescription srvad = new ShaderResourceViewDescription()
            {
                ArraySize = 1,
                Dimension = ShaderResourceViewDimension.Texture2DArray,
                Format = format,
                MipLevels = 1,
                MostDetailedMip = 0
            };

            for (int i = 0; i < elemcnt; i++)
            {
                srvad.FirstArraySlice = i;
                this.SRVArray[i] = new ShaderResourceView(context.Device, this.Resource, srvad);
            }

            this.desc = texBufferDesc;
        }
Example #20
0
		public static DynamicTexture Create(Device device, Texture2DDescription desc)
		{
			DynamicTexture dt = new DynamicTexture();
			dt.Texture = new Texture2D(device, desc);
			dt.RTView = new RenderTargetView(device, dt.Texture);
			dt.SRView = new ShaderResourceView(device, dt.Texture);
			return dt;
		}
Example #21
0
 internal DepthStencilBuffer(GraphicsDevice device, Texture2DDescription description2D, DepthFormat depthFormat)
     : base(device, description2D)
 {
     DepthFormat = depthFormat;
     DefaultViewFormat = ComputeViewFormat(DepthFormat, out HasStencil);
     Initialize(Resource);
     HasReadOnlyView = InitializeViewsDelayed(out ReadOnlyView);
 }
Example #22
0
        /// <summary>
        /// Creates render target
        /// </summary>
        /// <param name="rs"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="format"></param>
        public DepthStencilCube( GraphicsDevice device, DepthFormat format, int size, int samples, string debugName = "" )
            : base(device)
        {
            bool msaa	=	samples > 1;

            CheckSamplesCount( samples );

            SampleCount	=	samples;

            Format		=	format;
            SampleCount	=	samples;
            Width		=	size;
            Height		=	size;
            Depth		=	1;

            var	texDesc	=	new Texture2DDescription();
                texDesc.Width				=	Width;
                texDesc.Height				=	Height;
                texDesc.ArraySize			=	6;
                texDesc.BindFlags			=	BindFlags.RenderTarget | BindFlags.ShaderResource;
                texDesc.CpuAccessFlags		=	CpuAccessFlags.None;
                texDesc.Format				=	Converter.ConvertToTex( format );
                texDesc.MipLevels			=	1;
                texDesc.OptionFlags			=	ResourceOptionFlags.TextureCube;
                texDesc.SampleDescription	=	new DXGI.SampleDescription(samples, 0);
                texDesc.Usage				=	ResourceUsage.Default;

            texCube	=	new D3D.Texture2D( device.Device, texDesc );

            var srvDesc	=	new ShaderResourceViewDescription();
                srvDesc.Dimension			=	samples > 1 ? ShaderResourceViewDimension.Texture2DMultisampled : ShaderResourceViewDimension.Texture2D;
                srvDesc.Format				=	Converter.ConvertToSRV( format );
                srvDesc.Texture2D.MostDetailedMip	=	0;
                srvDesc.Texture2D.MipLevels			=	1;

            SRV		=	new ShaderResourceView( device.Device, texCube );

            //
            //	Create surfaces :
            //
            surfaces	=	new DepthStencilSurface[ 6 ];

            for ( int face=0; face<6; face++) {

                var rtvDesc = new DepthStencilViewDescription();
                    rtvDesc.Texture2DArray.MipSlice			=	0;
                    rtvDesc.Texture2DArray.FirstArraySlice	=	face;
                    rtvDesc.Texture2DArray.ArraySize		=	1;
                    rtvDesc.Dimension						=	msaa ? DepthStencilViewDimension.Texture2DMultisampledArray : DepthStencilViewDimension.Texture2DArray;
                    rtvDesc.Format							=	Converter.ConvertToDSV( format );

                var dsv	=	new DepthStencilView( device.Device, texCube, rtvDesc );

                int subResId	=	Resource.CalculateSubResourceIndex( 0, face, 1 );

                surfaces[face]	=	new DepthStencilSurface( dsv, format, Width, Height, SampleCount );
            }
        }
Example #23
0
        public Texture2DGL3x(Texture2DDescription description, TextureTarget textureTarget)
        {
            if (description.Width <= 0)
            {
                throw new ArgumentOutOfRangeException("description.Width", "description.Width must be greater than zero.");
            }

            if (description.Height <= 0)
            {
                throw new ArgumentOutOfRangeException("description.Height", "description.Height must be greater than zero.");
            }

            if (description.GenerateMipmaps)
            {
                if (textureTarget == TextureTarget.TextureRectangle)
                {
                    throw new ArgumentException("description.GenerateMipmaps cannot be true for texture rectangles.", "description");
                }
                
                if (!TextureUtility.IsPowerOfTwo(Convert.ToUInt32(description.Width)))
                {
                    throw new ArgumentException("When description.GenerateMipmaps is true, the width must be a power of two.", "description");
                }

                if (!TextureUtility.IsPowerOfTwo(Convert.ToUInt32(description.Height)))
                {
                    throw new ArgumentException("When description.GenerateMipmaps is true, the height must be a power of two.", "description");
                }
            }
            
            _name = new TextureNameGL3x();
            _target = textureTarget;
            _description = description;
            _lastTextureUnit = OpenTKTextureUnit.Texture0 + (Device.NumberOfTextureUnits - 1);

            //
            // TexImage2D is just used to allocate the texture so a PBO can't be bound.
            //
            WritePixelBufferGL3x.UnBind();
            BindToLastTextureUnit();
            GL.TexImage2D(_target, 0,
                TypeConverterGL3x.To(description.TextureFormat),
                description.Width,
                description.Height,
                0,
                TypeConverterGL3x.TextureToPixelFormat(description.TextureFormat),   
                TypeConverterGL3x.TextureToPixelType(description.TextureFormat),
                new IntPtr());

            //
            // Default sampler, compatiable when attaching a non-mimapped 
            // texture to a frame buffer object.
            //
            ApplySampler(Device.TextureSamplers.LinearClamp);

            GC.AddMemoryPressure(description.ApproximateSizeInBytes);
        }
Example #24
0
        public bool Initialise(Bitmap bitmap)
        {
            RemoveAndDispose(ref _tex);
            RemoveAndDispose(ref _texSRV);

            //Debug.Assert(bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            BitmapData bmData;

            Width = bitmap.Width;
            Height = bitmap.Height;

            bmData = bitmap.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadOnly,
                PixelFormat.Format32bppArgb);
            try
            {
                var texDesc = new Texture2DDescription();
                texDesc.Width = Width;
                texDesc.Height = Height;
                texDesc.MipLevels = 1;
                texDesc.ArraySize = 1;
                texDesc.Format = Format.B8G8R8A8_UNorm;
                texDesc.SampleDescription.Count = 1;
                texDesc.SampleDescription.Quality = 0;
                texDesc.Usage = ResourceUsage.Immutable;
                texDesc.BindFlags = BindFlags.ShaderResource;
                texDesc.CpuAccessFlags = CpuAccessFlags.None;
                texDesc.OptionFlags = ResourceOptionFlags.None;

                DataBox data;
                data.DataPointer = bmData.Scan0;
                data.RowPitch = bmData.Stride; // _texWidth * 4;
                data.SlicePitch = 0;

                _tex = ToDispose(new Texture2D(Device, texDesc, new[] {data}));
                if (_tex == null)
                    return false;

                var srvDesc = new ShaderResourceViewDescription();
                srvDesc.Format = Format.B8G8R8A8_UNorm;
                srvDesc.Dimension = ShaderResourceViewDimension.Texture2D;
                srvDesc.Texture2D.MipLevels = 1;
                srvDesc.Texture2D.MostDetailedMip = 0;

                _texSRV = ToDispose(new ShaderResourceView(Device, _tex, srvDesc));
                if (_texSRV == null)
                    return false;
            }
            finally
            {
                bitmap.UnlockBits(bmData);
            }

            _initialised = true;

            return true;
        }
Example #25
0
        public void LoadFromLoadInfo(IO.Files.Texture.TextureLoadInfo loadInfo)
        {
            var texDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = loadInfo.Format,
                Height = loadInfo.Height,
                Width = loadInfo.Width,
                MipLevels = loadInfo.Layers.Count,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };

            if (mTexture != gDefaultTexture)
            {
                if (mTexture != null)
                    mTexture.Dispose();
                if (NativeView != null)
                    NativeView.Dispose();
            }

            var boxes = new DataBox[texDesc.MipLevels];
            var streams = new DataStream[texDesc.MipLevels];
            try
            {
                for(var i = 0; i < texDesc.MipLevels; ++i)
                {
                    streams[i] = new DataStream(loadInfo.Layers[i].Length, true, true);
                    streams[i].WriteRange(loadInfo.Layers[i]);
                    streams[i].Position = 0;
                    boxes[i] = new DataBox(streams[i].DataPointer, loadInfo.RowPitchs[i], 0);
                }

                mTexture = new Texture2D(mContext.Device, texDesc, boxes);
                var srvd = new ShaderResourceViewDescription
                {
                    Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
                    Format = loadInfo.Format,
                    Texture2D = new ShaderResourceViewDescription.Texture2DResource { MipLevels = boxes.Length, MostDetailedMip = 0 }
                };

                NativeView = new ShaderResourceView(mContext.Device, mTexture, srvd);
            }
            finally
            {
                foreach (var stream in streams)
                {
                    if (stream != null)
                        stream.Dispose();
                }
            }
        }
Example #26
0
        /// <summary>
        /// Creates depth stencil texture, view and shader resource with format D24S8
        /// </summary>
        /// <param name="rs"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="format"></param>
        public DepthStencil2D( GraphicsDevice device, DepthFormat format, int width, int height, int samples = 1 )
            : base(device)
        {
            CheckSamplesCount( samples );

            Width		=	width;
            Height		=	height;
            Depth		=	1;
            Format		=	format;
            SampleCount	=	samples;

            var bindFlags	=	BindFlags.DepthStencil;

            if (device.GraphicsProfile==GraphicsProfile.HiDef) {
                bindFlags	|=	BindFlags.ShaderResource;

            } else if (device.GraphicsProfile==GraphicsProfile.Reach) {
                if (samples==1) {
                    bindFlags	|=	BindFlags.ShaderResource;
                }
            }

            var	texDesc	=	new Texture2DDescription();
                texDesc.Width				=	width;
                texDesc.Height				=	height;
                texDesc.ArraySize			=	1;
                texDesc.BindFlags			=	bindFlags;
                texDesc.CpuAccessFlags		=	CpuAccessFlags.None;
                texDesc.Format				=	Converter.ConvertToTex( format );
                texDesc.MipLevels			=	1;
                texDesc.OptionFlags			=	ResourceOptionFlags.None;
                texDesc.SampleDescription	=	new DXGI.SampleDescription(samples, 0);
                texDesc.Usage				=	ResourceUsage.Default;

            var dsvDesc	=	new DepthStencilViewDescription();
                dsvDesc.Dimension			=	samples > 1 ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D;
                dsvDesc.Format				=	Converter.ConvertToDSV( format );
                dsvDesc.Flags				=	DepthStencilViewFlags.None;

            var srvDesc	=	new ShaderResourceViewDescription();
                srvDesc.Dimension			=	samples > 1 ? ShaderResourceViewDimension.Texture2DMultisampled : ShaderResourceViewDimension.Texture2D;
                srvDesc.Format				=	Converter.ConvertToSRV( format );
                srvDesc.Texture2D.MostDetailedMip	=	0;
                srvDesc.Texture2D.MipLevels			=	1;

            tex2D		=	new D3D.Texture2D		( device.Device, texDesc );

            var dsv		=	new DepthStencilView	( device.Device, tex2D,	dsvDesc );

            if (bindFlags.HasFlag( BindFlags.ShaderResource)) {
                SRV		=	new ShaderResourceView	( device.Device, tex2D,	srvDesc );
            }

            surface		=	new DepthStencilSurface	( dsv, format, width, height, samples );
        }
        void InitDevice()
        {
            // create Direct 3D device
            device = D3DDevice.CreateDeviceAndSwapChain( renderHost.Handle, out swapChain );

            // Create a render target view
            using (Texture2D pBuffer = swapChain.GetBuffer<Texture2D>(0))
            {
                renderTargetView = device.CreateRenderTargetView(pBuffer);
            }

            // Create depth stencil texture
            Texture2DDescription descDepth = new Texture2DDescription()
            {
                Width = (uint)renderHost.ActualWidth,
                Height = (uint)renderHost.ActualHeight,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.D32_FLOAT,
                SampleDescription = new SampleDescription()
                {
                    Count = 1,
                    Quality = 0
                },
                BindFlags = BindFlag.DepthStencil,
            };

            depthStencil = device.CreateTexture2D(descDepth);

            // Create the depth stencil view
            DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription()
            {
                Format = descDepth.Format,
                ViewDimension = DepthStencilViewDimension.Texture2D
            };
            depthStencilView = device.CreateDepthStencilView(depthStencil, depthStencilViewDesc);

            // bind the views to the device
            device.OM.SetRenderTargets(new RenderTargetView[] { renderTargetView }, depthStencilView );

            // Setup the viewport
            Viewport vp = new Viewport()
            {
                Width = (uint)renderHost.ActualWidth,
                Height = (uint)renderHost.ActualHeight,
                MinDepth = 0.0f,
                MaxDepth = 1.0f,
                TopLeftX = 0,
                TopLeftY = 0
            };
            
            device.RS.SetViewports(new Viewport[] { vp });
        }
        public DX11RenderTextureArray(DX11RenderContext context, int w, int h, int elemcnt, Format format, bool buildslices = true, int miplevels = 0)
        {
            this.context = context;

            var texBufferDesc = new Texture2DDescription
            {
                ArraySize = elemcnt,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = format,
                Height = h,
                Width = w,
                OptionFlags = miplevels == 0 ? ResourceOptionFlags.GenerateMipMaps : ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1,0),
                Usage = ResourceUsage.Default,
                MipLevels= miplevels
            };

            this.Resource = new Texture2D(context.Device, texBufferDesc);

            RenderTargetViewDescription rtd = new RenderTargetViewDescription()
            {
                ArraySize = elemcnt,
                FirstArraySlice = 0,
                Dimension = RenderTargetViewDimension.Texture2DArray,
                Format = format
            };

            ShaderResourceViewDescription srvd = new ShaderResourceViewDescription()
            {
                ArraySize = elemcnt,
                FirstArraySlice = 0,
                Dimension = ShaderResourceViewDimension.Texture2DArray,
                Format = format,
                MipLevels = this.Resource.Description.MipLevels,
                MostDetailedMip = 0
            };

            this.SRV = new ShaderResourceView(context.Device, this.Resource, srvd);
            this.RTV = new RenderTargetView(context.Device, this.Resource, rtd);

            this.desc = texBufferDesc;

            this.SliceRTV = new DX11SliceRenderTarget[this.ElemCnt];

            if (buildslices)
            {
                for (int i = 0; i < this.ElemCnt; i++)
                {
                    this.SliceRTV[i] = new DX11SliceRenderTarget(this.context, this, i);
                }
            }
        }
Example #29
0
        public bool Initialize(Device device, SystemConfiguration configuration)
        {
            try
            {
                // Initialize and set up the render target description.
                var textureDesc = new Texture2DDescription()
                {
                    Width = configuration.Width,
                    Height = configuration.Height,
                    MipLevels = 1,
                    ArraySize = 1,
                    Format = Format.R32G32B32A32_Float,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage = ResourceUsage.Default,
                    BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None
                };

                // Create the render target texture.
                RenderTargetTexture = new Texture2D(device, textureDesc);

                // Initialize and setup the render target view
                var renderTargetViewDesc = new RenderTargetViewDescription()
                {
                    Format = textureDesc.Format,
                    Dimension = RenderTargetViewDimension.Texture2D,
                };
                renderTargetViewDesc.Texture2D.MipSlice = 0;

                // Create the render target view.
                RenderTargetView = new RenderTargetView(device, RenderTargetTexture, renderTargetViewDesc);

                // Initialize and setup the shader resource view
                var shaderResourceViewDesc = new ShaderResourceViewDescription()
                {
                    Format = textureDesc.Format,
                    Dimension = ShaderResourceViewDimension.Texture2D,
                };
                shaderResourceViewDesc.Texture2D.MipLevels = 1;
                shaderResourceViewDesc.Texture2D.MostDetailedMip = 0;

                // Create the render target view.
                ShaderResourceView = new ShaderResourceView(device, RenderTargetTexture, shaderResourceViewDesc);

                return true;
            }
            catch
            {
                return false;
            }
        }
Example #30
0
 public ScreenManager(int adapterIndex, int outputIndex)
 {
     using (var adapter = InitializeAdapter(adapterIndex))
     {
         _device = new Device(adapter);
         using(var output = InitializeOutput(adapter, outputIndex))
         {
             _desktopBounds = output.Description.DesktopBounds;
             _outputDuplication = InitializeOutputDuplication(output);
             _texture2DDescription = InitializeTexture2DDescription(_desktopBounds);
         }
     }
 }
Example #31
0
        /// <summary>
        /// Creates render target
        /// </summary>
        /// <param name="?"></param>
        /// <param name="format"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="samples"></param>
        /// <param name="mips"></param>
        /// <param name="debugName"></param>
        void Create(ColorFormat format, int size, int samples, bool mips, string debugName)
        {
            bool msaa = samples > 1;

            CheckSamplesCount(samples);

            if (mips && samples > 1)
            {
                throw new ArgumentException("Render target should be multisampler either mipmapped");
            }

            SampleCount = samples;

            Format      = format;
            SampleCount = samples;
            Width       = size;
            Height      = size;
            Depth       = 1;
            MipCount    = mips ? ShaderResource.CalculateMipLevels(Width, Height) : 1;

            var texDesc = new Texture2DDescription();

            texDesc.Width             = Width;
            texDesc.Height            = Height;
            texDesc.ArraySize         = 6;
            texDesc.BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource;
            texDesc.CpuAccessFlags    = CpuAccessFlags.None;
            texDesc.Format            = Converter.Convert(format);
            texDesc.MipLevels         = mips ? MipCount : 1;
            texDesc.OptionFlags       = ResourceOptionFlags.TextureCube | (mips ? ResourceOptionFlags.GenerateMipMaps : ResourceOptionFlags.None);
            texDesc.SampleDescription = new DXGI.SampleDescription(samples, 0);
            texDesc.Usage             = ResourceUsage.Default;


            texCube = new D3D.Texture2D(device.Device, texDesc);
            SRV     = new ShaderResourceView(device.Device, texCube);



            //
            //	Create surfaces :
            //
            surfaces = new RenderTargetSurface[MipCount, 6];

            for (int mip = 0; mip < MipCount; mip++)
            {
                int width  = GetMipSize(Width, mip);
                int height = GetMipSize(Height, mip);

                for (int face = 0; face < 6; face++)
                {
                    var rtvDesc = new RenderTargetViewDescription();
                    rtvDesc.Texture2DArray.MipSlice        = mip;
                    rtvDesc.Texture2DArray.FirstArraySlice = face;
                    rtvDesc.Texture2DArray.ArraySize       = 1;
                    rtvDesc.Dimension = msaa ? RenderTargetViewDimension.Texture2DMultisampledArray : RenderTargetViewDimension.Texture2DArray;
                    rtvDesc.Format    = Converter.Convert(format);

                    var rtv = new RenderTargetView(device.Device, texCube, rtvDesc);

                    int subResId = Resource.CalculateSubResourceIndex(mip, face, MipCount);

                    surfaces[mip, face] = new RenderTargetSurface(rtv, null, texCube, subResId, format, Width, Height, samples);
                }
            }
        }
Example #32
0
 /// <summary>
 /// Creates a new <see cref="RenderTargetCube"/> from a <see cref="Texture2DDescription"/>.
 /// </summary>
 /// <param name="device">The <see cref="GraphicsDevice"/>.</param>
 /// <param name="description">The description.</param>
 /// <returns>
 /// A new instance of <see cref="RenderTargetCube"/> class.
 /// </returns>
 /// <msdn-id>ff476521</msdn-id>
 /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
 /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
 public static RenderTargetCube New(GraphicsDevice device, Texture2DDescription description)
 {
     return(new RenderTargetCube(device, description));
 }
Example #33
0
        public bool Initialize(DSystemConfiguration configuration, IntPtr windowHandle)
        {
            try
            {
                #region Environment Configuration
                // Store the vsync setting.
                VerticalSyncEnabled = DSystemConfiguration.VerticalSyncEnabled;

                // Create a DirectX graphics interface factory.
                var factory = new Factory1();

                // Use the factory to create an adapter for the primary graphics interface (video card).
                var adapter = factory.GetAdapter1(0);

                // Get the primary adapter output (monitor).
                var monitor = adapter.GetOutput(0);

                // Get modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
                var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);

                // Now go through all the display modes and find the one that matches the screen width and height.
                // When a match is found store the the refresh rate for that monitor, if vertical sync is enabled.
                // Otherwise we use maximum refresh rate.
                var rational = new Rational(0, 1);
                if (VerticalSyncEnabled)
                {
                    foreach (var mode in modes)
                    {
                        if (mode.Width == configuration.Width && mode.Height == configuration.Height)
                        {
                            rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator);
                            break;
                        }
                    }
                }

                // Get the adapter (video card) description.
                var adapterDescription = adapter.Description;

                // Store the dedicated video card memory in megabytes.
                VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10;

                // Convert the name of the video card to a character array and store it.
                VideoCardDescription = adapterDescription.Description.Trim('\0');

                // Release the adapter output.
                monitor.Dispose();
                // Release the adapter.
                adapter.Dispose();
                // Release the factory.
                factory.Dispose();
                #endregion

                #region Initialize swap chain and d3d device
                // Initialize the swap chain description.
                var swapChainDesc = new SwapChainDescription()
                {
                    // Set to a single back buffer.
                    BufferCount = 1,
                    // Set the width and height of the back buffer.
                    ModeDescription = new ModeDescription(configuration.Width, configuration.Height, rational, Format.R8G8B8A8_UNorm)
                    {
                        Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrder.Unspecified
                    },
                    // Set the usage of the back buffer.
                    Usage = Usage.RenderTargetOutput,
                    // Set the handle for the window to render to.
                    OutputHandle = windowHandle,
                    // Turn multisampling off.
                    SampleDescription = new SampleDescription(1, 0),
                    // Set to full screen or windowed mode.
                    IsWindowed = !DSystemConfiguration.FullScreen,
                    // Don't set the advanced flags.
                    Flags = SwapChainFlags.None,
                    // Discard the back buffer content after presenting.
                    SwapEffect = SwapEffect.Discard
                };

                // Create the swap chain, Direct3D device, and Direct3D device context.
                SharpDX.Direct3D11.Device device;
                SwapChain swapChain;
                SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain);

                Device        = device;
                SwapChain     = swapChain;
                DeviceContext = device.ImmediateContext;
                #endregion

                #region Initialize buffers
                // Get the pointer to the back buffer.
                var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0);

                // Create the render target view with the back buffer pointer.
                RenderTargetView = new RenderTargetView(device, backBuffer);

                // Release pointer to the back buffer as we no longer need it.
                backBuffer.Dispose();

                // Initialize and set up the description of the depth buffer.
                var depthBufferDesc = new Texture2DDescription()
                {
                    Width             = configuration.Width,
                    Height            = configuration.Height,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = Format.D24_UNorm_S8_UInt,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = ResourceUsage.Default,
                    BindFlags         = BindFlags.DepthStencil,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    OptionFlags       = ResourceOptionFlags.None
                };

                // Create the texture for the depth buffer using the filled out description.
                DepthStencilBuffer = new Texture2D(device, depthBufferDesc);
                #endregion

                #region Initialize Depth Enabled Stencil
                // Initialize and set up the description of the stencil state.
                var depthStencilDesc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled   = true,
                    DepthWriteMask   = DepthWriteMask.All,
                    DepthComparison  = Comparison.Less,
                    IsStencilEnabled = true,
                    StencilReadMask  = 0xFF,
                    StencilWriteMask = 0xFF,
                    // Stencil operation if pixel front-facing.
                    FrontFace = new DepthStencilOperationDescription()
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    },
                    // Stencil operation if pixel is back-facing.
                    BackFace = new DepthStencilOperationDescription()
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    }
                };

                // Create the depth stencil state.
                DepthStencilState = new DepthStencilState(Device, depthStencilDesc);
                #endregion

                #region Initialize Output Merger
                // Set the depth stencil state.
                DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1);

                // Initialize and set up the depth stencil view.
                var depthStencilViewDesc = new DepthStencilViewDescription()
                {
                    Format    = Format.D24_UNorm_S8_UInt,
                    Dimension = DepthStencilViewDimension.Texture2D,
                    Texture2D = new DepthStencilViewDescription.Texture2DResource()
                    {
                        MipSlice = 0
                    }
                };

                // Create the depth stencil view.
                DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc);

                // Bind the render target view and depth stencil buffer to the output render pipeline.
                DeviceContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);
                #endregion

                #region Initialize Raster State
                // Setup the raster description which will determine how and what polygon will be drawn.
                var rasterDesc = new RasterizerStateDescription()
                {
                    IsAntialiasedLineEnabled = false,
                    CullMode                = CullMode.Back,
                    DepthBias               = 0,
                    DepthBiasClamp          = .0f,
                    IsDepthClipEnabled      = true,
                    FillMode                = FillMode.Solid,
                    IsFrontCounterClockwise = false,
                    IsMultisampleEnabled    = false,
                    IsScissorEnabled        = false,
                    SlopeScaledDepthBias    = .0f
                };

                // Create the rasterizer state from the description we just filled out.
                RasterState = new RasterizerState(Device, rasterDesc);
                #endregion

                #region Initialize Rasterizer
                // Now set the rasterizer state.
                DeviceContext.Rasterizer.State = RasterState;

                ViewPort = new ViewportF(0.0f, 0.0f, (float)configuration.Width, (float)configuration.Height, 0.0f, 1.0f);

                // Setup and create the viewport for rendering.
                DeviceContext.Rasterizer.SetViewport(ViewPort);
                #endregion

                #region Initialize matrices
                // Setup and create the projection matrix.
                ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4), ((float)configuration.Width / (float)configuration.Height), DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth);

                // Initialize the world matrix to the identity matrix.
                WorldMatrix = Matrix.Identity;

                // Create an orthographic projection matrix for 2D rendering.
                OrthoMatrix = Matrix.OrthoLH(configuration.Width, configuration.Height, DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth);
                #endregion

                #region Initialize Depth Disabled Stencil
                // Now create a second depth stencil state which turns off the Z buffer for 2D rendering. Added in Tutorial 11
                // The difference is that DepthEnable is set to false.
                // All other parameters are the same as the other depth stencil state.
                var depthDisabledStencilDesc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled   = false,
                    DepthWriteMask   = DepthWriteMask.All,
                    DepthComparison  = Comparison.Less,
                    IsStencilEnabled = true,
                    StencilReadMask  = 0xFF,
                    StencilWriteMask = 0xFF,
                    // Stencil operation if pixel front-facing.
                    FrontFace = new DepthStencilOperationDescription()
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    },
                    // Stencil operation if pixel is back-facing.
                    BackFace = new DepthStencilOperationDescription()
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    }
                };

                // Create the depth stencil state.
                DepthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc);
                #endregion

                #region Initialize Blend States
                // Create an alpha enabled blend state description.
                var blendStateDesc = new BlendStateDescription();
                blendStateDesc.RenderTarget[0].IsBlendEnabled        = true;
                blendStateDesc.RenderTarget[0].SourceBlend           = BlendOption.One;
                blendStateDesc.RenderTarget[0].DestinationBlend      = BlendOption.InverseSourceAlpha;
                blendStateDesc.RenderTarget[0].BlendOperation        = BlendOperation.Add;
                blendStateDesc.RenderTarget[0].SourceAlphaBlend      = BlendOption.One;
                blendStateDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
                blendStateDesc.RenderTarget[0].AlphaBlendOperation   = BlendOperation.Add;
                blendStateDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

                // Create the blend state using the description.
                AlphaEnableBlendingState = new BlendState(device, blendStateDesc);

                // Modify the description to create an disabled blend state description.
                blendStateDesc.RenderTarget[0].IsBlendEnabled = false;

                // Create the blend state using the description.
                AlphaDisableBlendingState = new BlendState(device, blendStateDesc);
                #endregion

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ShaderResourceViewProxy"/> class.
 /// </summary>
 /// <param name="device">The device.</param>
 /// <param name="textureDesc">The texture desc.</param>
 public ShaderResourceViewProxy(Device device, Texture2DDescription textureDesc) : this(device)
 {
     resource      = Collect(new Texture2D(device, textureDesc));
     TextureFormat = textureDesc.Format;
 }
Example #35
0
        public static Resource GenerateMipMaps(Device device, global::SharpDX.Toolkit.Graphics.Texture texture)
        {
            Resource textMip = null;

            //Check texture format support: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476426(v=vs.85).aspx
            switch (texture.Description.Format)
            {
            case global::SharpDX.DXGI.Format.R8G8B8A8_UNorm:
            case global::SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb:
            case global::SharpDX.DXGI.Format.B5G6R5_UNorm:
            case global::SharpDX.DXGI.Format.B8G8R8A8_UNorm:
            case global::SharpDX.DXGI.Format.B8G8R8A8_UNorm_SRgb:
            case global::SharpDX.DXGI.Format.B8G8R8X8_UNorm:
            case global::SharpDX.DXGI.Format.B8G8R8X8_UNorm_SRgb:
            case global::SharpDX.DXGI.Format.R16G16B16A16_Float:
            case global::SharpDX.DXGI.Format.R16G16B16A16_UNorm:
            case global::SharpDX.DXGI.Format.R16G16_Float:
            case global::SharpDX.DXGI.Format.R16G16_UNorm:
            case global::SharpDX.DXGI.Format.R32_Float:
            case global::SharpDX.DXGI.Format.R32G32B32A32_Float:
            case global::SharpDX.DXGI.Format.B4G4R4A4_UNorm:
            case global::SharpDX.DXGI.Format.R32G32B32_Float:
            case global::SharpDX.DXGI.Format.R16G16B16A16_SNorm:
            case global::SharpDX.DXGI.Format.R32G32_Float:
            case global::SharpDX.DXGI.Format.R10G10B10A2_UNorm:
            case global::SharpDX.DXGI.Format.R11G11B10_Float:
            case global::SharpDX.DXGI.Format.R8G8B8A8_SNorm:
            case global::SharpDX.DXGI.Format.R16G16_SNorm:
            case global::SharpDX.DXGI.Format.R8G8_UNorm:
            case global::SharpDX.DXGI.Format.R8G8_SNorm:
            case global::SharpDX.DXGI.Format.R16_Float:
            case global::SharpDX.DXGI.Format.R16_UNorm:
            case global::SharpDX.DXGI.Format.R16_SNorm:
            case global::SharpDX.DXGI.Format.R8_UNorm:
            case global::SharpDX.DXGI.Format.R8_SNorm:
            case global::SharpDX.DXGI.Format.A8_UNorm:
            case global::SharpDX.DXGI.Format.B5G5R5A1_UNorm:
                break;

            default:
                return(texture);   //Format not support, return the original texture.
            }
            switch (texture.Description.Dimension)
            {
            case global::SharpDX.Toolkit.Graphics.TextureDimension.Texture1D:
                var desc1D = new Texture1DDescription()
                {
                    Width          = texture.Description.Width,
                    MipLevels      = 0,
                    ArraySize      = 1,
                    BindFlags      = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    CpuAccessFlags = CpuAccessFlags.None,
                    Usage          = ResourceUsage.Default,
                    OptionFlags    = ResourceOptionFlags.GenerateMipMaps,
                    Format         = texture.Description.Format
                };
                textMip = new Texture1D(device, desc1D);
                break;

            case global::SharpDX.Toolkit.Graphics.TextureDimension.Texture2D:
                var desc2D = new Texture2DDescription()
                {
                    Width             = texture.Description.Width,
                    Height            = texture.Description.Height,
                    MipLevels         = 0,
                    ArraySize         = 1,
                    BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    Usage             = ResourceUsage.Default,
                    SampleDescription = texture.Description.SampleDescription,
                    OptionFlags       = ResourceOptionFlags.GenerateMipMaps,
                    Format            = texture.Description.Format
                };
                textMip = new Texture2D(device, desc2D);
                break;

            case global::SharpDX.Toolkit.Graphics.TextureDimension.Texture3D:
            case global::SharpDX.Toolkit.Graphics.TextureDimension.TextureCube:
                var desc3D = new Texture3DDescription()
                {
                    Width          = texture.Description.Width,
                    Height         = texture.Description.Height,
                    Depth          = texture.Description.ArraySize,
                    MipLevels      = 0,
                    BindFlags      = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    CpuAccessFlags = CpuAccessFlags.None,
                    Usage          = ResourceUsage.Default,
                    OptionFlags    = ResourceOptionFlags.GenerateMipMaps,
                    Format         = texture.Description.Format
                };
                textMip = new Texture3D(device, desc3D);
                break;

            default:
                throw new InvalidDataException("Input texture is invalid.");
            }

            using (var shaderRes = new ShaderResourceView(device, textMip))
            {
                device.ImmediateContext.CopySubresourceRegion(texture, 0, null, textMip, 0);
                device.ImmediateContext.GenerateMips(shaderRes);
            }
            return(textMip);
        }
        // Puvlix Methods
        public bool Initialize(SharpDX.Direct3D11.Device device, DSystemConfiguration configuration)
        {
            try
            {
                // Initialize and set up the render target description.
                Texture2DDescription textureDesc = new Texture2DDescription()
                {
                    // Shadow Map Texture size as a 1024x1024 Square
                    Width             = 1024,
                    Height            = 1024,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = Format.R32G32B32A32_Float,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = ResourceUsage.Default,
                    BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    OptionFlags       = ResourceOptionFlags.None
                };

                // Create the render target texture.
                RenderTargetTexture = new Texture2D(device, textureDesc);

                // Setup the description of the render target view.
                RenderTargetViewDescription renderTargetViewDesc = new RenderTargetViewDescription()
                {
                    Format    = textureDesc.Format,
                    Dimension = RenderTargetViewDimension.Texture2D,
                };
                renderTargetViewDesc.Texture2D.MipSlice = 0;

                // Create the render target view.
                RenderTargetView = new RenderTargetView(device, RenderTargetTexture, renderTargetViewDesc);

                // Setup the description of the shader resource view.
                ShaderResourceViewDescription shaderResourceViewDesc = new ShaderResourceViewDescription()
                {
                    Format    = textureDesc.Format,
                    Dimension = ShaderResourceViewDimension.Texture2D,
                };
                shaderResourceViewDesc.Texture2D.MipLevels       = 1;
                shaderResourceViewDesc.Texture2D.MostDetailedMip = 0;

                // Create the render target view.
                ShaderResourceView = new ShaderResourceView(device, RenderTargetTexture, shaderResourceViewDesc);

                // Initialize and Set up the description of the depth buffer.
                Texture2DDescription depthStencilDesc = new Texture2DDescription()
                {
                    Width             = 1024,
                    Height            = 1024,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = Format.D24_UNorm_S8_UInt,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = ResourceUsage.Default,
                    BindFlags         = BindFlags.DepthStencil,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    OptionFlags       = ResourceOptionFlags.None
                };

                // Create the texture for the depth buffer using the filled out description.
                DepthStencilBuffer = new Texture2D(device, depthStencilDesc);

                // Initailze the depth stencil view description.
                DepthStencilViewDescription deothStencilViewDesc = new DepthStencilViewDescription()
                {
                    Format    = Format.D24_UNorm_S8_UInt,
                    Dimension = DepthStencilViewDimension.Texture2D
                };
                deothStencilViewDesc.Texture2D.MipSlice = 0;

                // Create the depth stencil view.
                DepthStencilView = new DepthStencilView(device, DepthStencilBuffer, deothStencilViewDesc);

                // Setup the viewport for rendering.
                ViewPort = new ViewportF()
                {
                    Width    = 1024.0f,
                    Height   = 1024.0f,
                    MinDepth = 0.0f,
                    MaxDepth = 1.0f,
                    X        = 0.0f,
                    Y        = 0.0f
                };

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #37
0
        public void Initialize(RenderForm form)
        {
            this.RenderForm = form;

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

            // Create Device and SwapChain
            Device    device;
            SwapChain swapChain;

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain);

            this.Device           = device;
            this.ImmediateContext = device.ImmediateContext;
            this.SwapChain        = swapChain;

            // Ignore all windows events
            this.factory = this.SwapChain.GetParent <Factory>();
            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            this.BackBufferTexture = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            this.BackBufferRTV     = new RenderTargetView(device, this.BackBufferTexture);


            Texture2DDescription depthDesc = new Texture2DDescription();

            depthDesc.ArraySize                 = 1;
            depthDesc.BindFlags                 = BindFlags.DepthStencil;
            depthDesc.CpuAccessFlags            = CpuAccessFlags.None;
            depthDesc.Format                    = Format.D24_UNorm_S8_UInt;
            depthDesc.Height                    = form.ClientSize.Height;
            depthDesc.Width                     = form.ClientSize.Width;
            depthDesc.MipLevels                 = 1;
            depthDesc.SampleDescription.Count   = 1;
            depthDesc.SampleDescription.Quality = 0;
            depthDesc.Usage                     = ResourceUsage.Default;

            this.DepthStencilTexture = new Texture2D(this.Device, depthDesc);

            ShaderResourceViewDescription depthSRVdesc;

            depthSRVdesc.Dimension                 = ShaderResourceViewDimension.Texture2D;
            depthSRVdesc.Format                    = Format.D24_UNorm_S8_UInt;
            depthSRVdesc.Texture2D.MipLevels       = 1;
            depthSRVdesc.Texture2D.MostDetailedMip = 1;

            this.DepthStencilView = new DepthStencilView(this.Device, this.DepthStencilTexture);

            this.ImmediateContext.Rasterizer.SetViewport(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));

            this.ImmediateContext.OutputMerger.SetTargets(this.BackBufferRTV);
            this.ImmediateContext.OutputMerger.SetRenderTargets(this.DepthStencilView, this.BackBufferRTV);
        }
Example #38
0
        public void Initialize(int monitor)
        {
            const int graphicsCardAdapter = 0;
            Adapter1  adapter;

            try
            {
                adapter = new Factory1().GetAdapter1(graphicsCardAdapter);
            }
            catch (SharpDXException)
            {
                throw new DesktopDuplicationException("Could not find the specified graphics card adapter.");
            }

            Output output;

            using (adapter)
            {
                _device = new Device(adapter);

                try
                {
                    output = adapter.GetOutput(monitor);
                }
                catch (SharpDXException)
                {
                    throw new DesktopDuplicationException("Could not find the specified output device.");
                }
            }

            using (output)
                using (var output1 = output.QueryInterface <Output1>())
                {
                    _outputDesc  = output.Description;
                    _textureDesc = new Texture2DDescription
                    {
                        CpuAccessFlags    = CpuAccessFlags.Read,
                        BindFlags         = BindFlags.None,
                        Format            = Format.B8G8R8A8_UNorm,
                        Width             = _outputDesc.DesktopBounds.GetWidth(),
                        Height            = _outputDesc.DesktopBounds.GetHeight(),
                        OptionFlags       = ResourceOptionFlags.None,
                        MipLevels         = 1,
                        ArraySize         = 1,
                        SampleDescription = { Count = 1, Quality = 0 },
                        Usage             = ResourceUsage.Staging
                    };

                    try
                    {
                        _deskDupl = output1.DuplicateOutput(_device);
                    }
                    catch (SharpDXException ex)
                    {
                        if (ex.ResultCode.Code == SharpDX.DXGI.ResultCode.NotCurrentlyAvailable.Result.Code)
                        {
                            throw new DesktopDuplicationException(
                                      "There is already the maximum number of applications using the Desktop Duplication API running, please close one of the applications and try again.");
                        }
                    }
                }

            _currentMonitor = monitor;
            _screenHelper   = new ScreenHelper();
        }
Example #39
0
        private Texture LoadTextureFromFile(string fileName, bool generateMips, int mipLevels = -1)
        {
            BitmapDecoder decoder = new BitmapDecoder(_imagingFactory,
                                                      fileName, DecodeOptions.CacheOnDemand);
            BitmapFrameDecode bitmapFirstFrame = decoder.GetFrame(0);

            Utilities.Dispose(ref decoder);

            FormatConverter formatConverter = new FormatConverter(_imagingFactory);

            formatConverter.Initialize(bitmapFirstFrame, PixelFormat.Format32bppRGBA,
                                       BitmapDitherType.None, null, 0.0f, BitmapPaletteType.Custom);

            int        stride = formatConverter.Size.Width * 4;
            DataStream buffer = new DataStream(
                formatConverter.Size.Height * stride, true, true);

            formatConverter.CopyPixels(stride, buffer);

            int width  = formatConverter.Size.Width;
            int height = formatConverter.Size.Height;
            Texture2DDescription texture2DDescription = new Texture2DDescription()
            {
                Width             = width,
                Height            = height,
                MipLevels         = (generateMips ? 0 : 1),
                ArraySize         = 1,
                Format            = Format.R8G8B8A8_UNorm,
                SampleDescription = _sampleDescription,
                Usage             = ResourceUsage.Default,
                BindFlags         = (
                    generateMips ?
                    BindFlags.ShaderResource | BindFlags.RenderTarget : BindFlags.ShaderResource
                    ),
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = (
                    generateMips ?
                    ResourceOptionFlags.GenerateMipMaps :
                    ResourceOptionFlags.None
                    )
            };

            Texture2D textureObject;

            if (generateMips)
            {
                textureObject = new Texture2D(_directX3DGraphics.Device, texture2DDescription);
            }
            else
            {
                DataRectangle dataRectangle = new DataRectangle(buffer.DataPointer, stride);
                textureObject = new Texture2D(_directX3DGraphics.Device, texture2DDescription, dataRectangle);
            }

            ShaderResourceViewDescription shaderResourceViewDescription =
                new ShaderResourceViewDescription()
            {
                Dimension = ShaderResourceViewDimension.Texture2D,
                Format    = Format.R8G8B8A8_UNorm,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource
                {
                    MostDetailedMip = 0,
                    MipLevels       = (generateMips ? mipLevels : 1)
                }
            };
            ShaderResourceView shaderResourceView =
                new ShaderResourceView(_directX3DGraphics.Device, textureObject, shaderResourceViewDescription);

            if (generateMips)
            {
                DataBox dataBox = new DataBox(buffer.DataPointer, stride, 1);
                _directX3DGraphics.DeviceContext.UpdateSubresource(dataBox, textureObject, 0);
                _directX3DGraphics.DeviceContext.GenerateMips(shaderResourceView);
            }

            Utilities.Dispose(ref formatConverter);

            return(new Texture(textureObject, shaderResourceView, width, height, samplerState));
        }
        protected override void LoadContent()
        {
            _spriteBatch    = ToDisposeContent(new SpriteBatch(GraphicsDevice));
            _depthRectangle = new Rectangle(0, 0, RoomAliveToolkit.Kinect2Calibration.depthImageWidth, RoomAliveToolkit.Kinect2Calibration.depthImageHeight);

            int depthWidth  = RoomAliveToolkit.Kinect2Calibration.depthImageWidth;
            int depthHeight = RoomAliveToolkit.Kinect2Calibration.depthImageHeight;

            _roomAliveEffect = Content.Load <Effect>("Holographic");
            _fromUintEffect  = Content.Load <Effect>("FromUint");
            _gaussianEffect  = Content.Load <Effect>("BilateralFilter");

            _colorSamplerState = ToDisposeContent(SharpDX.Toolkit.Graphics.SamplerState.New(this.GraphicsDevice, new SamplerStateDescription()
            {
                Filter             = Filter.MinMagMipLinear,
                AddressU           = TextureAddressMode.Border,
                AddressV           = TextureAddressMode.Border,
                AddressW           = TextureAddressMode.Border,
                BorderColor        = new SharpDX.Color4(0.5f, 0.5f, 0.5f, 1.0f),
                ComparisonFunction = Comparison.Never,
                MaximumAnisotropy  = 16,
                MipLodBias         = 0,
                MinimumLod         = -float.MaxValue,
                MaximumLod         = float.MaxValue
            }));

            List <VertexPosition> vertices = new List <VertexPosition>();
            List <int>            indices  = new List <int>();

            // vertex buffer
            if (_camera.calibration != null)
            {
                var table = _camera.calibration.ComputeDepthFrameToCameraSpaceTable();
                for (int i = 0; i < depthHeight; i++)
                {
                    for (int j = 0; j < depthWidth; j++)
                    {
                        var point = table[RoomAliveToolkit.Kinect2Calibration.depthImageWidth * i + j];

                        vertices.Add(new VertexPosition(new SharpDX.Vector4(point.X, point.Y, j, i)));
                    }
                }


                for (int i = 0; i < depthHeight - 1; i++)
                {
                    for (int j = 0; j < depthWidth - 1; j++)
                    {
                        int baseIndex = depthWidth * i + j;
                        indices.Add(baseIndex);
                        indices.Add(baseIndex + depthWidth + 1);
                        indices.Add(baseIndex + 1);

                        indices.Add(baseIndex);
                        indices.Add(baseIndex + depthWidth);
                        indices.Add(baseIndex + depthWidth + 1);
                    }
                }

                _vertexArray = vertices.ToArray();
                _indexArray  = indices.ToArray();

                // build the plane geometry of the specified size and subdivision segments
                _geometry = ToDisposeContent(new GeometricPrimitive <VertexPosition>(GraphicsDevice, _vertexArray, _indexArray, true));
            }
            else
            {
                Console.WriteLine("Camera '{0}' is missing calibration", _camera.name);
                Visible = false;
                Enabled = false;
            }

            if (!string.IsNullOrEmpty(_colorImageFilePath))
            {
                _tex2DColorImage1 = SharpDX.Toolkit.Graphics.Texture2D.Load(GraphicsDevice, _colorImageFilePath, TextureFlags.ShaderResource, ResourceUsage.Dynamic);
                _tex2DColorImage2 = SharpDX.Toolkit.Graphics.Texture2D.Load(GraphicsDevice, _colorImageFilePath, TextureFlags.ShaderResource, ResourceUsage.Dynamic);
            }

            _imagingFactory = new SharpDX.WIC.ImagingFactory();
            if (!string.IsNullOrEmpty(_depthImageFilePath))
            {
                var depthImage = new RoomAliveToolkit.ShortImage(RoomAliveToolkit.Kinect2Calibration.depthImageWidth, RoomAliveToolkit.Kinect2Calibration.depthImageHeight);
                RoomAliveToolkit.ProjectorCameraEnsemble.LoadFromTiff(_imagingFactory, depthImage, _depthImageFilePath);

                UpdateDepthImage(this.GraphicsDevice, depthImage.DataIntPtr);
            }

            var floatDepthImageTextureDesc = new Texture2DDescription()
            {
                Width             = depthWidth,
                Height            = depthHeight,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = SharpDX.DXGI.Format.R32_Float,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
            };

            _floatDepthImageFinal   = ToDisposeContent(RenderTarget2D.New(GraphicsDevice, floatDepthImageTextureDesc));
            _floatDepthImageSubpass = ToDisposeContent(RenderTarget2D.New(GraphicsDevice, floatDepthImageTextureDesc));

            base.LoadContent();
        }
Example #41
0
            private void CreateWalkableTexture(IList <MapTile> tiles, int widthInTiles, int heightInTiles)
            {
                // create the texture description for the walkable map
                // it should have the same dimensions as the tile map
                var desc = new Texture2DDescription {
                    ArraySize         = 1,
                    BindFlags         = BindFlags.ShaderResource,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    Format            = Format.R8_UNorm,
                    Height            = heightInTiles,
                    Width             = widthInTiles,
                    MipLevels         = 1,
                    OptionFlags       = ResourceOptionFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = ResourceUsage.Default
                };

                // create the pixel data
                var colors = new List <byte>();

                for (var y = 0; y < heightInTiles; y++)
                {
                    for (var x = 0; x < widthInTiles; x++)
                    {
                        // walkable tiles are black, unwalkable tiles are white
                        colors.Add((byte)(tiles[x + widthInTiles * y].Walkable ? 0 : 255));
                    }
                }
                // do a bilinear smoothing on the walkable map, to smooth the transition between the normal and unwalkable textures
                for (var y = 0; y < heightInTiles; y++)
                {
                    for (var x = 0; x < widthInTiles; x++)
                    {
                        float temp = 0;
                        var   num  = 0;
                        for (var y1 = y - 1; y1 <= y + 1; y1++)
                        {
                            for (var x1 = x - 1; x1 <= x + 1; x1++)
                            {
                                if (y1 < 0 || y1 >= heightInTiles || x1 < 0 || x1 >= widthInTiles)
                                {
                                    continue;
                                }
                                temp += colors[x1 + y1 * widthInTiles];
                                num++;
                            }
                        }
                        colors[x + y * widthInTiles] = (byte)(temp / num);
                    }
                }

                // create the texture from the pixel data and create the ShaderResourceView
                var walkMap = new Texture2D(
                    _terrainRenderer._device,
                    desc,
                    new DataRectangle(widthInTiles * sizeof(byte), new DataStream(colors.ToArray(), false, false)));

                WalkableTiles = new ShaderResourceView(_terrainRenderer._device, walkMap);

                Util.ReleaseCom(ref walkMap);
            }
Example #42
0
        public static ShaderResourceView CreateTexture2DArray(Device device, DeviceContext context, string[] filePaths, TextureLoadOptions options)
        {
            var srcTex = new Texture2D[filePaths.Length];

            for (var i = 0; i < filePaths.Length; i++)
            {
                srcTex[i] = CreateTextureFromFile(device, filePaths[i], options);
            }
            var texElementDesc = srcTex[0].Description;

            var texArrayDesc = new Texture2DDescription {
                Width             = texElementDesc.Width,
                Height            = texElementDesc.Height,
                MipLevels         = texElementDesc.MipLevels,
                ArraySize         = srcTex.Length,
                Format            = texElementDesc.Format,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            };

            var texArray = new Texture2D(device, texArrayDesc);

            texArray.DebugName = "texture array: + " + filePaths.Aggregate((i, j) => i + ", " + j);
            for (int texElement = 0; texElement < srcTex.Length; texElement++)
            {
                for (int mipLevel = 0; mipLevel < texElementDesc.MipLevels; mipLevel++)
                {
                    int     mippedSize;
                    DataBox mappedTex2D;
                    mappedTex2D = context.MapSubresource(srcTex[texElement], mipLevel, 0, MapMode.Read, MapFlags.None, out mippedSize);

                    context.UpdateSubresource(
                        mappedTex2D,
                        texArray,
                        Resource.CalculateSubResourceIndex(mipLevel, texElement, texElementDesc.MipLevels)
                        );
                    context.UnmapSubresource(srcTex[texElement], mipLevel);
                }
            }
            var viewDesc = new ShaderResourceViewDescription {
                Format         = texArrayDesc.Format,
                Dimension      = ShaderResourceViewDimension.Texture2DArray,
                Texture2DArray = new ShaderResourceViewDescription.Texture2DArrayResource()
                {
                    MostDetailedMip = 0,
                    MipLevels       = texArrayDesc.MipLevels,
                    FirstArraySlice = 0,
                    ArraySize       = srcTex.Length
                }
            };

            var texArraySRV = new ShaderResourceView(device, texArray, viewDesc);

            Utilities.Dispose(ref texArray);
            for (int i = 0; i < srcTex.Length; i++)
            {
                Utilities.Dispose(ref srcTex[i]);
            }

            return(texArraySRV);
        }
Example #43
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // create d3d device and shaders
            var swapChainDesc = new SwapChainDescription
            {
                BufferCount       = 1,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = videoPanel1.Handle, // splitContainer1.Panel1.Handle,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard,
                SampleDescription = new SampleDescription(1, 0),
            };

            SharpDX.Direct3D11.Device.CreateWithSwapChain(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.Debug, swapChainDesc, out device, out swapChain);

            // render target
            renderTarget     = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            renderTargetView = new RenderTargetView(device, renderTarget);

            // depth buffer
            var depthBufferDesc = new Texture2DDescription()
            {
                Width             = videoPanel1.Width,
                Height            = videoPanel1.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.D32_Float, // necessary?
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None
            };

            depthStencil     = new Texture2D(device, depthBufferDesc);
            depthStencilView = new DepthStencilView(device, depthStencil);

            // viewport
            viewport = new Viewport(0, 0, videoPanel1.Width, videoPanel1.Height, 0f, 1f);

            // shaders
            var shaderByteCode = new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorVS.cso"));

            depthAndColorVS2 = new VertexShader(device, shaderByteCode);
            depthAndColorGS2 = new GeometryShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorGS.cso")));
            depthAndColorPS2 = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorPS.cso")));

            // depth stencil state
            var depthStencilStateDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                DepthWriteMask   = DepthWriteMask.All,
                DepthComparison  = Comparison.LessEqual,
                IsStencilEnabled = false,
            };

            depthStencilState = new DepthStencilState(device, depthStencilStateDesc);

            // rasterizer states
            var rasterizerStateDesc = new RasterizerStateDescription()
            {
                CullMode                = CullMode.None, // beware what this does to both shaders
                FillMode                = FillMode.Solid,
                IsDepthClipEnabled      = true,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled    = true,
            };

            rasterizerState = new RasterizerState(device, rasterizerStateDesc);

            // color sampler state
            var colorSamplerStateDesc = new SamplerStateDescription()
            {
                Filter      = Filter.MinMagMipLinear,
                AddressU    = TextureAddressMode.Border,
                AddressV    = TextureAddressMode.Border,
                AddressW    = TextureAddressMode.Border,
                BorderColor = new SharpDX.Color4(0.5f, 0.5f, 0.5f, 1.0f),
                //BorderColor = new SharpDX.Color4(0, 0, 0, 1.0f),
            };

            colorSamplerState = new SamplerState(device, colorSamplerStateDesc);

            // constant buffer
            var constantBufferDesc = new BufferDescription()
            {
                Usage               = ResourceUsage.Dynamic,
                BindFlags           = BindFlags.ConstantBuffer,
                SizeInBytes         = ConstantBuffer.size,
                CpuAccessFlags      = CpuAccessFlags.Write,
                StructureByteStride = 0,
                OptionFlags         = 0,
            };

            constantBuffer = new SharpDX.Direct3D11.Buffer(device, constantBufferDesc);

            // vertex layout is the same for all cameras
            vertexInputLayout = new InputLayout(device, shaderByteCode.Data, new[]
            {
                new InputElement("SV_POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
            });


            manipulator = new Kinect2ShaderDemo.Manipulator(videoPanel1, view, projection, viewport);
            manipulator.ViewMatrixChanged += manipulator_ViewMatrixChanged;

            // TODO: address when no file is loaded (disable everything except New)

            if (args.Length > 0)
            {
                path      = args[0];
                directory = Path.GetDirectoryName(path);
                LoadEnsemble();
            }



            Width  = Properties.Settings.Default.FormWidth;
            Height = Properties.Settings.Default.FormHeight;
            splitContainer1.SplitterDistance = Properties.Settings.Default.SplitterDistance;

            new System.Threading.Thread(RenderLoop).Start();
        }
Example #44
0
        public ProjectionMappingSample(string[] args)
        {
            // load ensemble.xml
            string path      = args[0];
            string directory = Path.GetDirectoryName(path);

            ensemble = RoomAliveToolkit.ProjectorCameraEnsemble.FromFile(path);

            // create d3d device
            var factory = new Factory();
            var adapter = factory.Adapters[0];

            device = new SharpDX.Direct3D11.Device(adapter, DeviceCreationFlags.None);

            // shaders
            depthAndColorShader       = new DepthAndColorShader(device);
            projectiveTexturingShader = new ProjectiveTexturingShader(device);
            passThroughShader         = new PassThrough(device, userViewTextureWidth, userViewTextureHeight);
            radialWobbleShader        = new RadialWobble(device, userViewTextureWidth, userViewTextureHeight);
            meshShader      = new MeshShader(device);
            fromUIntPS      = new FromUIntPS(device, depthImageWidth, depthImageHeight);
            bilateralFilter = new BilateralFilter(device, depthImageWidth, depthImageHeight);

            // create device objects for each camera
            foreach (var camera in ensemble.cameras)
            {
                cameraDeviceResources[camera] = new CameraDeviceResource(device, camera, renderLock, directory);
            }

            // one user view
            // user view render target, depth buffer, viewport for user view
            var userViewTextureDesc = new Texture2DDescription()
            {
                Width             = userViewTextureWidth,
                Height            = userViewTextureHeight,
                MipLevels         = 1, // revisit this; we may benefit from mipmapping?
                ArraySize         = 1,
                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
            };
            var userViewRenderTarget = new Texture2D(device, userViewTextureDesc);

            userViewRenderTargetView = new RenderTargetView(device, userViewRenderTarget);
            userViewSRV = new ShaderResourceView(device, userViewRenderTarget);

            var filteredUserViewRenderTarget = new Texture2D(device, userViewTextureDesc);

            filteredUserViewRenderTargetView = new RenderTargetView(device, filteredUserViewRenderTarget);
            filteredUserViewSRV = new ShaderResourceView(device, filteredUserViewRenderTarget);

            // user view depth buffer
            var userViewDpethBufferDesc = new Texture2DDescription()
            {
                Width             = userViewTextureWidth,
                Height            = userViewTextureHeight,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.D32_Float, // necessary?
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None
            };
            var userViewDepthStencil = new Texture2D(device, userViewDpethBufferDesc);

            userViewDepthStencilView = new DepthStencilView(device, userViewDepthStencil);

            // user view viewport
            userViewViewport = new Viewport(0, 0, userViewTextureWidth, userViewTextureHeight, 0f, 1f);


            // create a form for each projector
            foreach (var projector in ensemble.projectors)
            {
                var form = new ProjectorForm(factory, device, renderLock, projector);
                if (fullScreenEnabled)
                {
                    form.FullScreen = fullScreenEnabled; // TODO: fix this so can be called after Show
                }
                form.Show();
                projectorForms.Add(form);
            }

            // example 3d object
            var mesh = Mesh.FromOBJFile("Content/FloorPlan.obj");

            meshDeviceResources = new MeshDeviceResources(device, imagingFactory, mesh);


            userViewForm = new MainForm(factory, device, renderLock);
            userViewForm.Show();
            //userViewForm.ClientSize = new System.Drawing.Size(1920, 1080);


            userViewForm.videoPanel1.MouseClick += videoPanel1_MouseClick;

            // connect to local camera to acquire head position
            if (localHeadTrackingEnabled)
            {
                localKinectSensor = KinectSensor.GetDefault();
                bodyFrameReader   = localKinectSensor.BodyFrameSource.OpenReader();
                localKinectSensor.Open();
                Console.WriteLine("connected to local camera");
                new System.Threading.Thread(LocalBodyLoop).Start();
            }


            if (liveDepthEnabled)
            {
                foreach (var cameraDeviceResource in cameraDeviceResources.Values)
                {
                    cameraDeviceResource.StartLive();
                }
            }


            new System.Threading.Thread(RenderLoop).Start();
        }
Example #45
0
        public int SetupVideo(AVCodec *codec)
        {
            hwAccelSuccess = false;

            if (opt.video.HWAcceleration && VideoAcceleration.CheckCodecSupport(codec))
            {
                if (demuxer.decCtx.va.hw_device_ctx == null)
                {
                    demuxer.decCtx.va.Init(demuxer.decCtx.device);
                }

                if (demuxer.decCtx.va.hw_device_ctx != null)
                {
                    codecCtx->hw_device_ctx = av_buffer_ref(demuxer.decCtx.va.hw_device_ctx);
                    hwAccelSuccess          = true;
                }
            }

            codecCtx->thread_count = Math.Min(opt.video.DecoderThreads, codecCtx->codec_id == AV_CODEC_ID_HEVC ? 32 : 16);
            codecCtx->thread_type  = 0;
            //vCodecCtx->active_thread_type = FF_THREAD_FRAME;
            //vCodecCtx->active_thread_type = FF_THREAD_SLICE;
            codecCtx->thread_safe_callbacks = 1;

            // Hardware Texture (NV12 | P010) | Format will be set from source
            textDescHW = new Texture2DDescription()
            {
                Usage = ResourceUsage.Default,

                Width  = codecCtx->width,
                Height = codecCtx->height,

                BindFlags      = BindFlags.Decoder,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,

                SampleDescription = new SampleDescription(1, 0),
                ArraySize         = 1,
                MipLevels         = 1
            };

            // YUV Pixel Shader (textureY | textureU | textureV)
            textDescYUV = new Texture2DDescription()
            {
                Usage  = ResourceUsage.Immutable,
                Format = Format.R8_UNorm,

                Width  = codecCtx->width,
                Height = codecCtx->height,

                BindFlags      = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,

                SampleDescription = new SampleDescription(1, 0),
                ArraySize         = 1,
                MipLevels         = 1
            };

            // RGBA Sws Scale
            textDescRGB = new Texture2DDescription()
            {
                Usage  = ResourceUsage.Immutable,
                Format = Format.R8G8B8A8_UNorm,

                Width  = codecCtx->width,
                Height = codecCtx->height,

                BindFlags      = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,

                SampleDescription = new SampleDescription(1, 0),
                ArraySize         = 1,
                MipLevels         = 1
            };

            return(0);
        }
Example #46
0
 /// <summary>
 /// Creates a new texture from a <see cref="Texture2DDescription"/>.
 /// </summary>
 /// <param name="device">The <see cref="DirectXDevice"/>.</param>
 /// <param name="description">The description.</param>
 /// <returns>
 /// A new instance of <see cref="TextureCube"/> class.
 /// </returns>
 /// <msdn-id>ff476521</msdn-id>
 /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
 /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
 public static TextureCube New(DirectXDevice device, Texture2DDescription description)
 {
     return(new TextureCube(device, description));
 }
Example #47
0
 internal RenderTargetCube(GraphicsDevice device, Texture2DDescription description2D, params DataBox[] dataBoxes)
     : base(device, description2D, dataBoxes)
 {
     Initialize(Resource);
 }
Example #48
0
            public void OnDeviceInit()
            {
                Texture2DDescription desc = new Texture2DDescription();

                desc.Width                     = Size.X;
                desc.Height                    = Size.Y;
                desc.Format                    = m_resourceFormat;
                desc.ArraySize                 = 1;
                desc.MipLevels                 = 1;
                desc.BindFlags                 = BindFlags.ShaderResource | BindFlags.DepthStencil;
                desc.Usage                     = ResourceUsage.Default;
                desc.CpuAccessFlags            = 0;
                desc.SampleDescription.Count   = m_samplesCount;
                desc.SampleDescription.Quality = m_samplesQuality;
                desc.OptionFlags               = 0;
                m_resource                     = new Texture2D(MyRender11.Device, desc);
                m_resource.DebugName           = Name;

                DepthStencilViewDescription dsvDesc = new DepthStencilViewDescription();

                dsvDesc.Format = m_dsvFormat;
                if (m_samplesCount == 1)
                {
                    dsvDesc.Dimension          = DepthStencilViewDimension.Texture2D;
                    dsvDesc.Flags              = DepthStencilViewFlags.None;
                    dsvDesc.Texture2D.MipSlice = 0;
                }
                else
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                    dsvDesc.Flags     = DepthStencilViewFlags.None;
                }
                m_dsv = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);
                if (m_samplesCount == 1)
                {
                    dsvDesc.Dimension          = DepthStencilViewDimension.Texture2D;
                    dsvDesc.Flags              = DepthStencilViewFlags.ReadOnlyDepth;
                    dsvDesc.Texture2D.MipSlice = 0;
                }
                else
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                    dsvDesc.Flags     = DepthStencilViewFlags.ReadOnlyDepth;
                }
                m_dsv_roDepth = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);
                if (m_samplesCount == 1)
                {
                    dsvDesc.Dimension          = DepthStencilViewDimension.Texture2D;
                    dsvDesc.Flags              = DepthStencilViewFlags.ReadOnlyStencil;
                    dsvDesc.Texture2D.MipSlice = 0;
                }
                else
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                    dsvDesc.Flags     = DepthStencilViewFlags.ReadOnlyStencil;
                }
                m_dsv_roStencil = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);
                dsvDesc.Flags   = DepthStencilViewFlags.ReadOnlyStencil | DepthStencilViewFlags.ReadOnlyDepth;
                if (m_samplesCount == 1)
                {
                    dsvDesc.Dimension          = DepthStencilViewDimension.Texture2D;
                    dsvDesc.Texture2D.MipSlice = 0;
                }
                else
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                }
                m_dsv_ro = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);

                ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription();

                srvDesc.Format = m_srvDepthFormat;
                if (m_samplesCount == 1)
                {
                    srvDesc.Dimension                 = ShaderResourceViewDimension.Texture2D;
                    srvDesc.Texture2D.MipLevels       = -1;
                    srvDesc.Texture2D.MostDetailedMip = 0;
                }
                else
                {
                    srvDesc.Dimension = ShaderResourceViewDimension.Texture2DMultisampled;
                }
                m_srvDepth.OnDeviceInit(this, srvDesc);
                srvDesc.Format = m_srvStencilFormat;
                if (m_samplesCount == 1)
                {
                    srvDesc.Dimension                 = ShaderResourceViewDimension.Texture2D;
                    srvDesc.Texture2D.MipLevels       = -1;
                    srvDesc.Texture2D.MostDetailedMip = 0;
                }
                else
                {
                    srvDesc.Dimension = ShaderResourceViewDimension.Texture2DMultisampled;
                }
                m_srvStencil.OnDeviceInit(this, srvDesc);
            }
Example #49
0
        void OnResize()
        {
            Helpers.Dispose(ref depthBuffer);
            Helpers.Dispose(ref dsv);
            Helpers.Dispose(ref colorBuffer);
            Helpers.Dispose(ref rtv);

            var resolution = Surface.Resolution;

            TextBatcher.Resolution   = resolution;
            UILineBatcher.Resolution = resolution;

            var sampleDescription = new SampleDescription(4, 0);

            depthBuffer = new Texture2D(Surface.Device, new Texture2DDescription
            {
                Format            = Format.R32_Typeless,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = resolution.X,
                Height            = resolution.Y,
                SampleDescription = sampleDescription,
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            });
            depthBuffer.DebugName = "Depth Buffer";

            var depthStencilViewDescription = new DepthStencilViewDescription
            {
                Flags     = DepthStencilViewFlags.None,
                Dimension = DepthStencilViewDimension.Texture2DMultisampled,
                Format    = Format.D32_Float,
                Texture2D = { MipSlice = 0 }
            };

            dsv           = new DepthStencilView(Surface.Device, depthBuffer, depthStencilViewDescription);
            dsv.DebugName = "Depth DSV";

            //Using a 64 bit texture in the demos for lighting is pretty silly. But we gon do it.
            var description = new Texture2DDescription
            {
                Format            = Format.R16G16B16A16_Float,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = resolution.X,
                Height            = resolution.Y,
                SampleDescription = sampleDescription,
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            };

            colorBuffer           = new Texture2D(Surface.Device, description);
            colorBuffer.DebugName = "Color Buffer";

            rtv           = new RenderTargetView(Surface.Device, colorBuffer);
            rtv.DebugName = "Color RTV";

            description.SampleDescription = new SampleDescription(1, 0);
            resolvedColorBuffer           = new Texture2D(Surface.Device, description);
            resolvedColorBuffer.DebugName = "Resolved Color Buffer";

            resolvedSRV           = new ShaderResourceView(Surface.Device, resolvedColorBuffer);
            resolvedSRV.DebugName = "Resolved Color SRV";

            resolvedRTV           = new RenderTargetView(Surface.Device, resolvedColorBuffer);
            resolvedRTV.DebugName = "Resolved Color RTV";
        }
Example #50
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Texture2DBase" /> class.
 /// </summary>
 /// <param name="device">The <see cref="GraphicsDevice"/>.</param>
 /// <param name="description2D">The description.</param>
 /// <param name="dataBoxes">A variable-length parameters list containing data rectangles.</param>
 /// <msdn-id>ff476521</msdn-id>
 /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>
 /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>
 protected internal Texture2DBase(GraphicsDevice device, Texture2DDescription description2D, DataBox[] dataBoxes)
     : base(device, description2D)
 {
     Resource = new Direct3D11.Texture2D(device, description2D, dataBoxes);
 }
Example #51
0
            // encapsulates d3d resources for a camera
            public CameraDeviceResource(SharpDX.Direct3D11.Device device, ProjectorCameraEnsemble.Camera camera, Object renderLock, string directory)
            {
                this.device     = device;
                this.camera     = camera;
                this.renderLock = renderLock;

                // Kinect depth image
                var depthImageTextureDesc = new Texture2DDescription()
                {
                    Width             = 512,
                    Height            = 424,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = SharpDX.DXGI.Format.R16_UInt,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                    Usage             = ResourceUsage.Dynamic,
                    BindFlags         = BindFlags.ShaderResource,
                    CpuAccessFlags    = CpuAccessFlags.Write,
                };

                depthImageTexture   = new Texture2D(device, depthImageTextureDesc);
                depthImageTextureRV = new ShaderResourceView(device, depthImageTexture);

                var floatDepthImageTextureDesc = new Texture2DDescription()
                {
                    Width             = 512,
                    Height            = 424,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = SharpDX.DXGI.Format.R32_Float,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                    Usage             = ResourceUsage.Default,
                    BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    CpuAccessFlags    = CpuAccessFlags.None,
                };

                floatDepthImageTexture          = new Texture2D(device, floatDepthImageTextureDesc);
                floatDepthImageRV               = new ShaderResourceView(device, floatDepthImageTexture);
                floatDepthImageRenderTargetView = new RenderTargetView(device, floatDepthImageTexture);

                floatDepthImageTexture2          = new Texture2D(device, floatDepthImageTextureDesc);
                floatDepthImageRV2               = new ShaderResourceView(device, floatDepthImageTexture2);
                floatDepthImageRenderTargetView2 = new RenderTargetView(device, floatDepthImageTexture2);

                // Kinect color image
                var colorImageStagingTextureDesc = new Texture2DDescription()
                {
                    Width             = colorImageWidth,
                    Height            = colorImageHeight,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                    Usage             = ResourceUsage.Dynamic,
                    BindFlags         = BindFlags.ShaderResource,
                    CpuAccessFlags    = CpuAccessFlags.Write
                };

                colorImageStagingTexture = new Texture2D(device, colorImageStagingTextureDesc);

                var colorImageTextureDesc = new Texture2DDescription()
                {
                    Width             = colorImageWidth,
                    Height            = colorImageHeight,
                    MipLevels         = 0,
                    ArraySize         = 1,
                    Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                    Usage             = ResourceUsage.Default,
                    BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    OptionFlags       = ResourceOptionFlags.GenerateMipMaps
                };

                colorImageTexture   = new Texture2D(device, colorImageTextureDesc);
                colorImageTextureRV = new ShaderResourceView(device, colorImageTexture);

                // vertex buffer
                var table       = camera.calibration.ComputeDepthFrameToCameraSpaceTable();
                int numVertices = 6 * (depthImageWidth - 1) * (depthImageHeight - 1);
                var vertices    = new VertexPosition[numVertices];

                Int3[] quadOffsets = new Int3[]
                {
                    new Int3(0, 0, 0),
                    new Int3(1, 0, 0),
                    new Int3(0, 1, 0),
                    new Int3(1, 0, 0),
                    new Int3(1, 1, 0),
                    new Int3(0, 1, 0),
                };

                int vertexIndex = 0;

                for (int y = 0; y < depthImageHeight - 1; y++)
                {
                    for (int x = 0; x < depthImageWidth - 1; x++)
                    {
                        for (int i = 0; i < 6; i++)
                        {
                            int vertexX = x + quadOffsets[i].X;
                            int vertexY = y + quadOffsets[i].Y;

                            var point = table[depthImageWidth * vertexY + vertexX];

                            var vertex = new VertexPosition();
                            vertex.position         = new SharpDX.Vector4(point.X, point.Y, vertexX, vertexY);
                            vertices[vertexIndex++] = vertex;
                        }
                    }
                }

                var stream = new DataStream(numVertices * VertexPosition.SizeInBytes, true, true);

                stream.WriteRange(vertices);
                stream.Position = 0;

                var vertexBufferDesc = new BufferDescription()
                {
                    BindFlags      = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.None,
                    Usage          = ResourceUsage.Default,
                    SizeInBytes    = numVertices * VertexPosition.SizeInBytes,
                };

                vertexBuffer = new SharpDX.Direct3D11.Buffer(device, stream, vertexBufferDesc);

                vertexBufferBinding = new VertexBufferBinding(vertexBuffer, VertexPosition.SizeInBytes, 0);

                stream.Dispose();

                var colorImage = new RoomAliveToolkit.ARGBImage(colorImageWidth, colorImageHeight);

                ProjectorCameraEnsemble.LoadFromTiff(imagingFactory, colorImage, directory + "/camera" + camera.name + "/colorDark.tiff");

                var depthImage = new RoomAliveToolkit.ShortImage(depthImageWidth, depthImageHeight);

                ProjectorCameraEnsemble.LoadFromTiff(imagingFactory, depthImage, directory + "/camera" + camera.name + "/mean.tiff");

                lock (renderLock) // necessary?
                {
                    UpdateColorImage(device.ImmediateContext, colorImage.DataIntPtr);
                    UpdateDepthImage(device.ImmediateContext, depthImage.DataIntPtr);
                }

                colorImage.Dispose();
                depthImage.Dispose();
            }
Example #52
0
        private unsafe static Texture2D CreateTexture(Bitmap bmp, bool withMips)
        {
            Texture2D tex      = null;
            var       ctx      = WorldFrame.Instance.GraphicsContext;
            var       eventObj = new EventWaitHandle(false, EventResetMode.AutoReset);

            var colors = new byte[bmp.Width * bmp.Height * 4];
            var bmpd   = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly,
                                      PixelFormat.Format32bppArgb);

            fixed(byte *ptr = colors)
            UnsafeNativeMethods.CopyMemory(ptr, (byte *)bmpd.Scan0.ToPointer(), colors.Length);

            var totalMips = 1;

            if (withMips)
            {
                var l2H = (int)Math.Log(bmp.Height, 2);
                var l2W = (int)Math.Log(bmp.Width, 2);
                totalMips = Math.Min(l2H, l2W) + 1;
            }

            InvokeOrExecuteOnGpu(() =>
            {
                var texDesc = new Texture2DDescription
                {
                    ArraySize         = 1,
                    BindFlags         = BindFlags.ShaderResource,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    Format            = Format.B8G8R8A8_UNorm,
                    Width             = bmp.Width,
                    Height            = bmp.Height,
                    MipLevels         = totalMips,
                    OptionFlags       = withMips ? ResourceOptionFlags.GenerateMipMaps : ResourceOptionFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = ResourceUsage.Default
                };

                if (withMips)
                {
                    texDesc.BindFlags |= BindFlags.RenderTarget;
                }

                var gputex = new Texture2D(ctx.Device, texDesc);
                ctx.Context.UpdateSubresource(colors, gputex, 0, 4 * bmp.Width);

                if (withMips)
                {
                    var srvd = new ShaderResourceView(ctx.Device, gputex, new ShaderResourceViewDescription
                    {
                        Format    = Format.B8G8R8A8_UNorm,
                        Dimension = ShaderResourceViewDimension.Texture2D,
                        Texture2D = new ShaderResourceViewDescription.Texture2DResource
                        {
                            MipLevels       = totalMips,
                            MostDetailedMip = 0
                        }
                    });

                    ctx.Context.GenerateMips(srvd);
                    srvd.Dispose();
                }

                texDesc.BindFlags      = BindFlags.None;
                texDesc.CpuAccessFlags = CpuAccessFlags.Read;
                texDesc.OptionFlags    = ResourceOptionFlags.None;
                texDesc.Usage          = ResourceUsage.Staging;

                tex = new Texture2D(ctx.Device, texDesc);
                for (var i = 0; i < totalMips; ++i)
                {
                    ctx.Context.CopySubresourceRegion(gputex, i, null, tex, i);
                }

                gputex.Dispose();

                eventObj.Set();
            }, eventObj);

            return(tex);
        }
Example #53
0
 internal TextureCube(DirectXDevice device, Texture2DDescription description2D, params DataBox[] dataBoxes)
     : base(device, description2D, dataBoxes)
 {
 }
Example #54
0
        private void BuildDynamicCubeMapViews()
        {
            // create the render target cube map texture
            var texDesc = new Texture2DDescription()
            {
                Width             = CubeMapSize,
                Height            = CubeMapSize,
                MipLevels         = 0,
                ArraySize         = 6,
                SampleDescription = new SampleDescription(1, 0),
                Format            = Format.R8G8B8A8_UNorm,
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.GenerateMipMaps | ResourceOptionFlags.TextureCube
            };
            var cubeTex = new Texture2D(Device, texDesc);

            cubeTex.DebugName = "dynamic cubemap texture";
            // create the render target view array
            var rtvDesc = new RenderTargetViewDescription()
            {
                Format    = texDesc.Format,
                Dimension = RenderTargetViewDimension.Texture2DArray,
                ArraySize = 1,
                MipSlice  = 0
            };

            for (int i = 0; i < 6; i++)
            {
                rtvDesc.FirstArraySlice = i;
                _dynamicCubeMapRTV[i]   = new RenderTargetView(Device, cubeTex, rtvDesc);
            }
            // Create the shader resource view that we will bind to our effect for the cubemap
            var srvDesc = new ShaderResourceViewDescription()
            {
                Format          = texDesc.Format,
                Dimension       = ShaderResourceViewDimension.TextureCube,
                MostDetailedMip = 0,
                MipLevels       = -1
            };

            _dynamicCubeMapSRV = new ShaderResourceView(Device, cubeTex, srvDesc);
            // release the texture, now that it is saved to the views
            Util.ReleaseCom(ref cubeTex);
            // create the depth/stencil texture
            var depthTexDesc = new Texture2DDescription()
            {
                Width             = CubeMapSize,
                Height            = CubeMapSize,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = new SampleDescription(1, 0),
                Format            = Format.D32_Float,
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            };
            var depthTex = new Texture2D(Device, depthTexDesc);

            depthTex.DebugName = "dynamic cubemap depthmap";
            var dsvDesc = new DepthStencilViewDescription()
            {
                Format    = depthTexDesc.Format,
                Flags     = DepthStencilViewFlags.None,
                Dimension = DepthStencilViewDimension.Texture2D,
                MipSlice  = 0,
            };

            _dynamicCubeMapDSV = new DepthStencilView(Device, depthTex, dsvDesc);

            Util.ReleaseCom(ref depthTex);
            // create the viewport for rendering the cubemap faces
            _cubeMapViewPort = new Viewport(0, 0, CubeMapSize, CubeMapSize, 0, 1.0f);
        }
Example #55
0
        /// <summary>
        /// the receive thread runs though this loop until told to exit
        /// </summary>
        void ReceiveThreadProc()
        {
            bool newVideo = true;

            using var deviceHandle = deviceProvider.GetHandle();
            var device = deviceHandle.Resource;

            while (!_exitThread && _recvInstancePtr != IntPtr.Zero)
            {
                // The descriptors
                NDIlib.video_frame_v2_t videoFrame    = new NDIlib.video_frame_v2_t();
                NDIlib.audio_frame_v2_t audioFrame    = new NDIlib.audio_frame_v2_t();
                NDIlib.metadata_frame_t metadataFrame = new NDIlib.metadata_frame_t();

                switch (NDIlib.recv_capture_v2(_recvInstancePtr, ref videoFrame, ref audioFrame, ref metadataFrame, 1000))
                {
                // No data
                case NDIlib.frame_type_e.frame_type_none:
                    // No data received
                    break;

                // frame settings - check for extended functionality
                case NDIlib.frame_type_e.frame_type_status_change:
                    // check for PTZ
                    IsPtz = NDIlib.recv_ptz_is_supported(_recvInstancePtr);

                    // Check for recording
                    IsRecordingSupported = NDIlib.recv_recording_is_supported(_recvInstancePtr);

                    // Check for a web control URL
                    // We must free this string ptr if we get one.
                    IntPtr webUrlPtr = NDIlib.recv_get_web_control(_recvInstancePtr);
                    if (webUrlPtr == IntPtr.Zero)
                    {
                        WebControlUrl = String.Empty;
                    }
                    else
                    {
                        // convert to managed String
                        WebControlUrl = UTF.Utf8ToString(webUrlPtr);

                        // Don't forget to free the string ptr
                        NDIlib.recv_free_string(_recvInstancePtr, webUrlPtr);
                    }

                    break;

                // Video data
                case NDIlib.frame_type_e.frame_type_video:

                    // if not enabled, just discard
                    // this can also occasionally happen when changing sources
                    if (!_videoEnabled || videoFrame.p_data == IntPtr.Zero)
                    {
                        // alreays free received frames
                        NDIlib.recv_free_video_v2(_recvInstancePtr, ref videoFrame);

                        break;
                    }

                    // get all our info so that we can free the frame
                    int yres = (int)videoFrame.yres;
                    int xres = (int)videoFrame.xres;

                    // quick and dirty aspect ratio correction for non-square pixels - SD 4:3, 16:9, etc.
                    double dpiX = 96.0 * (videoFrame.picture_aspect_ratio / ((double)xres / (double)yres));

                    int stride     = (int)videoFrame.line_stride_in_bytes;
                    int bufferSize = yres * stride;


                    if (bufferSize != buffer01Size)
                    {
                        buffer0      = Marshal.ReAllocCoTaskMem(buffer0, bufferSize);
                        buffer1      = Marshal.ReAllocCoTaskMem(buffer1, bufferSize);
                        buffer01Size = bufferSize;
                    }

                    // Copy data
                    unsafe
                    {
                        byte *dst = (byte *)buffer0.ToPointer();
                        byte *src = (byte *)videoFrame.p_data.ToPointer();

                        for (int y = 0; y < yres; y++)
                        {
                            memcpy(dst, src, stride);
                            dst += stride;
                            src += stride;
                        }
                    }

                    // swap
                    IntPtr temp = buffer0;
                    buffer0 = buffer1;
                    buffer1 = temp;

                    SharpDX.DXGI.Format texFmt;
                    switch (videoFrame.FourCC)
                    {
                    case NDIlib.FourCC_type_e.FourCC_type_BGRA:
                        texFmt = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
                        break;

                    case NDIlib.FourCC_type_e.FourCC_type_BGRX:
                        texFmt = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
                        break;

                    case NDIlib.FourCC_type_e.FourCC_type_RGBA:
                        texFmt = SharpDX.DXGI.Format.R8G8B8A8_UNorm;
                        break;

                    case NDIlib.FourCC_type_e.FourCC_type_RGBX:
                        texFmt = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
                        break;

                    default:
                        texFmt = SharpDX.DXGI.Format.Unknown;         // TODO: need to handle other video formats
                        break;
                    }

                    if (newVideo)     // it's the first time we enter the while loop, so cerate a new texture
                    {
                        textureDesc = new Texture2DDescription()
                        {
                            Width             = xres,
                            Height            = yres,
                            MipLevels         = 1,
                            ArraySize         = 1,
                            Format            = texFmt,
                            SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                            Usage             = ResourceUsage.Default,
                            BindFlags         = BindFlags.ShaderResource,
                            CpuAccessFlags    = CpuAccessFlags.None,
                            OptionFlags       = ResourceOptionFlags.None
                        };

                        outputTexture = new Texture2D(device, textureDesc);

                        newVideo = false;
                    }

                    try
                    {
                        DataBox srcBox = new DataBox(buffer1);
                        device.ImmediateContext.UpdateSubresource(srcBox, outputTexture, 0);

                        videoFrames.OnNext(outputTexture);
                    }
                    finally
                    {
                        device.ImmediateContext.UnmapSubresource(outputTexture, 0);
                    }


                    // free frames that were received AFTER use!
                    // This writepixels call is dispatched, so we must do it inside this scope.
                    NDIlib.recv_free_video_v2(_recvInstancePtr, ref videoFrame);

                    break;

                // audio is beyond the scope of this example
                case NDIlib.frame_type_e.frame_type_audio:

                    // if no audio or disabled, nothing to do
                    if (!_audioEnabled || audioFrame.p_data == IntPtr.Zero || audioFrame.no_samples == 0)
                    {
                        // alreays free received frames
                        NDIlib.recv_free_audio_v2(_recvInstancePtr, ref audioFrame);

                        break;
                    }

                    //// if the audio format changed, we need to reconfigure the audio device
                    //bool formatChanged = false;

                    //// make sure our format has been created and matches the incomming audio
                    //if (_waveFormat == null ||
                    //    _waveFormat.Channels != audioFrame.no_channels ||
                    //    _waveFormat.SampleRate != audioFrame.sample_rate)
                    //{
                    //    //// Create a wavformat that matches the incomming frames
                    //    //_waveFormat = WaveFormat.CreateIeeeFloatWaveFormat((int)audioFrame.sample_rate, (int)audioFrame.no_channels);

                    //    formatChanged = true;
                    //}

                    //// set up our audio buffer if needed
                    //if (_bufferedProvider == null || formatChanged)
                    //{
                    //    _bufferedProvider = new BufferedWaveProvider(_waveFormat);
                    //    _bufferedProvider.DiscardOnBufferOverflow = true;
                    //}

                    //// set up our multiplexer used to mix down to 2 output channels)
                    //if (_multiplexProvider == null || formatChanged)
                    //{
                    //    _multiplexProvider = new MultiplexingWaveProvider(new List<IWaveProvider>() { _bufferedProvider }, 2);
                    //}

                    //    // set up our audio output device
                    //    if (_wasapiOut == null || formatChanged)
                    //    {
                    //        // We can't guarantee audio sync or buffer fill, that's beyond the scope of this example.
                    //        // This is close enough to show that audio is received and converted correctly.
                    //        _wasapiOut = new WasapiOut(NAudio.CoreAudioApi.AudioClientShareMode.Shared, 50);
                    //        _wasapiOut.Init(_multiplexProvider);
                    //        _wasapiOut.Volume = _volume;
                    //        _wasapiOut.Play();
                    //    }

                    // we're working in bytes, so take the size of a 32 bit sample (float) into account
                    int sizeInBytes = (int)audioFrame.no_samples * (int)audioFrame.no_channels * sizeof(float);

                    // NAudio is expecting interleaved audio and NDI uses planar.
                    // create an interleaved frame and convert from the one we received
                    NDIlib.audio_frame_interleaved_32f_t interleavedFrame = new NDIlib.audio_frame_interleaved_32f_t()
                    {
                        sample_rate = audioFrame.sample_rate,
                        no_channels = audioFrame.no_channels,
                        no_samples  = audioFrame.no_samples,
                        timecode    = audioFrame.timecode
                    };

                    // we need a managed byte array to add to buffered provider
                    byte[] audBuffer = new byte[sizeInBytes];

                    // pin the byte[] and get a GC handle to it
                    // doing it this way saves an expensive Marshal.Alloc/Marshal.Copy/Marshal.Free later
                    // the data will only be moved once, during the fast interleave step that is required anyway
                    GCHandle handle = GCHandle.Alloc(audBuffer, GCHandleType.Pinned);

                    // access it by an IntPtr and use it for our interleaved audio buffer
                    interleavedFrame.p_data = handle.AddrOfPinnedObject();

                    // Convert from float planar to float interleaved audio
                    // There is a matching version of this that converts to interleaved 16 bit audio frames if you need 16 bit
                    NDIlib.util_audio_to_interleaved_32f_v2(ref audioFrame, ref interleavedFrame);

                    // release the pin on the byte[]
                    // never try to access p_data after the byte[] has been unpinned!
                    // that IntPtr will no longer be valid.
                    handle.Free();

                    //// push the byte[] buffer into the bufferedProvider for output
                    //_bufferedProvider.AddSamples(audBuffer, 0, sizeInBytes);

                    // free the frame that was received
                    NDIlib.recv_free_audio_v2(_recvInstancePtr, ref audioFrame);

                    break;

                // Metadata
                case NDIlib.frame_type_e.frame_type_metadata:

                    // UTF-8 strings must be converted for use - length includes the terminating zero
                    //String metadata = Utf8ToString(metadataFrame.p_data, metadataFrame.length-1);

                    //System.Diagnostics.Debug.Print(metadata);

                    // free frames that were received
                    NDIlib.recv_free_metadata(_recvInstancePtr, ref metadataFrame);
                    break;
                }
            }
        }
        protected override void CreateDeviceDependentResources()
        {
            RemoveAndDispose(ref vertexShader);
            RemoveAndDispose(ref lightBuffer);
            RemoveAndDispose(ref RTV);
            RemoveAndDispose(ref SRV);
            RemoveAndDispose(ref rsCullBack);
            RemoveAndDispose(ref rsCullFront);
            RemoveAndDispose(ref rsWireframe);
            RemoveAndDispose(ref blendStateAdd);
            RemoveAndDispose(ref depthLessThan);
            RemoveAndDispose(ref depthGreaterThan);
            RemoveAndDispose(ref depthDisabled);
            RemoveAndDispose(ref perLightBuffer);

            RemoveAndDispose(ref psAmbientLight);
            RemoveAndDispose(ref psDirectionalLight);
            RemoveAndDispose(ref psPointLight);
            RemoveAndDispose(ref psSpotLight);
            RemoveAndDispose(ref psDebugLight);
            RemoveAndDispose(ref perLightBuffer);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            int width, height;
            SampleDescription sampleDesc;

            // Retrieve DSV from GBuffer and extract width/height
            // then create a new read-only DSV
            using (var depthTexture = gbuffer.DSV.ResourceAs <Texture2D>())
            {
                width      = depthTexture.Description.Width;
                height     = depthTexture.Description.Height;
                sampleDesc = depthTexture.Description.SampleDescription;

                // Initialize read-only DSV
                var dsvDesc = gbuffer.DSV.Description;
                dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyDepth | DepthStencilViewFlags.ReadOnlyStencil;
                DSVReadonly   = ToDispose(new DepthStencilView(device, depthTexture, dsvDesc));
            }
            // Check if GBuffer is multi-sampled
            bool isMSAA = sampleDesc.Count > 1;

            // Initialize the light render target
            var texDesc = new Texture2DDescription();

            texDesc.BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget;
            texDesc.ArraySize         = 1;
            texDesc.CpuAccessFlags    = CpuAccessFlags.None;
            texDesc.Usage             = ResourceUsage.Default;
            texDesc.Width             = width;
            texDesc.Height            = height;
            texDesc.MipLevels         = 1; // No mip levels
            texDesc.SampleDescription = sampleDesc;
            texDesc.Format            = Format.R8G8B8A8_UNorm;

            lightBuffer = ToDispose(new Texture2D(device, texDesc));

            // Render Target View description
            var rtvDesc = new RenderTargetViewDescription();

            rtvDesc.Format             = Format.R8G8B8A8_UNorm;
            rtvDesc.Dimension          = isMSAA ? RenderTargetViewDimension.Texture2DMultisampled : RenderTargetViewDimension.Texture2D;
            rtvDesc.Texture2D.MipSlice = 0;
            RTV = ToDispose(new RenderTargetView(device, lightBuffer, rtvDesc));

            // SRV description for render targets
            var srvDesc = new ShaderResourceViewDescription();

            srvDesc.Format                    = Format.R8G8B8A8_UNorm;
            srvDesc.Dimension                 = isMSAA ? SharpDX.Direct3D.ShaderResourceViewDimension.Texture2DMultisampled : SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D;
            srvDesc.Texture2D.MipLevels       = -1;
            srvDesc.Texture2D.MostDetailedMip = 0;
            SRV = ToDispose(new ShaderResourceView(device, lightBuffer, srvDesc));

            // Initialize additive blend state (assuming single render target)
            BlendStateDescription bsDesc = new BlendStateDescription();

            bsDesc.RenderTarget[0].IsBlendEnabled        = true;
            bsDesc.RenderTarget[0].AlphaBlendOperation   = BlendOperation.Add;
            bsDesc.RenderTarget[0].SourceAlphaBlend      = BlendOption.One;
            bsDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.One;
            bsDesc.RenderTarget[0].BlendOperation        = BlendOperation.Add;
            bsDesc.RenderTarget[0].SourceBlend           = BlendOption.One;
            bsDesc.RenderTarget[0].DestinationBlend      = BlendOption.One;
            bsDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            blendStateAdd = ToDispose(new BlendState(device, bsDesc));

            // Initialize rasterizer states
            RasterizerStateDescription rsDesc = new RasterizerStateDescription();

            rsDesc.FillMode = FillMode.Solid;
            rsDesc.CullMode = CullMode.Back;
            rsCullBack      = ToDispose(new RasterizerState(device, rsDesc));
            rsDesc.CullMode = CullMode.Front;
            rsCullFront     = ToDispose(new RasterizerState(device, rsDesc));
            rsDesc.CullMode = CullMode.Front;
            rsDesc.FillMode = FillMode.Wireframe;
            rsWireframe     = ToDispose(new RasterizerState(device, rsDesc));

            // Initialize depth state
            var dsDesc = new DepthStencilStateDescription();

            dsDesc.IsStencilEnabled = false;
            dsDesc.IsDepthEnabled   = true;

            // Less-than depth comparison
            dsDesc.DepthComparison = Comparison.Less;
            depthLessThan          = ToDispose(new DepthStencilState(device, dsDesc));
            // Greater-than depth comparison
            dsDesc.DepthComparison = Comparison.Greater;
            depthGreaterThan       = ToDispose(new DepthStencilState(device, dsDesc));
            // Depth/stencil testing disabled
            dsDesc.IsDepthEnabled = false;
            depthDisabled         = ToDispose(new DepthStencilState(device, dsDesc));

            // Buffer to light parameters
            perLightBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <PerLight>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            if (isMSAA)
            {
                // Compile and create the vertex shader
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "VSLight", "vs_5_0"))
                    vertexShader = ToDispose(new VertexShader(device, bytecode));
                // Compile pixel shaders
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSAmbientLight", "ps_5_0"))
                    psAmbientLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSDirectionalLight", "ps_5_0"))
                    psDirectionalLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSPointLight", "ps_5_0"))
                    psPointLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSSpotLight", "ps_5_0"))
                    psSpotLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSDebugLight", "ps_5_0"))
                    psDebugLight = ToDispose(new PixelShader(device, bytecode));
            }
            else
            {
                // Compile and create the vertex shader
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "VSLight", "vs_5_0"))
                    vertexShader = ToDispose(new VertexShader(device, bytecode));
                // Compile pixel shaders
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSAmbientLight", "ps_5_0"))
                    psAmbientLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSDirectionalLight", "ps_5_0"))
                    psDirectionalLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSPointLight", "ps_5_0"))
                    psPointLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSSpotLight", "ps_5_0"))
                    psSpotLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSDebugLight", "ps_5_0"))
                    psDebugLight = ToDispose(new PixelShader(device, bytecode));
            }
        }
Example #57
0
        public int SetupVideo(AVCodec *codec)
        {
            hwAccelSuccess = false;

            if (decCtx.cfg.decoder.HWAcceleration)
            {
                if (VideoAcceleration.CheckCodecSupport(codec))
                {
                    if (demuxer.decCtx.va.hw_device_ctx == null)
                    {
                        demuxer.decCtx.va.Init(decCtx.renderer.device);
                    }

                    if (demuxer.decCtx.va.hw_device_ctx != null)
                    {
                        codecCtx->hw_device_ctx = av_buffer_ref(demuxer.decCtx.va.hw_device_ctx);
                        hwAccelSuccess          = true;
                        Log("HW Acceleration Success");
                    }
                }
                else
                {
                    Log("HW Acceleration Failed");
                }
            }
            else
            {
                Log("HW Acceleration Disabled");
            }

            codecCtx->thread_count = Math.Min(decCtx.cfg.decoder.VideoThreads, codecCtx->codec_id == AV_CODEC_ID_HEVC ? 32 : 16);
            codecCtx->thread_type  = 0;
            //vCodecCtx->active_thread_type = FF_THREAD_FRAME;
            //vCodecCtx->active_thread_type = FF_THREAD_SLICE;
            //codecCtx->thread_safe_callbacks = 1;

            int bits = info.PixelFormatDesc->comp.ToArray()[0].depth;

            textDesc = new Texture2DDescription()
            {
                Usage     = ResourceUsage.Default,
                BindFlags = BindFlags.ShaderResource,

                Format = bits > 8 ? Format.R16_UNorm : Format.R8_UNorm,              // FOR HW/SW will be set later
                Width  = codecCtx->width,
                Height = codecCtx->height,

                SampleDescription = new SampleDescription(1, 0),
                ArraySize         = 1,
                MipLevels         = 1
            };

            textDescUV = new Texture2DDescription()
            {
                Usage     = ResourceUsage.Default,
                BindFlags = BindFlags.ShaderResource,

                //Format              = bits > 8 ? Format.R16G16_UNorm : Format.R8G8_UNorm, // FOR HW/SW will be set later
                Format = bits > 8 ? Format.R16_UNorm : Format.R8_UNorm,              // FOR HW/SW will be set later
                Width  = codecCtx->width >> info.PixelFormatDesc->log2_chroma_w,
                Height = codecCtx->height >> info.PixelFormatDesc->log2_chroma_h,

                SampleDescription = new SampleDescription(1, 0),
                ArraySize         = 1,
                MipLevels         = 1
            };

            decCtx.renderer.FrameResized();

            return(0);
        }
Example #58
0
        private void InitDirectX()
        {
            try
            {
                ClearDirectXOutputs();

                using (var factory = new Factory1())
                {
                    foreach (var adapter in factory.Adapters1.Where(x => (x.Outputs?.Length ?? 0) > 0))
                    {
                        foreach (var output in adapter.Outputs)
                        {
                            try
                            {
                                var device  = new SharpDX.Direct3D11.Device(adapter);
                                var output1 = output.QueryInterface <Output1>();

                                var bounds = output1.Description.DesktopBounds;
                                var width  = bounds.Right - bounds.Left;
                                var height = bounds.Bottom - bounds.Top;

                                // Create Staging texture CPU-accessible
                                var textureDesc = new Texture2DDescription
                                {
                                    CpuAccessFlags    = CpuAccessFlags.Read,
                                    BindFlags         = BindFlags.None,
                                    Format            = Format.B8G8R8A8_UNorm,
                                    Width             = width,
                                    Height            = height,
                                    OptionFlags       = ResourceOptionFlags.None,
                                    MipLevels         = 1,
                                    ArraySize         = 1,
                                    SampleDescription = { Count = 1, Quality = 0 },
                                    Usage             = ResourceUsage.Staging
                                };

                                var texture2D = new Texture2D(device, textureDesc);

                                _directxScreens.Add(
                                    output1.Description.DeviceName,
                                    new DirectXOutput(adapter,
                                                      device,
                                                      output1.DuplicateOutput(device),
                                                      texture2D));
                            }
                            catch (Exception ex)
                            {
                                Logger.Write(ex);
                            }
                        }
                    }
                }


                NeedsInit = false;
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
            }
        }
Example #59
0
        public void Init(Game game, int Capacity, Vector2 leftBottom, Vector2 rightTop, int Width, int Height)
        {
            this.game     = game;
            this.Capacity = Capacity;
            this.Width    = Width;
            this.Height   = Height;

            var rs = game.GraphicsDevice;

            //////////////////////////// Init buffers ///////////////////////////////////////////
            var dataBufDesc = new BufferDescription {
                BindFlags           = BindFlags.ShaderResource,
                CpuAccessFlags      = CpuAccessFlags.None,
                OptionFlags         = ResourceOptionFlags.BufferStructured,
                Usage               = ResourceUsage.Default,
                SizeInBytes         = Capacity * Marshal.SizeOf(typeof(Element)),
                StructureByteStride = Marshal.SizeOf(typeof(Element))
            };

            dataBuffer = new Buffer(rs.Device, dataBufDesc);

            var stagingBufDesc = new BufferDescription {
                BindFlags           = BindFlags.None,
                CpuAccessFlags      = CpuAccessFlags.Write,
                OptionFlags         = ResourceOptionFlags.None,
                Usage               = ResourceUsage.Staging,
                SizeInBytes         = dataBufDesc.SizeInBytes,
                StructureByteStride = dataBufDesc.StructureByteStride
            };

            stagingBuffer = new Buffer(rs.Device, stagingBufDesc);

            stagingBufDesc.CpuAccessFlags = CpuAccessFlags.Read;
            readBuffer = new Buffer(rs.Device, stagingBufDesc);


            /////////////////////  ////////////////////////////////////
            var rwBufDesc = new BufferDescription {
                BindFlags           = BindFlags.ShaderResource | BindFlags.UnorderedAccess,
                CpuAccessFlags      = CpuAccessFlags.None,
                OptionFlags         = ResourceOptionFlags.BufferAllowRawViews,
                Usage               = ResourceUsage.Default,
                SizeInBytes         = Width * Height * Marshal.SizeOf(typeof(uint)),
                StructureByteStride = Marshal.SizeOf(typeof(uint))
            };

            rwBuffer = new Buffer(rs.Device, rwBufDesc);

            var textDesc = new Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.ShaderResource | BindFlags.UnorderedAccess,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.R32G32B32A32_Float,
                Width             = Width,
                Height            = Height,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                Usage             = ResourceUsage.Default,
                SampleDescription = new SampleDescription {
                    Count = 1
                }
            };


            finalTexture = new Texture2D(rs.Device, textDesc);
            tempTexture  = new Texture2D(rs.Device, textDesc);

            ///////////////////////////// Init UAV and SRV //////////////////////////////////////////
            ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription {
                Format    = Format.Unknown,
                Buffer    = { ElementCount = Capacity, FirstElement = 0 },
                Dimension = ShaderResourceViewDimension.Buffer
            };

            dataSRV = new ShaderResourceView(rs.Device, dataBuffer, srvDesc);


            var rwUAVDesc = new UnorderedAccessViewDescription {
                Format    = Format.R32_Typeless,
                Dimension = UnorderedAccessViewDimension.Buffer,
                Buffer    = new UnorderedAccessViewDescription.BufferResource {
                    ElementCount = Width * Height, FirstElement = 0, Flags = UnorderedAccessViewBufferFlags.Raw
                }
            };

            rwUAV = new UnorderedAccessView(rs.Device, rwBuffer, rwUAVDesc);


            var uavDesc = new UnorderedAccessViewDescription
            {
                Format    = Format.R32G32B32A32_Float,
                Dimension = UnorderedAccessViewDimension.Texture2D,
                Texture2D = new UnorderedAccessViewDescription.Texture2DResource {
                    MipSlice = 0
                }
            };

            finalTextureUAV = new UnorderedAccessView(rs.Device, finalTexture, uavDesc);
            tempUAV         = new UnorderedAccessView(rs.Device, tempTexture, uavDesc);


            var rwSRVDesc = new ShaderResourceViewDescription {
                Format    = Format.R32_UInt,
                Dimension = ShaderResourceViewDimension.Buffer,
                Buffer    = new ShaderResourceViewDescription.BufferResource {
                    ElementCount = Width * Height, FirstElement = 0
                }
            };

            rwSRV = new ShaderResourceView(rs.Device, rwBuffer, rwSRVDesc);


            var srvTexDesc = new ShaderResourceViewDescription
            {
                Format    = Format.R32G32B32A32_Float,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource {
                    MipLevels = 1, MostDetailedMip = 0
                }
            };

            FinalSRV = new ShaderResourceView(rs.Device, finalTexture, srvTexDesc);
            tempSRV  = new ShaderResourceView(rs.Device, tempTexture, srvTexDesc);

            computeShader = rs.CreateUberShader("effects/HeatMap.hlsl", typeof(HeatMapFlags));
            cBuffer       = rs.CreateConstBuffer <HeatMapCData>();


            rightTopMerc   = GeoHelper.WorldToTilePos(rightTop);
            leftBottomMerc = GeoHelper.WorldToTilePos(leftBottom);

            CellStep   = rightTopMerc - leftBottomMerc;
            CellStep.X = CellStep.X / Width;
            CellStep.Y = CellStep.X;                 //CellStep.Y / Height;

            pallete = game.Content.Load <Texture2D>("textures/pallete.tga");
        }
Example #60
0
        /// <summary>
        /// Updates resources associated with a holographic camera's swap chain.
        /// The app does not access the swap chain directly, but it does create
        /// resource views for the back buffer.
        /// </summary>
        public void CreateResourcesForBackBuffer(
            DeviceResources deviceResources,
            HolographicCameraRenderingParameters cameraParameters
            )
        {
            var device = deviceResources.D3DDevice;

            // Get the WinRT object representing the holographic camera's back buffer.
            IDirect3DSurface surface = cameraParameters.Direct3D11BackBuffer;

            // Get a DXGI interface for the holographic camera's back buffer.
            // Holographic cameras do not provide the DXGI swap chain, which is owned
            // by the system. The Direct3D back buffer resource is provided using WinRT
            // interop APIs.
            InteropStatics.IDirect3DDxgiInterfaceAccess surfaceDxgiInterfaceAccess = surface as InteropStatics.IDirect3DDxgiInterfaceAccess;
            IntPtr pResource = surfaceDxgiInterfaceAccess.GetInterface(InteropStatics.ID3D11Resource);

            SharpDX.Direct3D11.Resource resource = SharpDX.Direct3D11.Resource.FromPointer <SharpDX.Direct3D11.Resource>(pResource);
            Marshal.Release(pResource);

            // Get a Direct3D interface for the holographic camera's back buffer.
            Texture2D cameraBackBuffer = resource.QueryInterface <Texture2D>();

            // Determine if the back buffer has changed. If so, ensure that the render target view
            // is for the current back buffer.
            if ((null == d3dBackBuffer) || (d3dBackBuffer.NativePointer != cameraBackBuffer.NativePointer))
            {
                // This can change every frame as the system moves to the next buffer in the
                // swap chain. This mode of operation will occur when certain rendering modes
                // are activated.
                d3dBackBuffer = cameraBackBuffer;

                // Create a render target view of the back buffer.
                // Creating this resource is inexpensive, and is better than keeping track of
                // the back buffers in order to pre-allocate render target views for each one.
                d3dRenderTargetView = this.ToDispose(new RenderTargetView(device, BackBufferTexture2D));

                // Get the DXGI format for the back buffer.
                // This information can be accessed by the app using CameraResources::GetBackBufferDXGIFormat().
                Texture2DDescription backBufferDesc = BackBufferTexture2D.Description;
                dxgiFormat = backBufferDesc.Format;

                // Check for render target size changes.
                Size currentSize = holographicCamera.RenderTargetSize;
                if (d3dRenderTargetSize != currentSize)
                {
                    // Set render target size.
                    d3dRenderTargetSize = HolographicCamera.RenderTargetSize;

                    // A new depth stencil view is also needed.
                    this.RemoveAndDispose(ref d3dDepthStencilView);
                }
            }

            // Refresh depth stencil resources, if needed.
            if (null == DepthStencilView)
            {
                // Create a depth stencil view for use with 3D rendering if needed.
                var depthStencilDesc = new Texture2DDescription
                {
                    Format            = SharpDX.DXGI.Format.D16_UNorm,
                    Width             = (int)RenderTargetSize.Width,
                    Height            = (int)RenderTargetSize.Height,
                    ArraySize         = IsRenderingStereoscopic ? 2 : 1, // Create two textures when rendering in stereo.
                    MipLevels         = 1,                               // Use a single mipmap level.
                    BindFlags         = BindFlags.DepthStencil,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0)
                };

                using (var depthStencil = new Texture2D(device, depthStencilDesc))
                {
                    var depthStencilViewDesc = new DepthStencilViewDescription();
                    depthStencilViewDesc.Dimension = IsRenderingStereoscopic ? DepthStencilViewDimension.Texture2DArray : DepthStencilViewDimension.Texture2D;
                    depthStencilViewDesc.Texture2DArray.ArraySize = IsRenderingStereoscopic ? 2 : 0;
                    d3dDepthStencilView = this.ToDispose(new DepthStencilView(device, depthStencil, depthStencilViewDesc));
                }
            }

            // Create the constant buffer, if needed.
            if (null == viewProjectionConstantBuffer)
            {
                // Create a constant buffer to store view and projection matrices for the camera.
                ViewProjectionConstantBuffer viewProjectionConstantBufferData = new ViewProjectionConstantBuffer();
                viewProjectionConstantBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create(
                                                                  device,
                                                                  BindFlags.ConstantBuffer,
                                                                  ref viewProjectionConstantBufferData));
            }
        }