Ejemplo n.º 1
0
        /// <summary>
        /// WIC <see cref="SharpDX.WIC.BitmapSource"/> から <see cref="SharpDX.Direct3D11.Texture2D"/> を作成する
        /// </summary>
        /// <param name="app"></param>
        /// <param name="bitmapSource">The WIC bitmap source</param>
        /// <param name="name">任意の名前</param>
        /// <returns>A Texture2D</returns>
        protected static MCTexture CreateTexture2DFromBitmap(Application app, SharpDX.WIC.BitmapSource bitmapSource, string name)
        {
            // WICイメージピクセルを受け取るためにDataStreamを割り当てます。
            int       stride = bitmapSource.Size.Width * 4;
            MCTexture tx     = new MCTexture(app, name);

            using (var buffer = new SharpDX.DataStream(bitmapSource.Size.Height * stride, true, true))
            {
                // WICの内容をバッファにコピーする
                bitmapSource.CopyPixels(stride, buffer);
                Texture123DDesc d = new Texture123DDesc();
                d.D2 = new Texture2DDescription()
                {
                    Width             = bitmapSource.Size.Width,
                    Height            = bitmapSource.Size.Height,
                    ArraySize         = 1,
                    BindFlags         = SharpDX.Direct3D11.BindFlags.ShaderResource,
                    Usage             = SharpDX.Direct3D11.ResourceUsage.Immutable,
                    CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.None,
                    Format            = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                    MipLevels         = 1,
                    OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.None,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                };
                if (tx.CreateTexture2D(0, d, new DataRectangle(buffer.DataPointer, stride)) == 1)
                {
                    return(null);
                }
            }
            return(tx);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Function to load an font from a stream.
        /// </summary>
        /// <param name="stream">The stream containing the font data to read.</param>
        /// <param name="name">[Optional] The name of the font.</param>
        /// <returns>A <see cref="GorgonFont"/> containing the font data from the stream.</returns>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="stream"/>, or the <paramref name="name"/> parameter is <b>null</b>.</exception>
        /// <exception cref="ArgumentEmptyException">Thrown when the <paramref name="stream"/> is write only.
        /// <para>-or-</para>
        /// <para>Thrown when the <paramref name="name"/> parameter is empty.</para>
        /// </exception>
        /// <exception cref="EndOfStreamException">Thrown when the amount of data requested exceeds the size of the stream minus its current position.</exception>
        public GorgonFont LoadFromStream(Stream stream, string name = null)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (!stream.CanRead)
            {
                throw new ArgumentException(Resources.GORGFX_ERR_STREAM_WRITE_ONLY, nameof(stream));
            }

            Stream externalStream = stream;

            try
            {
                if (!stream.CanSeek)
                {
                    externalStream = new DX.DataStream((int)stream.Length, true, true);
                    stream.CopyTo(externalStream);
                    externalStream.Position = 0;
                }

                return(OnLoadFromStream(name, externalStream));
            }
            finally
            {
                if (externalStream != stream)
                {
                    externalStream.Dispose();
                }
            }
        }
Ejemplo n.º 3
0
        private D3D11.ShaderResourceView LoadTexture(string name)
        {
            var converter = new SharpDX.WIC.FormatConverter(imagingFactory);
            var decoder   = new SharpDX.WIC.BitmapDecoder(imagingFactory, name, SharpDX.WIC.DecodeOptions.CacheOnDemand);

            converter.Initialize(decoder.GetFrame(0), SharpDX.WIC.PixelFormat.Format32bppBGRA, SharpDX.WIC.BitmapDitherType.None, null, 0.0, SharpDX.WIC.BitmapPaletteType.Custom);

            var stride     = converter.Size.Width * 4;
            var size       = converter.Size.Height * stride;
            var dataStream = new SharpDX.DataStream(size, true, true);

            converter.CopyPixels(stride, dataStream);
            D3D11.Texture2D tex = new D3D11.Texture2D(d3dDevice,
                                                      new D3D11.Texture2DDescription()
            {
                Width             = converter.Size.Width,
                Height            = converter.Size.Height,
                ArraySize         = 1,
                BindFlags         = D3D11.BindFlags.ShaderResource,
                Usage             = D3D11.ResourceUsage.Immutable,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                MipLevels         = 1,
                OptionFlags       = D3D11.ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
            },
                                                      new SharpDX.DataRectangle(dataStream.DataPointer, stride)
                                                      );

            return(new D3D11.ShaderResourceView(d3dDevice, tex));
        }
Ejemplo n.º 4
0
        public Object LoadImage(String filename)
        {
            Object image = null;

            if (File.Exists(filename))
            {
                using (System.Drawing.Bitmap bmp = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromFile(filename))
                {
                    System.Drawing.Imaging.BitmapData bData = bmp.LockBits(
                        new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height),
                        System.Drawing.Imaging.ImageLockMode.ReadOnly,
                        System.Drawing.Imaging.PixelFormat.Format32bppPArgb
                        );

                    SharpDX.DataStream                 stream  = new SharpDX.DataStream(bData.Scan0, bData.Stride * bData.Height, true, false);
                    SharpDX.Direct2D1.PixelFormat      pFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied);
                    SharpDX.Direct2D1.BitmapProperties bProps  = new SharpDX.Direct2D1.BitmapProperties(pFormat);

                    image = new SharpDX.Direct2D1.Bitmap(d2dRenderTarget, new Size2(bmp.Width, bmp.Height), stream, bData.Stride, bProps);
                    bmp.UnlockBits(bData);
                    stream.Dispose();
                }
            }

            return(image);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 参考自:https://github.com/sharpdx/SharpDX-Samples/blob/master/StoreApp/OldSamplesToBeBackPorted/CommonDX/TextureLoader.cs 和noire项目
        /// </summary>
        /// <param name="device">设备对象</param>
        /// <param name="bitmapSource"></param>
        /// <returns></returns>
        public static SharpDX.Direct3D11.ShaderResourceView CreateShaderResourceViewFromFile(SharpDX.Direct3D11.Device device, string fileName)
        {
            Texture2D tempTex;

            using (var bitmapSource = LoadBitmapSourceFromFile(_factory, fileName)) {
                // Allocate DataStream to receive the WIC image pixels
                int stride = bitmapSource.Size.Width * 4;
                using (var buffer = new SharpDX.DataStream(bitmapSource.Size.Height * stride, true, true)) {
                    // Copy the content of the WIC to the buffer
                    bitmapSource.CopyPixels(stride, buffer);
                    tempTex = new SharpDX.Direct3D11.Texture2D(
                        device,
                        new SharpDX.Direct3D11.Texture2DDescription()
                    {
                        Width             = bitmapSource.Size.Width,
                        Height            = bitmapSource.Size.Height,
                        ArraySize         = 1,
                        BindFlags         = SharpDX.Direct3D11.BindFlags.ShaderResource,
                        Usage             = SharpDX.Direct3D11.ResourceUsage.Immutable,
                        CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.None,
                        Format            = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                        MipLevels         = 1,
                        OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.None,
                        SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                    },
                        new SharpDX.DataRectangle(buffer.DataPointer, stride));
                    bitmapSource.Dispose();
                }
            }
            return(new ShaderResourceView(device, tempTex));
        }
Ejemplo n.º 6
0
        /*
         * public void RenderSoftBodyTextured(SoftBody softBody)
         * {
         *  if (!(softBody.UserObject is Array))
         *      return;
         *
         *  object[] userObjArr = softBody.UserObject as object[];
         *  FloatArray vertexBuffer = userObjArr[0] as FloatArray;
         *  IntArray indexBuffer = userObjArr[1] as IntArray;
         *
         *  int vertexCount = (vertexBuffer.Count / 8);
         *
         *  if (vertexCount > 0)
         *  {
         *      int faceCount = indexBuffer.Count / 2;
         *
         *      bool index32 = vertexCount > 65536;
         *
         *      Mesh mesh = new Mesh(device, faceCount, vertexCount,
         *          MeshFlags.SystemMemory | (index32 ? MeshFlags.Use32Bit : 0),
         *          VertexFormat.Position | VertexFormat.Normal | VertexFormat.Texture1);
         *
         *      SlimDX.DataStream indices = mesh.LockIndexBuffer(LockFlags.Discard);
         *      if (index32)
         *      {
         *          foreach (int i in indexBuffer)
         *              indices.Write(i);
         *      }
         *      else
         *      {
         *          foreach (int i in indexBuffer)
         *              indices.Write((ushort)i);
         *      }
         *      mesh.UnlockIndexBuffer();
         *
         *      SlimDX.DataStream verts = mesh.LockVertexBuffer(LockFlags.Discard);
         *      foreach (float f in vertexBuffer)
         *          verts.Write(f);
         *      mesh.UnlockVertexBuffer();
         *
         *      mesh.ComputeNormals();
         *      mesh.DrawSubset(0);
         *      mesh.Dispose();
         *  }
         * }
         * */

        public static Buffer CreateScreenQuad(Device device)
        {
            Buffer vertexBuffer;

            BufferDescription vertexBufferDesc = new BufferDescription()
            {
                SizeInBytes = sizeof(float) * 5 * 4,
                Usage       = ResourceUsage.Default,
                BindFlags   = BindFlags.VertexBuffer,
            };

            using (var data = new SharpDX.DataStream(vertexBufferDesc.SizeInBytes, false, true))
            {
                data.Write(new Vector3(0.5f, 0.5f, 0));
                data.Write(new Vector2(1, 0));
                data.Write(new Vector3(0.5f, -0.5f, 0));
                data.Write(new Vector2(1, 1));
                data.Write(new Vector3(-0.5f, 0.5f, 0));
                data.Write(new Vector2(0, 0));
                data.Write(new Vector3(-0.5f, -0.5f, 0));
                data.Write(new Vector2(0, 1));
                data.Position = 0;
                vertexBuffer  = new Buffer(device, data, vertexBufferDesc);
            }

            return(vertexBuffer);
        }
Ejemplo n.º 7
0
        // 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);
            }
        }
Ejemplo n.º 8
0
    public static SharpDX.Direct2D1.Bitmap Test(SharpDX.Direct2D1.DeviceContext dc, ImagingFactory factory, System.Windows.Media.Imaging.BitmapSource src)
    {
        // PixelFormat settings/conversion
        if (src.Format != System.Windows.Media.PixelFormats.Bgra32)
        {
            // Convert BitmapSource
            FormatConvertedBitmap fcb = new FormatConvertedBitmap();
            fcb.BeginInit();
            fcb.Source            = src;
            fcb.DestinationFormat = PixelFormats.Bgra32;
            fcb.EndInit();
            src = fcb;
        }

        SharpDX.Direct2D1.Bitmap retval = null;
        try
        {
            int    stride     = src.PixelWidth * (src.Format.BitsPerPixel + 7) / 8;
            int    bufferSize = stride * src.PixelHeight;
            byte[] buffer     = new byte[bufferSize];
            src.CopyPixels(Int32Rect.Empty, buffer, stride, 0);
            GCHandle           pinnedArray = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            IntPtr             pointer     = pinnedArray.AddrOfPinnedObject();
            SharpDX.DataStream datastream  = new SharpDX.DataStream(pointer, bufferSize, true, true);
            var bmpProps1 = new SharpDX.Direct2D1.BitmapProperties1(dc.PixelFormat, dc.Factory.DesktopDpi.Width, dc.Factory.DesktopDpi.Height);

            retval = new SharpDX.Direct2D1.Bitmap1(dc, new SharpDX.Size2(src.PixelWidth, src.PixelHeight), datastream, stride, bmpProps1);
            pinnedArray.Free();
        }
        catch (Exception e)
        {
        }
        return(retval);
    }
Ejemplo n.º 9
0
        // Used with soft bodies
        public void SetDynamicVertexBuffer(Device device, Vector3[] vectors)
        {
            if (VertexBuffer != null && VertexCount * 2 == vectors.Length)
            {
                // Update existing buffer
                using (var data = VertexBuffer.Map(MapMode.WriteDiscard))
                {
                    data.WriteRange(vectors, 0, vectors.Length);
                    VertexBuffer.Unmap();
                }
            }
            else
            {
                // Create new buffer
                if (VertexBuffer != null)
                    VertexBuffer.Dispose();

                BufferDescription vertexBufferDesc = new BufferDescription()
                {
                    SizeInBytes = Marshal.SizeOf(typeof(Vector3)) * 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);
                }

                BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Function to load an image from a stream.
        /// </summary>
        /// <param name="stream">The stream containing the image data to read.</param>
        /// <param name="size">[Optional] The size of the image within the stream, in bytes.</param>
        /// <returns>A <see cref="IGorgonImage"/> containing the image data from the stream.</returns>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="stream"/> parameter is <b>null</b>.</exception>
        /// <exception cref="ArgumentEmptyException">Thrown when the <paramref name="stream"/> is write only.</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when the <paramref name="size"/> parameter is less than 1.</exception>
        /// <exception cref="EndOfStreamException">Thrown when the amount of data requested exceeds the size of the stream minus its current position.</exception>
        /// <exception cref="GorgonException">Thrown when the image data in the stream has a pixel format that is unsupported.</exception>
        /// <remarks>
        /// <para>
        /// When the <paramref name="size"/> parameter is specified, the image data will be read from the stream up to the amount specified. If it is omitted, then image data will be read up to the end of
        /// the stream.
        /// </para>
        /// </remarks>
        public IGorgonImage LoadFromStream(Stream stream, long?size = null)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (!stream.CanRead)
            {
                throw new ArgumentException(Resources.GORIMG_ERR_STREAM_IS_WRITEONLY, nameof(stream));
            }

            if (size + stream.Position > stream.Length)
            {
                throw new EndOfStreamException();
            }

            if (size < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(size), Resources.GORIMG_ERR_IMAGE_BYTE_LENGTH_TOO_SHORT);
            }

            long basePosition = stream.Position;

            if (size == null)
            {
                size = stream.Length;
            }

            Stream externalStream = stream;

            try
            {
                if (!stream.CanSeek)
                {
                    externalStream = new DX.DataStream((int)(size ?? stream.Length), true, true);
                    stream.CopyTo(externalStream, (int)(size ?? stream.Length));
                    externalStream.Position = 0;
                }

                IGorgonImage result = OnDecodeFromStream(externalStream, size.Value);

                // Move the base stream to the number of bytes written (this is already done if we've copied the stream into memory above).
                if (stream.Position < basePosition + size)
                {
                    stream.Position = basePosition + size.Value;
                }

                return(result);
            }
            finally
            {
                if (externalStream != stream)
                {
                    externalStream?.Dispose();
                }
            }
        }
Ejemplo n.º 11
0
        public void DrawDebugWorld(DynamicsWorld world)
        {
            world.DebugDrawWorld();

            if (lines.Count == 0)
            {
                return;
            }

            inputAssembler.InputLayout = inputLayout;

            if (lineArray.Length != lines.Count)
            {
                lineArray = new PositionColored[lines.Count];
                lines.CopyTo(lineArray);

                if (vertexBuffer != null)
                {
                    vertexBuffer.Dispose();
                }
                vertexBufferDesc.SizeInBytes = PositionColored.Stride * lines.Count;
                using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true))
                {
                    data.WriteRange(lineArray);
                    data.Position = 0;
                    vertexBuffer  = new Buffer(device, data, vertexBufferDesc);
                }
                vertexBufferBinding.Buffer = vertexBuffer;
            }
            else
            {
                lines.CopyTo(lineArray);

                DataStream ds;
                var        map = device.ImmediateContext.MapSubresource(vertexBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out ds);
                ds.WriteRange(lineArray);
                device.ImmediateContext.UnmapSubresource(vertexBuffer, 0);
            }

            inputAssembler.SetVertexBuffers(0, vertexBufferBinding);
            inputAssembler.PrimitiveTopology = global::SharpDX.Direct3D.PrimitiveTopology.LineList;

            device.ImmediateContext.VertexShader.Set(vertexShader);
            device.ImmediateContext.PixelShader.Set(pixelShader);
            device.ImmediateContext.Draw(lines.Count, 0);

            lines.Clear();
        }
        /// <summary>
        /// Function to read the sprite data from a stream.
        /// </summary>
        /// <param name="stream">The stream containing the sprite.</param>
        /// <param name="overrideTexture">[Optional] The texture to use as an override for the sprite.</param>
        /// <param name="byteCount">[Optional] The number of bytes to read from the stream.</param>
        /// <returns>A new <see cref="GorgonPolySprite"/>.</returns>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="stream"/> parameter is <b>null</b>.</exception>
        /// <exception cref="GorgonException">Thrown if the <paramref name="stream"/> is write only.</exception>
        /// <exception cref="EndOfStreamException">Thrown if the current <paramref name="stream"/> position, plus the size of the data exceeds the length of the stream.</exception>
        /// <exception cref="NotSupportedException">This method is not supported by this codec.</exception>
        public GorgonPolySprite FromStream(Stream stream, GorgonTexture2DView overrideTexture = null, int?byteCount = null)
        {
            if (!CanDecode)
            {
                throw new NotSupportedException();
            }

            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (!stream.CanRead)
            {
                throw new GorgonException(GorgonResult.CannotRead, Resources.GOR2DIO_ERR_STREAM_IS_WRITE_ONLY);
            }

            if (byteCount == null)
            {
                byteCount = (int)stream.Length;
            }

            if ((stream.Position + byteCount.Value) > stream.Length)
            {
                throw new EndOfStreamException();
            }

            Stream externalStream = stream;

            try
            {
                if (!stream.CanSeek)
                {
                    externalStream = new DX.DataStream(byteCount ?? (int)stream.Length, true, true);
                    stream.CopyTo(externalStream, byteCount ?? (int)stream.Length);
                    externalStream.Position = 0;
                }

                return(OnReadFromStream(externalStream, byteCount.Value, overrideTexture));
            }
            finally
            {
                if (externalStream != stream)
                {
                    externalStream?.Dispose();
                }
            }
        }
Ejemplo n.º 13
0
        public void SetVertexBuffer(Device device, Vector3[] vectors)
        {
            BufferDescription vertexBufferDesc = new BufferDescription()
            {
                SizeInBytes = Vector3.SizeInBytes * vectors.Length,
                Usage       = ResourceUsage.Default,
                BindFlags   = BindFlags.VertexBuffer
            };

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

            BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0);
        }
Ejemplo n.º 14
0
        public void SetIndexBuffer(Device device, uint[] indices)
        {
            IndexFormat = Format.R32_UInt;

            BufferDescription indexBufferDesc = new BufferDescription()
            {
                SizeInBytes = sizeof(uint) * indices.Length,
                Usage       = ResourceUsage.Default,
                BindFlags   = BindFlags.IndexBuffer
            };

            using (var data = new DataStream(indexBufferDesc.SizeInBytes, false, true))
            {
                data.WriteRange(indices);
                data.Position = 0;
                IndexBuffer   = new Buffer(device, data, indexBufferDesc);
            }
        }
Ejemplo n.º 15
0
        public void SetVertexBuffer(Device device, Vector3[] vectors)
        {
            BufferDescription vertexBufferDesc = new BufferDescription()
            {
                SizeInBytes = Vector3.SizeInBytes * vectors.Length,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.VertexBuffer
            };

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

            BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0);
        }
        /// <summary>
        /// Creates the constant buffer object.
        /// </summary>
        protected internal override D3D11.Buffer CreateConstantBuffer(EngineDevice device)
        {
            using (var dataStream = new SharpDX.DataStream(SharpDX.Utilities.SizeOf <T>(), true, true))
            {
                dataStream.Write(m_initialData);
                dataStream.Position = 0;

                return(new D3D11.Buffer(
                           device.DeviceD3D11_1,
                           dataStream,
                           new D3D11.BufferDescription(
                               m_structureSize,
                               D3D11.ResourceUsage.Dynamic,
                               D3D11.BindFlags.ConstantBuffer,
                               D3D11.CpuAccessFlags.Write,
                               D3D11.ResourceOptionFlags.None,
                               0)));
            }
        }
Ejemplo n.º 17
0
        public void SetVertexBuffer(Device device, Vector3[] vertices)
        {
            BufferDescription vertexBufferDesc = new BufferDescription()
            {
                SizeInBytes = Marshal.SizeOf(typeof(Vector3)) * vertices.Length,
                Usage       = ResourceUsage.Default,
                BindFlags   = BindFlags.VertexBuffer
            };

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

            BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0);
        }
Ejemplo n.º 18
0
        internal ShaderResourceView GetShaderResourceFromFile(SharpDX.Direct3D11.Device device, string imagePath)
        {
            using (var oBitmapSource = LoadBitmap(new SharpDX.WIC.ImagingFactory2(), imagePath))
            {
                //The stride is the number of bytes per "line". This is the width times the number of bytes per pixel, which is 4
                int iStride = oBitmapSource.Size.Width * 4;
                using (var oBuffer = new SharpDX.DataStream(oBitmapSource.Size.Height * iStride, true, true))
                {
                    // Copy the content of the WIC to the buffer
                    oBitmapSource.CopyPixels(iStride, oBuffer);

                    using (var oTexture = CreateTexture2DFromBitmap(device, oBuffer, oBitmapSource.Size.Width, oBitmapSource.Size.Height))
                    {
                        ShaderResourceView oShaderResourceView = new ShaderResourceView(device, oTexture);
                        return(oShaderResourceView);
                    }
                }
            }
        }
Ejemplo n.º 19
0
    void ModifyVertexBuffer()
    {
        var bufferHandle = m_VertexBufferHandle;
        int vertexCount  = m_VertexBufferVertexCount;

        if (bufferHandle == System.IntPtr.Zero)
        {
            return;
        }

        float t = m_Time * 3.0f;

        System.Func <int, byte[]> getPadding = bufferSize =>
        {
            var stride = (int)(bufferSize / vertexCount);
            return(new byte[stride - (3 + 3 + 2) * 4]);
        };

        System.Action <System.IntPtr, int, byte[]> callback = (ptr, size, padding) =>
        {
            using (var stream = new SharpDX.DataStream(ptr, size, false, true))
            {
                // modify vertex Y position with several scrolling sine waves,
                // copy the rest of the source data unmodified
                for (int i = 0; i < vertexCount; ++i)
                {
                    var src = m_VertexSource[i];
                    stream.Write(src.pos.x);
                    stream.Write(src.pos.y + UnityEngine.Mathf.Sin(src.pos[0] * 1.1f + t) * 0.4f + UnityEngine.Mathf.Sin(src.pos[2] * 0.9f - t) * 0.3f);
                    stream.Write(src.pos.z);
                    stream.Write(src.normal);
                    stream.Write(src.uv);
                    stream.Write(padding, 0, padding.Length);
                }
            }
        };

        BeginModifyVertexBuffer(bufferHandle
                                , getPadding
                                , callback);
    }
Ejemplo n.º 20
0
        public static D3D11.Texture2D CreateTexture2DFromBitmap(D3D11.Device device, SharpDX.WIC.BitmapSource bitmapSource)
        {
            // Allocate DataStream to receive the WIC image pixels
            int stride = bitmapSource.Size.Width * 4;

            using (var buffer = new SharpDX.DataStream(bitmapSource.Size.Height * stride, true, true)) {
                // Copy the content of the WIC to the buffer
                bitmapSource.CopyPixels(stride, buffer);
                return(new D3D11.Texture2D(device, new D3D11.Texture2DDescription()
                {
                    Width = bitmapSource.Size.Width,
                    Height = bitmapSource.Size.Height,
                    ArraySize = 1,
                    BindFlags = D3D11.BindFlags.ShaderResource,
                    Usage = D3D11.ResourceUsage.Immutable,
                    CpuAccessFlags = D3D11.CpuAccessFlags.None,
                    Format = Format.R8G8B8A8_UNorm,
                    MipLevels = 1,
                    OptionFlags = D3D11.ResourceOptionFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                }, new DataRectangle(buffer.DataPointer, stride)));
            }
        }
Ejemplo n.º 21
0
        public void Initialize()
        {
            Form.SizeChanged += (o, args) =>
            {
                if (_swapChain == null)
                {
                    return;
                }

                renderView.Dispose();
                depthView.Dispose();
                DisposeBuffers();

                if (Form.WindowState == FormWindowState.Minimized)
                {
                    return;
                }

                Width  = Form.ClientSize.Width;
                Height = Form.ClientSize.Height;
                _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0);

                CreateBuffers();
                SetSceneConstants();
            };

            Width       = 1024;
            Height      = 768;
            NearPlane   = 1.0f;
            FarPlane    = 200.0f;
            FieldOfView = (float)Math.PI / 4;

            try
            {
                OnInitializeDevice();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Could not create DirectX 11 device.");
                return;
            }


            // shader.fx

            const ShaderFlags shaderFlags = ShaderFlags.None;

            //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization;

            string[] sources = { "shader.fx", "grender.fx" };
            using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), sources, shaderFlags))
            {
                effect = new Effect(_device, shaderByteCode);
            }
            EffectTechnique technique = effect.GetTechniqueByName("GBufferCreate");

            shadowGenPass  = technique.GetPassByName("ShadowMap");
            gBufferGenPass = technique.GetPassByName("GBufferGen");
            debugDrawPass  = technique.GetPassByName("DebugDraw");

            BufferDescription sceneConstantsDesc = new BufferDescription()
            {
                SizeInBytes    = Marshal.SizeOf(typeof(ShaderSceneConstants)),
                Usage          = ResourceUsage.Dynamic,
                BindFlags      = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags    = ResourceOptionFlags.None
            };

            sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc);
            EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene");

            effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer);

            RasterizerStateDescription _rasterizerStateDesc = new RasterizerStateDescription()
            {
                CullMode             = CullMode.None,
                FillMode             = FillMode.Solid,
                DepthBias            = 0,
                DepthBiasClamp       = 0,
                SlopeScaledDepthBias = 0,
                IsDepthClipEnabled   = true,
            };

            noCullState = new RasterizerState(_device, _rasterizerStateDesc);
            _rasterizerStateDesc.CullMode = CullMode.Back;
            backCullState = new RasterizerState(_device, _rasterizerStateDesc);
            _rasterizerStateDesc.CullMode = CullMode.Front;
            frontCullState = new RasterizerState(_device, _rasterizerStateDesc);
            _immediateContext.Rasterizer.State = CullingEnabled ? backCullState : noCullState;

            DepthStencilStateDescription depthDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                IsStencilEnabled = false,
                DepthWriteMask   = DepthWriteMask.All,
                DepthComparison  = Comparison.Less
            };

            depthState = new DepthStencilState(_device, depthDesc);
            depthDesc.DepthWriteMask     = DepthWriteMask.Zero;
            outsideLightVolumeDepthState = new DepthStencilState(_device, depthDesc);
            depthDesc.DepthComparison    = Comparison.Greater;
            insideLightVolumeDepthState  = new DepthStencilState(_device, depthDesc);

            DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                IsStencilEnabled = false,
                DepthWriteMask   = DepthWriteMask.All,
                DepthComparison  = Comparison.Less
            };

            lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc);


            // grender.fx
            technique               = effect.GetTechniqueByName("DeferredShader");
            gBufferRenderPass       = technique.GetPassByName("DeferredShader");
            gBufferPostProcessPass  = technique.GetPassByName("Blur");
            gBufferPostProcessPass2 = technique.GetPassByName("PostProcess");
            gBufferOverlayPass      = technique.GetPassByName("Overlay");

            lightBufferVar            = effect.GetVariableByName("lightBuffer").AsShaderResource();
            normalBufferVar           = effect.GetVariableByName("normalBuffer").AsShaderResource();
            diffuseBufferVar          = effect.GetVariableByName("diffuseBuffer").AsShaderResource();
            depthMapVar               = effect.GetVariableByName("depthMap").AsShaderResource();
            shadowLightDepthBufferVar = effect.GetVariableByName("lightDepthMap").AsShaderResource();

            sunLightDirectionVar = effect.GetVariableByName("SunLightDirection").AsVector();
            viewportWidthVar     = effect.GetVariableByName("ViewportWidth").AsScalar();
            viewportHeightVar    = effect.GetVariableByName("ViewportHeight").AsScalar();
            viewParametersVar    = effect.GetVariableByName("ViewParameters").AsVector();

            overlayViewProjectionVar = effect.GetVariableByName("OverlayViewProjection").AsMatrix();


            // light.fx
            using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), "light.fx", shaderFlags))
            {
                lightShader = new Effect(_device, shaderByteCode);
            }

            technique             = lightShader.GetTechniqueByIndex(0);
            lightAccumulationPass = technique.GetPassByName("Light");

            lightWorldVar          = lightShader.GetVariableByName("World").AsMatrix();
            lightPositionRadiusVar = lightShader.GetVariableByName("PositionRadius").AsVector();
            lightColorVar          = lightShader.GetVariableByName("Color").AsVector();

            lightProjectionVar     = lightShader.GetVariableByName("Projection").AsMatrix();
            lightViewVar           = lightShader.GetVariableByName("View").AsMatrix();
            lightViewInverseVar    = lightShader.GetVariableByName("ViewInverse").AsMatrix();
            lightViewportWidthVar  = lightShader.GetVariableByName("ViewportWidth").AsScalar();
            lightViewportHeightVar = lightShader.GetVariableByName("ViewportHeight").AsScalar();
            lightEyePositionVar    = lightShader.GetVariableByName("EyePosition").AsVector();
            lightViewParametersVar = lightShader.GetVariableByName("ViewParameters").AsVector();

            InputElement[] elements =
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
            };
            lightVolumeInputLayout = new InputLayout(Device, lightShader.GetTechniqueByIndex(0).GetPassByName("Light").Description.Signature, elements);

            pointLightVolumeVertices = Light.CreatePointLightVolume(out pointLightVolumeIndices);
            BufferDescription vertexBufferDesc = new BufferDescription()
            {
                SizeInBytes = Vector3.SizeInBytes * pointLightVolumeVertices.Length,
                Usage       = ResourceUsage.Default,
                BindFlags   = BindFlags.VertexBuffer,
            };

            using (var data = new SharpDX.DataStream(vertexBufferDesc.SizeInBytes, false, true))
            {
                data.WriteRange(pointLightVolumeVertices);
                data.Position = 0;
                pointLightVolumeVertexBuffer = new Buffer(Device, data, vertexBufferDesc);
            }
            pointLightVolumeVertexBufferBinding = new VertexBufferBinding(pointLightVolumeVertexBuffer, 12, 0);

            BufferDescription indexBufferDesc = new BufferDescription()
            {
                SizeInBytes = sizeof(uint) * pointLightVolumeIndices.Length,
                Usage       = ResourceUsage.Default,
                BindFlags   = BindFlags.IndexBuffer
            };

            using (var data = new SharpDX.DataStream(indexBufferDesc.SizeInBytes, false, true))
            {
                data.WriteRange(pointLightVolumeIndices);
                data.Position = 0;
                pointLightVolumeIndexBuffer = new Buffer(Device, data, indexBufferDesc);
            }

            lightDepthBufferVar  = lightShader.GetVariableByName("depthBuffer").AsShaderResource();
            lightNormalBufferVar = lightShader.GetVariableByName("normalBuffer").AsShaderResource();

            lights.Add(new Light(pointLightPosition, 60, new Vector4(1, 0.95f, 0.9f, 1)));
            //lights.Add(new Light(pointLightPosition, 60, new Vector4(0, 0, 1, 1)));
            //lights.Add(new Light(new Vector3(-10, 10, 10), 30, new Vector4(1, 0, 0, 1)));
            //lights.Add(new Light(new Vector3(10, 5, -10), 20, new Vector4(0, 1, 0, 1)));
            //lights.Add(new Light(new Vector3(-10, 5, -10), 20, new Vector4(1, 0, 1, 1)));


            Info         = new InfoText(_device, 256, 256);
            _meshFactory = new MeshFactory(this);

            CreateBuffers();
        }
Ejemplo n.º 22
0
        public void SetIndexBuffer(Device device, uint[] indices)
        {
            IndexFormat = Format.R32_UInt;

            BufferDescription indexBufferDesc = new BufferDescription()
            {
                SizeInBytes = sizeof(uint) * indices.Length,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.IndexBuffer
            };

            using (var data = new DataStream(indexBufferDesc.SizeInBytes, false, true))
            {
                data.WriteRange(indices);
                data.Position = 0;
                IndexBuffer = new Buffer(device, data, indexBufferDesc);
            }
        }
        public void DrawDebugWorld(DynamicsWorld world)
        {
            world.DebugDrawWorld();

            if (lines.Count == 0)
                return;

            inputAssembler.InputLayout = inputLayout;

            if (lineArray.Length != lines.Count)
            {
                lineArray = new PositionColored[lines.Count];
                lines.CopyTo(lineArray);

                if (vertexBuffer != null)
                {
                    vertexBuffer.Dispose();
                }
                vertexBufferDesc.SizeInBytes = PositionColored.Stride * lines.Count;
                using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true))
                {
                    data.WriteRange(lineArray);
                    data.Position = 0;
                    vertexBuffer = new Buffer(device, data, vertexBufferDesc);
                }
                vertexBufferBinding.Buffer = vertexBuffer;
            }
            else
            {
                lines.CopyTo(lineArray);

                DataStream ds;
                var map = device.ImmediateContext.MapSubresource(vertexBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out ds);
                ds.WriteRange(lineArray);
                device.ImmediateContext.UnmapSubresource(vertexBuffer, 0);
            }

            inputAssembler.SetVertexBuffers(0, vertexBufferBinding);
            inputAssembler.PrimitiveTopology = global::SharpDX.Direct3D.PrimitiveTopology.LineList;

            device.ImmediateContext.VertexShader.Set(vertexShader);
            device.ImmediateContext.PixelShader.Set(pixelShader);
            device.ImmediateContext.Draw(lines.Count, 0);

            lines.Clear();
        }
Ejemplo n.º 24
0
        private static SharpDX.Direct3D11.Texture2D CreateTexture2DFromBitmap(SharpDX.Direct3D11.Device device, SharpDX.DataStream buffer, int width, int height)
        {
            int iStride = width * 4;

            return(new SharpDX.Direct3D11.Texture2D(device, new SharpDX.Direct3D11.Texture2DDescription()
            {
                Width = width,
                Height = height,
                ArraySize = 1,
                BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource,
                Usage = SharpDX.Direct3D11.ResourceUsage.Immutable,
                CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None,
                Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                MipLevels = 1,
                OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
            }, new SharpDX.DataRectangle(buffer.DataPointer, iStride)));
        }
Ejemplo n.º 25
0
        public void Initialize()
        {
            Form.SizeChanged += (o, args) =>
            {
                if (_swapChain == null)
                    return;

                renderView.Dispose();
                depthView.Dispose();
                DisposeBuffers();

                if (Form.WindowState == FormWindowState.Minimized)
                    return;

                Width = Form.ClientSize.Width;
                Height = Form.ClientSize.Height;
                _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0);

                CreateBuffers();
                SetSceneConstants();
            };

            Width = 1024;
            Height = 768;
            NearPlane = 1.0f;
            FarPlane = 200.0f;
            FieldOfView = (float)Math.PI / 4;

            try
            {
                OnInitializeDevice();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Could not create DirectX 11 device.");
                return;
            }


            // shader.fx

            const ShaderFlags shaderFlags = ShaderFlags.None;
            //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization;

            string[] sources = new[] { "shader.fx", "grender.fx" };
            using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), sources, shaderFlags))
            {
                effect = new Effect(_device, shaderByteCode);
            }
            EffectTechnique technique = effect.GetTechniqueByName("GBufferCreate");
            shadowGenPass = technique.GetPassByName("ShadowMap");
            gBufferGenPass = technique.GetPassByName("GBufferGen");
            debugDrawPass = technique.GetPassByName("DebugDraw");

            BufferDescription sceneConstantsDesc = new BufferDescription()
            {
                SizeInBytes = Marshal.SizeOf(typeof(ShaderSceneConstants)),
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None
            };
            sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc);
            EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene");
            effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer);

            RasterizerStateDescription _rasterizerStateDesc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = 0,
                IsDepthClipEnabled = true,
            };
            noCullState = new RasterizerState(_device, _rasterizerStateDesc);
            _rasterizerStateDesc.CullMode = CullMode.Back;
            backCullState = new RasterizerState(_device, _rasterizerStateDesc);
            _rasterizerStateDesc.CullMode = CullMode.Front;
            frontCullState = new RasterizerState(_device, _rasterizerStateDesc);
            _immediateContext.Rasterizer.State = CullingEnabled ? backCullState : noCullState;

            DepthStencilStateDescription depthDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };
            depthState = new DepthStencilState(_device, depthDesc);
            depthDesc.DepthWriteMask = DepthWriteMask.Zero;
            outsideLightVolumeDepthState = new DepthStencilState(_device, depthDesc);
            depthDesc.DepthComparison = Comparison.Greater;
            insideLightVolumeDepthState = new DepthStencilState(_device, depthDesc);

            DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };
            lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc);


            // grender.fx
            technique = effect.GetTechniqueByName("DeferredShader");
            gBufferRenderPass = technique.GetPassByName("DeferredShader");
            gBufferPostProcessPass = technique.GetPassByName("Blur");
            gBufferPostProcessPass2 = technique.GetPassByName("PostProcess");
            gBufferOverlayPass = technique.GetPassByName("Overlay");

            lightBufferVar = effect.GetVariableByName("lightBuffer").AsShaderResource();
            normalBufferVar = effect.GetVariableByName("normalBuffer").AsShaderResource();
            diffuseBufferVar = effect.GetVariableByName("diffuseBuffer").AsShaderResource();
            depthMapVar = effect.GetVariableByName("depthMap").AsShaderResource();
            shadowLightDepthBufferVar = effect.GetVariableByName("lightDepthMap").AsShaderResource();

            sunLightDirectionVar = effect.GetVariableByName("SunLightDirection").AsVector();
            viewportWidthVar = effect.GetVariableByName("ViewportWidth").AsScalar();
            viewportHeightVar = effect.GetVariableByName("ViewportHeight").AsScalar();
            viewParametersVar = effect.GetVariableByName("ViewParameters").AsVector();

            overlayViewProjectionVar = effect.GetVariableByName("OverlayViewProjection").AsMatrix();


            // light.fx
            using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), "light.fx", shaderFlags))
            {
                lightShader = new Effect(_device, shaderByteCode);
            }

            technique = lightShader.GetTechniqueByIndex(0);
            lightAccumulationPass = technique.GetPassByName("Light");

            lightWorldVar = lightShader.GetVariableByName("World").AsMatrix();
            lightPositionRadiusVar = lightShader.GetVariableByName("PositionRadius").AsVector();
            lightColorVar = lightShader.GetVariableByName("Color").AsVector();

            lightProjectionVar = lightShader.GetVariableByName("Projection").AsMatrix();
            lightViewVar = lightShader.GetVariableByName("View").AsMatrix();
            lightViewInverseVar = lightShader.GetVariableByName("ViewInverse").AsMatrix();
            lightViewportWidthVar = lightShader.GetVariableByName("ViewportWidth").AsScalar();
            lightViewportHeightVar = lightShader.GetVariableByName("ViewportHeight").AsScalar();
            lightEyePositionVar = lightShader.GetVariableByName("EyePosition").AsVector();
            lightViewParametersVar = lightShader.GetVariableByName("ViewParameters").AsVector();

            InputElement[] elements = new InputElement[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
            };
            lightVolumeInputLayout = new InputLayout(Device, lightShader.GetTechniqueByIndex(0).GetPassByName("Light").Description.Signature, elements);

            pointLightVolumeVertices = Light.CreatePointLightVolume(out pointLightVolumeIndices);
            BufferDescription vertexBufferDesc = new BufferDescription()
            {
                SizeInBytes = Vector3.SizeInBytes * pointLightVolumeVertices.Length,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.VertexBuffer,
            };

            using (var data = new SharpDX.DataStream(vertexBufferDesc.SizeInBytes, false, true))
            {
                data.WriteRange(pointLightVolumeVertices);
                data.Position = 0;
                pointLightVolumeVertexBuffer = new Buffer(Device, data, vertexBufferDesc);
            }
            pointLightVolumeVertexBufferBinding = new VertexBufferBinding(pointLightVolumeVertexBuffer, 12, 0);

            BufferDescription indexBufferDesc = new BufferDescription()
            {
                SizeInBytes = sizeof(uint) * pointLightVolumeIndices.Length,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.IndexBuffer
            };
            using (var data = new SharpDX.DataStream(indexBufferDesc.SizeInBytes, false, true))
            {
                data.WriteRange(pointLightVolumeIndices);
                data.Position = 0;
                pointLightVolumeIndexBuffer = new Buffer(Device, data, indexBufferDesc);
            }

            lightDepthBufferVar = lightShader.GetVariableByName("depthBuffer").AsShaderResource();
            lightNormalBufferVar = lightShader.GetVariableByName("normalBuffer").AsShaderResource();

            lights.Add(new Light(pointLightPosition, 60, new Vector4(1, 0.95f, 0.9f, 1)));
            //lights.Add(new Light(pointLightPosition, 60, new Vector4(0, 0, 1, 1)));
            //lights.Add(new Light(new Vector3(-10, 10, 10), 30, new Vector4(1, 0, 0, 1)));
            //lights.Add(new Light(new Vector3(10, 5, -10), 20, new Vector4(0, 1, 0, 1)));
            //lights.Add(new Light(new Vector3(-10, 5, -10), 20, new Vector4(1, 0, 1, 1)));


            Info = new InfoText(_device, 256, 256);
            _meshFactory = new MeshFactory(this);

            CreateBuffers();
        }
Ejemplo n.º 26
0
        /*
        public void RenderSoftBodyTextured(SoftBody softBody)
        {
            if (!(softBody.UserObject is Array))
                return;

            object[] userObjArr = softBody.UserObject as object[];
            FloatArray vertexBuffer = userObjArr[0] as FloatArray;
            IntArray indexBuffer = userObjArr[1] as IntArray;

            int vertexCount = (vertexBuffer.Count / 8);

            if (vertexCount > 0)
            {
                int faceCount = indexBuffer.Count / 2;

                bool index32 = vertexCount > 65536;

                Mesh mesh = new Mesh(device, faceCount, vertexCount,
                    MeshFlags.SystemMemory | (index32 ? MeshFlags.Use32Bit : 0),
                    VertexFormat.Position | VertexFormat.Normal | VertexFormat.Texture1);

                SlimDX.DataStream indices = mesh.LockIndexBuffer(LockFlags.Discard);
                if (index32)
                {
                    foreach (int i in indexBuffer)
                        indices.Write(i);
                }
                else
                {
                    foreach (int i in indexBuffer)
                        indices.Write((ushort)i);
                }
                mesh.UnlockIndexBuffer();

                SlimDX.DataStream verts = mesh.LockVertexBuffer(LockFlags.Discard);
                foreach (float f in vertexBuffer)
                    verts.Write(f);
                mesh.UnlockVertexBuffer();

                mesh.ComputeNormals();
                mesh.DrawSubset(0);
                mesh.Dispose();
            }
        }
         * */
        public static Buffer CreateScreenQuad(Device device)
        {
            Buffer vertexBuffer;

            BufferDescription vertexBufferDesc = new BufferDescription()
            {
                SizeInBytes = sizeof(float) * 5 * 4,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.VertexBuffer,
            };

            using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true))
            {
                data.Write(new Vector3(0.5f, 0.5f, 0));
                data.Write(new Vector2(1, 0));
                data.Write(new Vector3(0.5f, -0.5f, 0));
                data.Write(new Vector2(1, 1));
                data.Write(new Vector3(-0.5f, 0.5f, 0));
                data.Write(new Vector2(0, 0));
                data.Write(new Vector3(-0.5f, -0.5f, 0));
                data.Write(new Vector2(0, 1));
                data.Position = 0;
                vertexBuffer = new Buffer(device, data, vertexBufferDesc);
            }

            return vertexBuffer;
        }
Ejemplo n.º 27
0
        // Used with soft bodies
        public void SetDynamicVertexBuffer(Device device, Vector3[] vectors)
        {
            if (VertexBuffer != null && VertexCount * 2 == vectors.Length)
            {
                // Update existing buffer
                using (var data = VertexBuffer.Map(MapMode.WriteDiscard))
                {
                    data.WriteRange(vectors, 0, vectors.Length);
                    VertexBuffer.Unmap();
                }
            }
            else
            {
                // Create new buffer
                if (VertexBuffer != null)
                    VertexBuffer.Dispose();

                BufferDescription vertexBufferDesc = new BufferDescription()
                {
                    SizeInBytes = Marshal.SizeOf(typeof(Vector3)) * 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);
                }

                BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0);
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Function to create the resources for the buffer.
        /// </summary>
        /// <param name="data">The initial data for the buffer.</param>
        private void CreateResources(GorgonDataStream data)
        {
            var desc = new D3D.BufferDescription
            {
                BindFlags           = D3D.BindFlags.None,
                CpuAccessFlags      = D3DCPUAccessFlags,
                OptionFlags         = D3D.ResourceOptionFlags.None,
                SizeInBytes         = Settings.SizeInBytes,
                StructureByteStride = Settings.StructureSize,
                Usage = D3DUsage
            };

            // If this is a render target buffer, then ensure that we have a default resource.
            if ((IsRenderTarget) && (Settings.Usage != BufferUsage.Default))
            {
                throw new GorgonException(GorgonResult.CannotCreate, Resources.GORGFX_RENDERTARGET_NEED_DEFAULT);
            }

            // Set up the buffer.  If we're a staging buffer, then none of this stuff will
            // work because staging buffers can't be bound to the pipeline, so just skip it.
            if (Settings.Usage != BufferUsage.Staging)
            {
                switch (BufferType)
                {
                case BufferType.Constant:
                    desc.BindFlags = D3D.BindFlags.ConstantBuffer;
                    break;

                case BufferType.Index:
                    desc.BindFlags = D3D.BindFlags.IndexBuffer;
                    break;

                case BufferType.Vertex:
                    desc.BindFlags = D3D.BindFlags.VertexBuffer;
                    break;

                case BufferType.Structured:
                    if (!IsRenderTarget)
                    {
                        desc.OptionFlags = D3D.ResourceOptionFlags.BufferStructured;
                    }
                    break;
                }

                // Update binding modifiers.
                if (Settings.AllowShaderViews)
                {
                    desc.BindFlags |= D3D.BindFlags.ShaderResource;
                }

                if (Settings.AllowUnorderedAccessViews)
                {
                    desc.BindFlags |= D3D.BindFlags.UnorderedAccess;
                }

                if (!IsRenderTarget)
                {
                    if (Settings.AllowIndirectArguments)
                    {
                        desc.OptionFlags = D3D.ResourceOptionFlags.DrawIndirectArguments;
                    }
                }
                else
                {
                    desc.BindFlags |= D3D.BindFlags.RenderTarget;
                }

                if (Settings.IsOutput)
                {
                    desc.BindFlags |= D3D.BindFlags.StreamOutput;
                }

                if (Settings.AllowRawViews)
                {
                    desc.OptionFlags = D3D.ResourceOptionFlags.BufferAllowRawViews;
                }
            }

            // Create and initialize the buffer.
            if (data != null)
            {
                long position = data.Position;

                using (var dxStream = new DX.DataStream(data.BasePointer, data.Length - position, true, true))
                {
                    D3DResource = D3DBuffer = new D3D.Buffer(Graphics.D3DDevice, dxStream, desc);
                }
            }
            else
            {
                D3DResource = D3DBuffer = new D3D.Buffer(Graphics.D3DDevice, desc);
            }
        }
Ejemplo n.º 29
0
        public void SetVertexBuffer(Device device, Vector3[] vertices)
        {
            BufferDescription vertexBufferDesc = new BufferDescription()
            {
                SizeInBytes = Marshal.SizeOf(typeof(Vector3)) * vertices.Length,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.VertexBuffer
            };

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

            BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0);
        }
Ejemplo n.º 30
0
        // 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);
            }
        }