Exemplo n.º 1
2
 public Terrain(Device device, String texture, int pitch, Renderer renderer)
 {
     HeightMap = new System.Drawing.Bitmap(@"Data/Textures/"+texture);
     WaterShader = new WaterShader(device);
     TerrainShader = new TerrainShader(device);
     _width = HeightMap.Width-1;
     _height = HeightMap.Height-1;
     _pitch = pitch;
     _terrainTextures = new ShaderResourceView[4];
     _terrainTextures[0] = new Texture(device, "Sand.png").TextureResource;
     _terrainTextures[1] = new Texture(device, "Grass.png").TextureResource;
     _terrainTextures[2] = new Texture(device, "Ground.png").TextureResource;
     _terrainTextures[3] = new Texture(device, "Rock.png").TextureResource;
     _reflectionClippingPlane = new Vector4(0.0f, 1.0f, 0.0f, 0.0f);
     _refractionClippingPlane = new Vector4(0.0f, -1.0f, 0.0f, 0.0f);
     _noClippingPlane = new Vector4(0.0f, 1.0f, 0.0f, 10000);
     _reflectionTexture = new RenderTexture(device, renderer.ScreenSize);
     _refractionTexture = new RenderTexture(device, renderer.ScreenSize);
     _renderer = renderer;
     _bitmap = new Bitmap(device,_refractionTexture.ShaderResourceView,renderer.ScreenSize, new Vector2I(100, 100), 0);
     _bitmap.Position = new Vector2I(renderer.ScreenSize.X - 100, 0);
     _bitmap2 = new Bitmap(device, _reflectionTexture.ShaderResourceView, renderer.ScreenSize, new Vector2I(100, 100), 0);
     _bitmap2.Position = new Vector2I(renderer.ScreenSize.X - 100, 120);
     _bumpMap = _renderer.TextureManager.Create("OceanWater.png");
     _skydome = new ObjModel(device, "skydome.obj", renderer.TextureManager.Create("Sky.png"));
     BuildBuffers(device);
     WaveTranslation = new Vector2(0,0);
 }
        public PhysicsDebugDraw(DeviceManager manager)
        {
            device = manager.Direct3DDevice;
            inputAssembler = device.ImmediateContext.InputAssembler;
            lineArray = new PositionColored[0];

            using (var bc = HLSLCompiler.CompileFromFile(@"Shaders\PhysicsDebug.hlsl", "VSMain", "vs_5_0"))
            {
                vertexShader = new VertexShader(device, bc);

                InputElement[] elements = new InputElement[]
                {
                    new InputElement("SV_POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                    new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 12, 0, InputClassification.PerVertexData, 0)
                };
                inputLayout = new InputLayout(device, bc, elements);
            }

            vertexBufferDesc = new BufferDescription()
            {
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.Write
            };

            vertexBufferBinding = new VertexBufferBinding(null, PositionColored.Stride, 0);

            using (var bc = HLSLCompiler.CompileFromFile(@"Shaders\PhysicsDebug.hlsl", "PSMain", "ps_5_0"))
                pixelShader = new PixelShader(device, bc);
        }
Exemplo n.º 3
0
        public DrawingSurface(DrawingBackend backend, int width, int height)
        {
            if (width < 0 || height < 0)
                throw new Exception("Area of DrawingSurface's is neagative");

            _factory = backend.Factory;
            _device = backend.Device;

            _backend = backend;
            _width = width;
            _height = height;

            var textureDesc = new Texture2DDescription
            {
                MipLevels = 1,
                ArraySize = 1,
                BindFlags = BindFlags.RenderTarget,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.B8G8R8A8_UNorm,
                OptionFlags = ResourceOptionFlags.None,
                Width = _width,
                Height = _height,
                Usage = ResourceUsage.Default,
                SampleDescription = new SampleDescription(1, 0)
            };

            _texture = new Texture2D(_device, textureDesc);
        }
Exemplo n.º 4
0
        public bool Initialize(Device device, DeviceContext deviceContext, IntPtr windowHandle, int screanWidth, int screenHeight, Matrix baseViewMatrix)
        {
            // Store the screen width and height.
            ScreenWidth = screanWidth;
            ScreenHeight = screenHeight;

            // Store the base view matrix.
            BaseViewMatrix = baseViewMatrix;

            // Create the font object.
            Font = new Font();

            // Initialize the font object.
            if (!Font.Initialize(device, "fontdata.txt", "font.dds"))
                return false;

            // Create the font shader object.
            FontShader = new FontShader();

            // Initialize the font shader object.
            if (!FontShader.Initialize(device, windowHandle))
                return false;

            // Initialize the first sentence.
            if (!InitializeSentence(out sentences[0], 32, device))
                return false;

            // Now update the sentence vertex buffer with the new string information.
            if (!UpdateSentece(ref sentences[0], "Render Count:", 20, 20, 1, 1, 1, deviceContext))
                return false;

            return true;
        }
Exemplo n.º 5
0
        /// <summary>
        /// Create a buffer containing all GameColors
        /// </summary>
        public static SharpDX.Direct3D11.Buffer CreateGameColorBuffer(Device device)
        {
            int numcolors = GameColorRGB.NUMCOLORS;

            var arr = new int[numcolors];
            for (int i = 0; i < numcolors; ++i)
            {
                var gc = (GameColor)i;
                arr[i] = GameColorRGB.FromGameColor(gc).ToInt32();
            }

            SharpDX.Direct3D11.Buffer colorBuffer;

            using (var stream = DataStream.Create(arr, true, false))
            {
                colorBuffer = new SharpDX.Direct3D11.Buffer(device, stream, new BufferDescription()
                {
                    BindFlags = BindFlags.ShaderResource,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None,
                    SizeInBytes = sizeof(int) * arr.Length,
                    Usage = ResourceUsage.Immutable,
                });
            }

            return colorBuffer;
        }
        // Used with soft bodies
        public void SetDynamicVertexBuffer(Device device, Vector3[] vectors)
        {
            if (VertexBuffer != null && VertexCount * 2 == vectors.Length)
            {
                DataBox db = device.ImmediateContext.MapSubresource(VertexBuffer, 0, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None);
                SharpDX.Utilities.Write(db.DataPointer, vectors, 0, vectors.Length);
                device.ImmediateContext.UnmapSubresource(VertexBuffer, 0);
            }
            else
            {
                // Create new buffer
                if (VertexBuffer != null)
                    VertexBuffer.Dispose();

                BufferDescription vertexBufferDesc = new BufferDescription()
                {
                    SizeInBytes = Vector3.SizeInBytes * vectors.Length,
                    Usage = ResourceUsage.Dynamic,
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.Write
                };

                using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true))
                {
                    data.WriteRange(vectors);
                    data.Position = 0;
                    VertexBuffer = new Buffer(device, data, vertexBufferDesc);
                }

                VertexCount = vectors.Length / 2;
                BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0);
            }
        }
Exemplo n.º 7
0
        public bool Initialize(Device device, string heightMapFileName)
        {
            // Load the height map for the terrain
            if (!LoadHeightMapFilename(heightMapFileName))
                return false;

            // Normalize the height of the height map
            NormalizeHeightMap();

            // Calculate the normals for the terrain data.
            if (!CalculateNormals())
                return false;

            // Set the number of vertices per quad (2 triangles)
            NumberOfVerticesPerQuad = 6;

            // Set the value of the topology
            CurrentTopology = PrimitiveTopology.TriangleList;

            // Initialize the vertex and index buffer.
            if (!InitializeBuffers(device))
                return false;

            return true;
        }
Exemplo n.º 8
0
        public DepthBuffer(Device device, int width, int height)
        {
            try
            {
                _device = device;
                _depthBuffer = new Texture2D(_device, new Texture2DDescription
                {
                    Format = Format.D32_Float_S8X24_UInt,
                    ArraySize = 1,
                    MipLevels = 1,
                    Width = width,
                    Height = height,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage = ResourceUsage.Default,
                    BindFlags = BindFlags.DepthStencil,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None
                });

                _depthView = new DepthStencilView(device, _depthBuffer);
            }
            catch
            {
                Dispose();
                throw;
            }
        }
// ReSharper restore InconsistentNaming

        static CompositionEngine()
        {
            _wicFactory = new SharpDX.WIC.ImagingFactory();
            _dWriteFactory = new SharpDX.DirectWrite.Factory();

            var d3DDevice = new SharpDX.Direct3D11.Device(
                DriverType.Hardware,
                DeviceCreationFlags.BgraSupport
#if DEBUG
                | DeviceCreationFlags.Debug
#endif
,
                FeatureLevel.Level_11_1,
                FeatureLevel.Level_11_0,
                FeatureLevel.Level_10_1,
                FeatureLevel.Level_10_0,
                FeatureLevel.Level_9_3,
                FeatureLevel.Level_9_2,
                FeatureLevel.Level_9_1
                );

            var dxgiDevice = ComObject.As<SharpDX.DXGI.Device>(d3DDevice.NativePointer);
                //new SharpDX.DXGI.Device2(d3DDevice.NativePointer);
            var d2DDevice = new SharpDX.Direct2D1.Device(dxgiDevice);
            _d2DFactory = d2DDevice.Factory;
            _d2DDeviceContext = new SharpDX.Direct2D1.DeviceContext(d2DDevice, D2D.DeviceContextOptions.None);
            _d2DDeviceContext.DotsPerInch = new Size2F(LogicalDpi, LogicalDpi);
        }
Exemplo n.º 10
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 },
                });
        }
Exemplo n.º 11
0
        public Bitmap(Device device, ShaderResourceView texture, Vector2I screenSize, Vector2I size, float depth = 0.0f)
        {
            Texture = texture;
            ScreenSize = screenSize;
            Size = size;
            _changed = true;
            Depth = depth;

            VertexCount = 4;
            IndexCount = 6;

            _vertices = new TranslateShader.Vertex[VertexCount];
            UInt32[] indices =  {0, 1, 2, 0, 3, 1};

            VertexBuffer = Buffer.Create(device, _vertices,
                new BufferDescription
                {
                    Usage = ResourceUsage.Dynamic,
                    SizeInBytes = Utilities.SizeOf<TranslateShader.Vertex>() * VertexCount,
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.Write,
                    OptionFlags = ResourceOptionFlags.None,
                    StructureByteStride = 0
                });

            IndexBuffer = Buffer.Create(device, BindFlags.IndexBuffer, indices);
        }
Exemplo n.º 12
0
        public ProjectorFormLoader(String path)
        {
            Forms = new List<ProjectorForm>();

            // load ensemble.xml
            string directory = Path.GetDirectoryName(path);
            var ensemble = ProjectorCameraEnsemble.FromFile(path);

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

            // When using DeviceCreationFlags.Debug on Windows 10, ensure that "Graphics Tools" are installed via Settings/System/Apps & features/Manage optional features.
            // Also, when debugging in VS, "Enable native code debugging" must be selected on the project.
            var device = new SharpDX.Direct3D11.Device(adapter, DeviceCreationFlags.None);

            Object renderLock = new Object();

            // create a form for each projector
            foreach (var projector in ensemble.projectors) {
                var form = new ProjectorForm(factory, device, renderLock, projector);
                form.FullScreen = FULLSCREEN_ENABLED; // TODO: fix this so can be called after Show
                form.Show();
                Forms.Add(form);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Copies the content of the specified texture.
        /// </summary>
        /// <param name="device">The Direct3D 11 device.</param>
        /// <param name="source">The source texture.</param>
        /// <param name="target">The target texture.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="device"/>, <paramref name="source"/> or <paramref name="target"/> is
        /// <see langword="null"/>.
        /// </exception>
        public static void Copy(Device device, Texture2D source, Texture2D target)
        {
            if (device == null)
            throw new ArgumentNullException("device");
              if (source == null)
            throw new ArgumentNullException("source");
              if (target == null)
            throw new ArgumentNullException("target");

              int sourceWidth = source.Description.Width;
              int sourceHeight = source.Description.Height;
              int targetWidth = target.Description.Width;
              int targetHeight = target.Description.Height;

              if (sourceWidth == targetWidth && sourceHeight == targetHeight)
              {
            device.ImmediateContext.CopyResource(source, target);
              }
              else
              {
            int width = Math.Min(sourceWidth, targetWidth);
            int height = Math.Min(sourceHeight, targetHeight);
            var region = new ResourceRegion(0, 0, 0, width, height, 1);
            device.ImmediateContext.CopySubresourceRegion(source, 0, region, target, 0);
              }
        }
Exemplo n.º 14
0
        public TextureShader(Device device)
        {
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "TextureVertexShader", "vs_4_0", ShaderFlags);
            var pixelShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "TexturePixelShader", "ps_4_0", ShaderFlags);

            VertexShader = new VertexShader(device, vertexShaderByteCode);
            PixelShader = new PixelShader(device, pixelShaderByteCode);

            Layout = VertexDefinition.PositionTexture.GetInputLayout(device, vertexShaderByteCode);

            vertexShaderByteCode.Dispose();
            pixelShaderByteCode.Dispose();

            ConstantMatrixBuffer = new Buffer(device, MatrixBufferDesription);

            // Create a texture sampler state description.
            var samplerDesc = new SamplerStateDescription
            {
                Filter = Filter.Anisotropic,
                AddressU = TextureAddressMode.Mirror,
                AddressV = TextureAddressMode.Mirror,
                AddressW = TextureAddressMode.Mirror,
                MipLodBias = 0,
                MaximumAnisotropy = 16,
                ComparisonFunction = Comparison.Always,
                BorderColor = new Color4(1, 1, 1, 1),
                MinimumLod = 0,
                MaximumLod = 0
            };

            // Create the texture sampler state.
            SamplerState = new SamplerState(device, samplerDesc);
        }
Exemplo n.º 15
0
        public DX11Renderer(IntPtr windowHandle, Size2 size, Device dev = null)
        {
            RenderSize = size;
            _windowHandle = windowHandle;
            if(dev != null)
            {
                _dxDevice = dev;
            }
            else
            {
                var swapchainDesc = new SwapChainDescription()
                {
                    BufferCount = 2,
                    ModeDescription =
                        new ModeDescription(size.Width, size.Height,
                                            new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    IsWindowed = true,
                    OutputHandle = windowHandle,
                    SampleDescription = new SampleDescription(1, 0),
                    SwapEffect = SwapEffect.Discard,
                    Usage = Usage.RenderTargetOutput
                };

                // Create Device and SwapChain
                Device.CreateWithSwapChain(DriverType.Hardware,
                   DeviceCreationFlags.None, swapchainDesc, out _dxDevice, out _swapChain);

                // Ignore all windows events
                //    var factory = _swapChain.GetParent<Factory>();
                //    factory.MakeWindowAssociation(windowHandle, WindowAssociationFlags.None);

                Reset(size.Width, size.Height);
            }
        }
Exemplo n.º 16
0
 public Form1(Factory factory, SharpDX.Direct3D11.Device device, Object renderLock)
 {
     InitializeComponent();
     this.factory = factory;
     this.device = device;
     this.renderLock = renderLock;
 }
Exemplo n.º 17
0
 public UISurface(Device device)
 {
     this.mDevice = device;
     mBatchPool = new UISurfaceBatchPool(device);
     mFontMaterialMgr = new UISurfaceFontMaterialManager(device);
     SetDesignHeight(Game.Instance.RenderViewSize.Height);
 }
Exemplo n.º 18
0
        /// <summary>
        /// Creates a new graphics resource.
        /// </summary>
        /// <param name="device">The graphics device to use.</param>
        /// <param name="dimensions">The resource dimensions.</param>
        /// <param name="format">The resource's DXGI format.</param>
        /// <param name="renderTargetView">Whether to bind as RTV.</param>
        /// <param name="shaderResourceView">Whether to bind as SRV.</param>
        /// <param name="hasMipMaps">Whether to enable mip-maps for this texture.</param>
        public GraphicsResource(Device device, Size dimensions, Format format, Boolean renderTargetView = true, Boolean shaderResourceView = true, Boolean hasMipMaps = false)
        {
            if ((!renderTargetView) && (!shaderResourceView))
                throw new ArgumentException("The requested resource cannot be bound at all to the pipeline.");

            if ((hasMipMaps) && ((!renderTargetView) || (!shaderResourceView)))
                throw new ArgumentException("A resource with mipmaps must be bound as both input and output.");

            BindFlags bindFlags = (renderTargetView ? BindFlags.RenderTarget : 0) | (shaderResourceView ? BindFlags.ShaderResource : 0);
            ResourceOptionFlags optionFlags = (hasMipMaps ? ResourceOptionFlags.GenerateMipMaps : 0);
            int mipLevels = (hasMipMaps ? MipLevels(dimensions) : 1);

            Resource = new Texture2D(device, new Texture2DDescription()
            {
                Format = format,
                BindFlags = bindFlags,
                Width = dimensions.Width,
                Height = dimensions.Height,

                ArraySize = 1,
                MipLevels = mipLevels,
                OptionFlags = optionFlags,
                Usage = ResourceUsage.Default,
                CpuAccessFlags = CpuAccessFlags.None,
                SampleDescription = new SampleDescription(1, 0),
            });

            RTV = (  renderTargetView ?   new RenderTargetView(device, Resource) : null);
            SRV = (shaderResourceView ? new ShaderResourceView(device, Resource) : null);
        }
 public RenderTarget(Device device, int width, int height, int sampleCount, int sampleQuality, Format format)
     : this()
 {
     Texture = _disposer.Add(new Texture2D(device, new Texture2DDescription
     {
         Format              = format,
         Width               = width,
         Height              = height,
         ArraySize           = 1,
         MipLevels           = 1,
         BindFlags           = BindFlags.RenderTarget | BindFlags.ShaderResource,
         CpuAccessFlags      = CpuAccessFlags.None,
         OptionFlags         = ResourceOptionFlags.None,
         Usage               = ResourceUsage.Default,
         SampleDescription   = new SampleDescription(sampleCount, sampleQuality),
     }));
     RenderTargetView = _disposer.Add(new RenderTargetView(device, Texture, new RenderTargetViewDescription
     {
         Format = format,
         Dimension = RenderTargetViewDimension.Texture2DMultisampled,
         //MipSlice = 0,
     }));
     
     ShaderResourceView = _disposer.Add(new ShaderResourceView(device, Texture));
     Viewport = new Viewport(0, 0, width, height, 0.0f, 1.0f);
 }
Exemplo n.º 20
0
        public void Initialize()
        {
            DestroyResources();

            var flags = DeviceCreationFlags.BgraSupport;
            #if DEBUG
            flags |= DeviceCreationFlags.Debug;
            #endif

            var featureLevels = new[]
            {
                FeatureLevel.Level_11_1,
                FeatureLevel.Level_11_0
            };

            using(var device = new Device(DriverType.Hardware, flags, featureLevels))
            {
                Device = device.QueryInterface<Device1>();
                Context = device.ImmediateContext.QueryInterface<DeviceContext1>();
            }

            IsInitialized = true;

            // todo: Reinitialize all dependent resources by having them hook this event
            var handler = Initialized;
            if(handler != null)
                handler();
        }
Exemplo n.º 21
0
        public static bool IsDx11Supported()
        {
            var factory = GetFactory();
            FeatureLevel[] featureLevels = {FeatureLevel.Level_11_0};

            for (int i = 0; i < factory.Adapters.Length; i++)
            {
                var adapter = factory.Adapters[i];
                Device adapterTestDevice = null;
                try
                {
                    adapterTestDevice = new Device(adapter, DeviceCreationFlags.None, featureLevels);
                }
                catch (Exception)
                {
                    continue;
                }

                UInt64 vram;
                UInt64 svram;
                GetRamSizes(out vram, adapter, out svram);

                // microsoft software renderer allocates 256MB shared memory, cpu integrated graphic on notebooks has 0 preallocated, all shared
                return (vram > 500000000 || svram > 500000000);
            }
            return false;
        }
Exemplo n.º 22
0
 public static InputLayout GetInputLayout(Device device, CompilationResult vertexShaderByteCode)
 {
     var inputElements = new InputElement[]
     {
         new InputElement
         {
             SemanticName = "POSITION",
             SemanticIndex = 0,
             Format = Format.R32G32B32_Float,
             Slot = 0,
             AlignedByteOffset = 0,
             Classification = InputClassification.PerVertexData,
             InstanceDataStepRate = 0
         },
         new InputElement
         {
             SemanticName = "COLOR",
             SemanticIndex = 0,
             Format = Format.R32G32B32A32_Float,
             Slot = 0,
             AlignedByteOffset = LightShader.Vertex.AppendAlignedElement1,
             Classification = InputClassification.PerVertexData,
             InstanceDataStepRate = 0
         }
     };
     return new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);
 }
Exemplo n.º 23
0
 public FbxMesh(AssimpSharp.Mesh mesh, AssimpSharp.Material mat, Device device, string path)
 {
     this.device = device;
     this.path = path;
     LoadMesh(mesh);
     LoadMaterial(mat);
 }
Exemplo n.º 24
0
        public MeshFactory(SharpDX11Graphics graphics)
        {
            this.device = graphics.Device;
            this.inputAssembler = device.ImmediateContext.InputAssembler;
            this.demo = graphics.Demo;

            instanceDataDesc = new BufferDescription()
            {
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None,
            };

            InputElement[] elements = new InputElement[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0, InputClassification.PerVertexData, 0),
                new InputElement("WORLD", 0, Format.R32G32B32A32_Float, 0, 1, InputClassification.PerInstanceData, 1),
                new InputElement("WORLD", 1, Format.R32G32B32A32_Float, 16, 1, InputClassification.PerInstanceData, 1),
                new InputElement("WORLD", 2, Format.R32G32B32A32_Float, 32, 1, InputClassification.PerInstanceData, 1),
                new InputElement("WORLD", 3, Format.R32G32B32A32_Float, 48, 1, InputClassification.PerInstanceData, 1),
                new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 64, 1, InputClassification.PerInstanceData, 1)
            };
            inputLayout = new InputLayout(device, graphics.GetEffectPass().Description.Signature, elements);

            groundColor = ColorToUint(Color.Green);
            activeColor = ColorToUint(Color.Orange);
            passiveColor = ColorToUint(Color.OrangeRed);
            softBodyColor = ColorToUint(Color.LightBlue);
        }
        private void CreateDeviceResources()
        {
            // This flag adds support for surfaces with a different color channel ordering
            // than the API default. It is required for compatibility with Direct2D.
            DeviceCreationFlags creationFlags = DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug;

            // This array defines the set of DirectX hardware feature levels this app will support.
            // Note the ordering should be preserved.
            // Don't forget to declare your application's minimum required feature level in its
            // description.  All applications are assumed to support 9.1 unless otherwise stated.

            SharpDX.Direct3D.FeatureLevel[] featureLevels = 
	        {
                SharpDX.Direct3D.FeatureLevel.Level_11_1,
		        SharpDX.Direct3D.FeatureLevel.Level_11_0,
		        SharpDX.Direct3D.FeatureLevel.Level_10_1,
		        SharpDX.Direct3D.FeatureLevel.Level_10_0,
		        SharpDX.Direct3D.FeatureLevel.Level_9_3
	        };

            // Create the Direct3D 11 API device object and a corresponding context.
            using (var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, creationFlags, featureLevels))
                _device = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();

            // Get Direct3D 11.1 context
            _deviceContext = ToDispose(_device.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>());
        }
Exemplo n.º 26
0
        public bool Initialize(Device device, HeightMapTerrain terrain)
        {
            // Get the number of the vertices on the terrain vertex array.
            var vertexCount = terrain.VertexCount;

            // Store the total triangle count for the vertex list.
            TriangleCount = vertexCount / 3;

            VertexList = new List<HeightMapTerrainShader.Vertex>(vertexCount);

            // Copy the terrain vertices into vertex list.
            terrain.CopyVertexArray(VertexList);

            // Calculate the center x,z and the width of the mesh.
            float centerX, centerZ, width;
            CalculateMeshDimensions(vertexCount, out centerX, out centerZ, out width);

            // Create the parent node for the quad tree
            // Recursively build the quad tree based on the vertex list data and mesh dimensions.
            ParentNode = CreateTreeNode(device, centerX, centerZ, width);

            // Release the vertex list since the quad tree now has the vertices in each node.
            VertexList.Clear();

            return true;
        }
Exemplo n.º 27
0
        public bool Initialize(Device device, string heightMapFileName, string textureFileName)
        {
            // Set the number of vertices per quad (2 triangles)
            NumberOfVerticesPerQuad = 6;

            // Set the value of the topology
            CurrentTopology = PrimitiveTopology.TriangleList;

            // How many times the terrain texture will be repeated both over the width and length of the terrain.
            TextureRepeat = 8;

            // Load the height map for the terrain
            if (!LoadHeightMapFilename(heightMapFileName))
                return false;

            // Normalize the height of the height map
            NormalizeHeightMap();

            // Calculate the normals for the terrain data.
            if (!CalculateNormals())
                return false;

            // Calculate the texture coordinates.
            CalculateTextureCoordinates();

            // Load the texture for this model.
            if (!LoadTexture(device, textureFileName))
                return false;

            // Initialize the vertex and index buffer.
            if (!InitializeBuffers(device))
                return false;

            return true;
        }
Exemplo n.º 28
0
 public void SetInputLayout(Device device, ShaderSignature inputSignature)
 {
     foreach (ModelMesh mesh in m_meshes)
     {
         mesh.SetInputLayout(device, inputSignature);
     }
     m_inputLayoutSet = true;
 }
 public RenderTarget(Device device, SwapChain swapChain)
     : this()
 {
     Texture = _disposer.Add(Texture2D.FromSwapChain<Texture2D>(swapChain, 0));
     RenderTargetView = _disposer.Add(new RenderTargetView(device, Texture));
     ShaderResourceView = null;
     Viewport = new Viewport(0, 0, Width, Height, 0.0f, 1.0f);
 }
Exemplo n.º 30
0
		public D3D11_2D1(Device11 drawdevice, Device10 textdevice)
			: base(false) // nothing!
		{
			if (drawdevice == null || textdevice == null)
			{
				using (var dg = new DisposeGroup())
				{
					if (drawdevice == null && textdevice == null)
					{
						Adapter a = null;
						foreach (var item in DeviceUtil.GetAdapters(dg))
						{
							if (!item.IsInterfaceSupported<Device10>())
								continue;
							if (Device11.GetSupportedFeatureLevel(item) < Direct3D.FeatureLevel.Level_10_1)
								continue;
							a = item;
							break;
						}
						device = new Device11(a, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.SingleThreaded | DeviceCreationFlags.Debug);
						device10 = new Device10(a, Direct3D10.DeviceCreationFlags.BgraSupport | Direct3D10.DeviceCreationFlags.Singlethreaded | Direct3D10.DeviceCreationFlags.Debug);
					}
					else
					{
						if (drawdevice == null)
						{
							using (var xgidtext = textdevice.QueryInterface<DeviceXGI>())
								device = new Device11(xgidtext.Adapter, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.SingleThreaded | DeviceCreationFlags.Debug);
							textdevice.AddReference();
							device10 = textdevice;
						}
						else
						{
							using (var xgiddraw = drawdevice.QueryInterface<DeviceXGI>())
								device10 = new Device10(xgiddraw.Adapter, Direct3D10.DeviceCreationFlags.BgraSupport | Direct3D10.DeviceCreationFlags.Singlethreaded | Direct3D10.DeviceCreationFlags.Debug);
							drawdevice.AddReference();
							device = drawdevice;
						}
					}
				}
			}
			else
			{
				using (var xgidev10 = device10.QueryInterface<DeviceXGI>())
				using (var xgidev11 = device.QueryInterface<DeviceXGI>())
				{
					if (xgidev10.Adapter.NativePointer != xgidev11.Adapter.NativePointer)
						throw new ArgumentException("drawdevice.Adapter.NativePointer != textdevice.Adapter.NativePointer");
				}
				textdevice.AddReference();
				drawdevice.AddReference();
				device = drawdevice;
				device10 = textdevice;
			}

			factory2D = new SharpDX.Direct2D1.Factory();
			factoryDW = new FactoryDW();
		}
Exemplo n.º 31
0
        private static void Main()
        {
            var form = new RenderForm("SharpDX - MiniTri Direct3D 11 Sample");

            // 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.None, desc, out device, out swapChain);
            var context = device.ImmediateContext;

            // Ignore all windows events
            var factory = swapChain.GetParent <Factory>();

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

            // New RenderTargetView from the backbuffer
            var backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            var renderView = new RenderTargetView(device, backBuffer);

            // Compile Vertex and Pixel shaders
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "VS", "vs_4_0", ShaderFlags.None, EffectFlags.None);
            var vertexShader         = new VertexShader(device, vertexShaderByteCode);

            var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None);
            var pixelShader         = new PixelShader(device, pixelShaderByteCode);

            // Layout from VertexShader input signature
            var layout = new InputLayout(
                device,
                ShaderSignature.GetInputSignature(vertexShaderByteCode),
                new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
            });

            // Instantiate Vertex buiffer from vertex data
            var vertices = Buffer.Create(device, BindFlags.VertexBuffer, 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)
            });

            // Prepare All the stages
            context.InputAssembler.InputLayout       = layout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0));
            context.VertexShader.Set(vertexShader);
            context.Rasterizer.SetViewport(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
            context.PixelShader.Set(pixelShader);
            context.OutputMerger.SetTargets(renderView);

            // Main loop
            RenderLoop.Run(form, () =>
            {
                context.ClearRenderTargetView(renderView, Color.Black);
                context.Draw(3, 0);
                swapChain.Present(0, PresentFlags.None);
            });

            // Release all resources
            vertexShaderByteCode.Dispose();
            vertexShader.Dispose();
            pixelShaderByteCode.Dispose();
            pixelShader.Dispose();
            vertices.Dispose();
            layout.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            context.ClearState();
            context.Flush();
            device.Dispose();
            context.Dispose();
            swapChain.Dispose();
            factory.Dispose();
        }
Exemplo n.º 32
0
        public ShadowShader(Device device)
        {
            byte[] vsbytes = File.ReadAllBytes("Shaders\\ShadowVS.cso");
            byte[] psbytes = File.ReadAllBytes("Shaders\\ShadowPS.cso");

            shadowvs = new VertexShader(device, vsbytes);
            shadowps = new PixelShader(device, psbytes);


            VSSceneVars  = new GpuVarsBuffer <ShadowShaderVSSceneVars>(device);
            VSEntityVars = new GpuVarsBuffer <ShadowShaderVSEntityVars>(device);
            VSModelVars  = new GpuVarsBuffer <ShadowShaderVSModelVars>(device);
            GeomVars     = new GpuVarsBuffer <ShadowShaderGeomVars>(device);


            //supported layouts - requires Position, Normal, Colour, Texcoord
            layouts.Add(VertexType.Default, new InputLayout(device, vsbytes, VertexTypeDefault.GetLayout()));
            layouts.Add(VertexType.DefaultEx, new InputLayout(device, vsbytes, VertexTypeDefaultEx.GetLayout()));
            layouts.Add(VertexType.PNCCT, new InputLayout(device, vsbytes, VertexTypePNCCT.GetLayout()));
            layouts.Add(VertexType.PNCCTTTT, new InputLayout(device, vsbytes, VertexTypePNCCTTTT.GetLayout()));
            layouts.Add(VertexType.PBBNCCTTX, new InputLayout(device, vsbytes, VertexTypePBBNCCTTX.GetLayout()));
            layouts.Add(VertexType.PBBNCCT, new InputLayout(device, vsbytes, VertexTypePBBNCCT.GetLayout()));
            layouts.Add(VertexType.PNCTTTX, new InputLayout(device, vsbytes, VertexTypePNCTTTX.GetLayout()));
            layouts.Add(VertexType.PNCTTTX_2, new InputLayout(device, vsbytes, VertexTypePNCTTTX_2.GetLayout()));
            layouts.Add(VertexType.PNCTTTX_3, new InputLayout(device, vsbytes, VertexTypePNCTTTX_3.GetLayout()));
            layouts.Add(VertexType.PNCTTTTX, new InputLayout(device, vsbytes, VertexTypePNCTTTTX.GetLayout()));
            layouts.Add(VertexType.PNCTTX, new InputLayout(device, vsbytes, VertexTypePNCTTX.GetLayout()));
            layouts.Add(VertexType.PNCCTTX, new InputLayout(device, vsbytes, VertexTypePNCCTTX.GetLayout()));
            layouts.Add(VertexType.PNCCTTX_2, new InputLayout(device, vsbytes, VertexTypePNCCTTX_2.GetLayout()));
            layouts.Add(VertexType.PNCCTTTX, new InputLayout(device, vsbytes, VertexTypePNCCTTTX.GetLayout()));
            layouts.Add(VertexType.PBBNCCTX, new InputLayout(device, vsbytes, VertexTypePBBNCCTX.GetLayout()));
            layouts.Add(VertexType.PBBNCTX, new InputLayout(device, vsbytes, VertexTypePBBNCTX.GetLayout()));
            layouts.Add(VertexType.PBBNCT, new InputLayout(device, vsbytes, VertexTypePBBNCT.GetLayout()));
            layouts.Add(VertexType.PNCCTT, new InputLayout(device, vsbytes, VertexTypePNCCTT.GetLayout()));
            layouts.Add(VertexType.PNCCTX, new InputLayout(device, vsbytes, VertexTypePNCCTX.GetLayout()));
            layouts.Add(VertexType.PNCH2, new InputLayout(device, vsbytes, VertexTypePNCH2.GetLayout()));
            layouts.Add(VertexType.PCCH2H4, new InputLayout(device, vsbytes, VertexTypePCCH2H4.GetLayout()));
            layouts.Add(VertexType.PBBNCTT, new InputLayout(device, vsbytes, VertexTypePBBNCTT.GetLayout()));
            layouts.Add(VertexType.PBBNCTTX, new InputLayout(device, vsbytes, VertexTypePBBNCTTX.GetLayout()));
            layouts.Add(VertexType.PBBNCTTT, new InputLayout(device, vsbytes, VertexTypePBBNCTTT.GetLayout()));
            layouts.Add(VertexType.PNCTT, new InputLayout(device, vsbytes, VertexTypePNCTT.GetLayout()));
            layouts.Add(VertexType.PNCTTT, new InputLayout(device, vsbytes, VertexTypePNCTTT.GetLayout()));
            layouts.Add(VertexType.PBBNCTTTX, new InputLayout(device, vsbytes, VertexTypePBBNCTTTX.GetLayout()));



            texsampler = new SamplerState(device, new SamplerStateDescription()
            {
                AddressU           = TextureAddressMode.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                BorderColor        = Color.Black,
                ComparisonFunction = Comparison.Always,
                Filter             = Filter.MinMagMipLinear,
                MaximumAnisotropy  = 1,
                MaximumLod         = float.MaxValue,
                MinimumLod         = 0,
                MipLodBias         = 0,
            });
            texsamplerc = new SamplerState(device, new SamplerStateDescription()
            {
                AddressU           = TextureAddressMode.Clamp,
                AddressV           = TextureAddressMode.Clamp,
                AddressW           = TextureAddressMode.Clamp,
                BorderColor        = Color.Black,
                ComparisonFunction = Comparison.Always,
                Filter             = Filter.MinMagMipPoint,
                MaximumAnisotropy  = 1,
                MaximumLod         = float.MaxValue,
                MinimumLod         = 0,
                MipLodBias         = 0,
            });
        }
 /// <summary>
 /// Constructs a new CPU DX-interop accelerator.
 /// </summary>
 /// <param name="accelerator">The target CPU accelerator.</param>
 /// <param name="d3dDevice">The target DX device.</param>
 internal CPUDirectXAccelerator(CPUAccelerator accelerator, Device d3dDevice)
     : base(accelerator, d3dDevice)
 {
 }
Exemplo n.º 34
0
        private bool InitializeShader(Device device, IntPtr windowHandler, string vsFileName, string psFileName)
        {
            try
            {
                // Setup full pathes
                vsFileName = SystemConfiguration.ShadersFilePath + vsFileName;
                psFileName = SystemConfiguration.ShadersFilePath + psFileName;

                // Compile the vertex shader code.
                var vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "ColorVertexShader", SystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None);
                // Compile the pixel shader code.
                var pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "ColorPixelShader", SystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None);

                // Create the vertex shader from the buffer.
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                // Create the pixel shader from the buffer.
                PixelShader = new PixelShader(device, pixelShaderByteCode);

                // Now setup the layout of the data that goes into the shader.
                // This setup needs to match the VertexType structure in the Model and in the shader.
                var inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = Format.R32G32B32A32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "COLOR",
                        SemanticIndex        = 0,
                        Format               = Format.R32G32B32A32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };

                // Create the vertex input the layout.
                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);

                // Release the vertex and pixel shader buffers, since they are no longer needed.
                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();

                // Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
                var matrixBufferDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <Matrix>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantMatrixBuffer = new Buffer(device, matrixBufferDesc);

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error initializing shader. Error is " + ex.Message);
                return(false);
            };
        }
Exemplo n.º 35
0
 public bool Initialize(Device device, IntPtr windowHandler)
 {
     // Initialize the vertex and pixel shaders.
     return(InitializeShader(device, windowHandler, "color.vs", "color.ps"));
 }
Exemplo n.º 36
0
 public MfVideoProcessor(SharpDX.Direct3D11.Device d)
 {
     this.device = d;
 }
Exemplo n.º 37
0
        private bool InitializeShader(Device device, IntPtr windowHandler, string vsFileName, string psFileName)
        {
            try
            {
                // Setup full pathes
                vsFileName = SystemConfiguration.ShadersFilePath + vsFileName;
                psFileName = SystemConfiguration.ShadersFilePath + psFileName;

                #region Initilize Shaders
                // Compile the vertex shader code.
                var vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "ClipPlaneVertexShader", SystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None);
                // Compile the pixel shader code.
                var pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "ClipPlanePixelShader", SystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None);

                // Create the vertex shader from the buffer.
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                // Create the pixel shader from the buffer.
                PixelShader = new PixelShader(device, pixelShaderByteCode);
                #endregion

                #region Initialize Input Layouts
                // Now setup the layout of the data that goes into the shader.
                // This setup needs to match the VertexType structure in the Model and in the shader.
                var inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "TEXCOORD",
                        SemanticIndex        = 0,
                        Format               = Format.R32G32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };

                // Create the vertex input the layout.
                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);
                #endregion

                // Release the vertex and pixel shader buffers, since they are no longer needed.
                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();

                #region Initialize Matrix Buffer
                // Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
                var matrixBufferDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <MatrixBuffer>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantMatrixBuffer = new Buffer(device, matrixBufferDesc);
                #endregion

                #region Initialize Sampler
                // Create a texture sampler state description.
                var samplerDesc = new SamplerStateDescription()
                {
                    Filter             = Filter.MinMagMipLinear,
                    AddressU           = TextureAddressMode.Wrap,
                    AddressV           = TextureAddressMode.Wrap,
                    AddressW           = TextureAddressMode.Wrap,
                    MipLodBias         = 0,
                    MaximumAnisotropy  = 1,
                    ComparisonFunction = Comparison.Always,
                    BorderColor        = new Color4(0, 0, 0, 0),
                    MinimumLod         = 0,
                    MaximumLod         = 0
                };

                // Create the texture sampler state.
                SampleState = new SamplerState(device, samplerDesc);
                #endregion

                #region Initialize Clip Plane Buffer
                // Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
                var clipPlaneBufferDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <ClipPlaneBuffer>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantClipPlaneBuffer = new Buffer(device, clipPlaneBufferDesc);
                #endregion

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error initializing shader. Error is " + ex.Message);
                return(false);
            };
        }
Exemplo n.º 38
0
        public ShadowMap(Direct3D11.Device device, SwapChain swapChain, int width, int height)
        {
            this.device = device;
            this.width  = width;
            this.height = height;

            viewport = new Viewport(0, 0, width, height, 0, 1f);

            //shadowMap = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);

            var depthDesc = new Texture2DDescription
            {
                Width     = this.width,
                Height    = this.height,
                MipLevels = 1,
                ArraySize = 1,
                //Format = Format.R24G8_Typeless,
                Format            = SharpDX.DXGI.Format.R32G32B32A32_Float,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                //BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource,
                BindFlags      = SharpDX.Direct3D11.BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None
            };

            DepthMap = new Texture2D(device, depthDesc);

            RenderTargetViews = new []
            {
                new RenderTargetView(device, DepthMap)
            };

            DsvText = new Texture2D(device, new Texture2DDescription()
            {
                Format            = Format.D32_Float_S8X24_UInt,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = width,
                Height            = height,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            });

            // Create the depth buffer view
            DepthMapDsv = new DepthStencilView(device, DsvText);

            //var shaderResourseViewDesc = new ShaderResourceViewDescription
            //{
            //    Format = Format.D32_Float,
            //    Dimension = ShaderResourceViewDimension.Texture2D,
            //    Texture2D = new ShaderResourceViewDescription.Texture2DResource()
            //    {
            //        MipLevels = 1,
            //        MostDetailedMip = 0,
            //    }
            //};
            //shaderResourceView = new ShaderResourceView(GameDevice, DSVText, shaderResourseViewDesc);

            //var location = System.Reflection.Assembly.GetExecutingAssembly().Location;
            //var path = Path.GetDirectoryName(location) + "\\Shaders\\ShadowMapShaders.hlsl";
            //using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile(path, "VS", "vs_5_0", ShaderFlags.PackMatrixRowMajor))
            //{
            //    shadowInputShaderSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode);
            //    shadowVertexShader = new Direct3D11.VertexShader(device, vertexShaderByteCode);
            //}

            //using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(path, "PS", "ps_5_0", ShaderFlags.PackMatrixRowMajor))
            //{
            //    shadowPixelShader = new Direct3D11.PixelShader(device, pixelShaderByteCode);
            //}

            //shadowInputLayout = new InputLayout(device, shadowInputShaderSignature, inputElements);
        }