Example #1
0
        // Constructor
        public static void Initialize()
        {
            QuadVertex[] svQuad = new QuadVertex[4];
            svQuad[0].pos = new Vector4(-1.0f, 1.0f, 0.5f, 1.0f);
            svQuad[0].tex = new Vector2(0.0f, 0.0f);
            svQuad[1].pos = new Vector4(1.0f, 1.0f, 0.5f, 1.0f);
            svQuad[1].tex = new Vector2(1.0f, 0.0f);
            svQuad[2].pos = new Vector4(-1.0f, -1.0f, 0.5f, 1.0f);
            svQuad[2].tex = new Vector2(0.0f, 1.0f);
            svQuad[3].pos = new Vector4(1.0f, -1.0f, 0.5f, 1.0f);
            svQuad[3].tex = new Vector2(1.0f, 1.0f);

            DataStream s = new DataStream(4 * Marshal.SizeOf(typeof(QuadVertex)), true, true);

            s.WriteRange(svQuad);


            s.Position = 0;
            BufferDescription bufferDescription = new BufferDescription();

            bufferDescription.BindFlags      = BindFlags.VertexBuffer;
            bufferDescription.CpuAccessFlags = CpuAccessFlags.None;
            bufferDescription.OptionFlags    = ResourceOptionFlags.None;
            bufferDescription.SizeInBytes    = 4 * Marshal.SizeOf(typeof(QuadVertex));
            bufferDescription.Usage          = ResourceUsage.Default;

            quadVerts = new D3D10.Buffer(Game.Device, s, bufferDescription);
            s.Close();
        }
 private void POST(string url, string postData, string tokenName)
 {
     string token = GetToken(tokenName);
     Request = (HttpWebRequest)System.Net.WebRequest.Create(url);
     Request.Method = "POST";
     Request.KeepAlive = true;
     Request.CookieContainer = CookieContainer;
     postData = string.Format("{0}={1}&{2}", tokenName, token, postData);
     byte[] byteArray = Encoding.UTF8.GetBytes(postData);
     // Set the ContentType property of the WebRequest.
     Request.ContentType = "application/x-www-form-urlencoded";
     // Set the ContentLength property of the WebRequest.
     Request.ContentLength = byteArray.Length;
     // Get the request stream.
     DataStream = Request.GetRequestStream();
     // Write the data to the request stream.
     DataStream.Write(byteArray, 0, byteArray.Length);
     // Close the Stream object.
     DataStream.Close();
     Response = Request.GetResponse();
     // Get the stream containing content returned by the server.
     DataStream = Response.GetResponseStream();
     // Open the stream using a StreamReader for easy access.
     Reader = new StreamReader(DataStream);
     // Read the content.
     Page = Reader.ReadToEnd();
     // Clean up the streams.
     Reader.Close();
     DataStream.Close();
     Response.Close();
 }
Example #3
0
        private void CreateBatch(PositionTexCoordNormalVertex[] vertices, short[] indices, Renderer renderer)
        {
            Debug.Assert(vertices != null && indices != null);

            int vertexBufferSize = PositionTexCoordNormalVertex.SizeInBytes * vertices.Length;
            var verticesData     = new DataStream(vertexBufferSize, true, true);

            verticesData.WriteRange(vertices);
            verticesData.Seek(0, SeekOrigin.Begin);
            var vertexBuffer = new Buffer(renderer.Device, verticesData, vertexBufferSize, ResourceUsage.Default,
                                          BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None);

            verticesData.Close();

            int indexBufferSize = sizeof(short) * indices.Length;
            var indicesData     = new DataStream(indexBufferSize, true, true);

            indicesData.WriteRange(indices);
            indicesData.Seek(0, SeekOrigin.Begin);
            var indexBuffer = new Buffer(renderer.Device, indicesData, indexBufferSize, ResourceUsage.Default,
                                         BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None);

            indicesData.Close();

            // Create batch
            var vertexBufferBinding = new VertexBufferBinding(vertexBuffer, PositionTexCoordNormalVertex.SizeInBytes, 0);
            var inputLayout         = new InputLayout(renderer.Device, PositionTexCoordNormalVertex.InputElements,
                                                      effect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature);

            batch = new DrawIndexedBatch(renderer.Device, effect, new[] { vertexBufferBinding }, inputLayout, indexBuffer, Format.R16_UInt,
                                         indices.Length, 0, 0);
            batches.Add(batch);
        }
        private void CreateVertexBuffer()
        {
            _vertexCount = _xRes * _yRes;

            var vertexStream = new DataStream(_vertexCount * PointVertex.SizeOf, true, true);

            // store pixel coordinates in each vertex
            for (short y = 0; y < _yRes; y++)
            {
                for (short x = 0; x < _xRes; x++)
                {
                    var pt = new PointVertex(x, y);
                    vertexStream.Write(pt);
                }
            }
            vertexStream.Position = 0;

            // create vertex buffer
            _vertexBuffer = new Buffer(_dxDevice, vertexStream,
                                       _vertexCount * PointVertex.SizeOf, ResourceUsage.Immutable,
                                       BindFlags.VertexBuffer,
                                       CpuAccessFlags.None, ResourceOptionFlags.None);

            vertexStream.Close();
        }
Example #5
0
        /// <summary>
        /// Closes the stream. We used the close method to transfer
        /// the file via ftp.
        /// </summary>
        public void Close()
        {
            DataStream.WriteLine("]}");
            DataStream.Flush();
            DataStream.Close();

            // transfer the file to the sftp service
            if (!HasUsers)
            {
                Logger.Debug("No Users to update. Skipping sftp process.");
            }
            else
            {
                var host            = StreamConfig.Settings["host"];
                var username        = StreamConfig.Settings["username"];
                var password        = StreamConfig.Settings["password"];
                var destinationPath = StreamConfig.Settings["destinationPath"];

                SftpService.SendFile(FileName, host, username, password, destinationPath);
            }

            // clean up the temp file
            try
            {
                File.Delete(FileName);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw;
            }
        }
        private void CreateIndexBuffer()
        {
            _indexCount = (_xRes - 1) * (_yRes - 1) * 6;
            var indexStream = new DataStream(_indexCount * sizeof(uint), true, true);

            // create index buffer
            for (int y = 0; y < _yRes - 1; y++)
            {
                for (int x = 0; x < _xRes - 1; x++)
                {
                    // first triangle
                    indexStream.Write(y * _xRes + x);
                    indexStream.Write((y + 1) * _xRes + x);
                    indexStream.Write(y * _xRes + x + 1);

                    // second triangle
                    indexStream.Write((y + 1) * _xRes + x);
                    indexStream.Write((y + 1) * _xRes + x + 1);
                    indexStream.Write(y * _xRes + x + 1);
                }
            }

            indexStream.Position = 0;

            _indexBuffer = new Buffer(_dxDevice, indexStream, _indexCount * sizeof(uint), ResourceUsage.Immutable,
                                      BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None);

            indexStream.Close();
        }
Example #7
0
        private void ExportFileEventHandler(ControllerContext context)
        {
            try
            {
                if (this.DataStream != null)
                {
                    context.HttpContext.Response.Clear();
                    // Econding
                    context.HttpContext.Response.ContentEncoding = Encoding.UTF8;
                    // Set ContentType
                    //context.HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    context.HttpContext.Response.ContentType = "application/octet-stream";
                    // Output File Name
                    var browser        = context.HttpContext.Request.Browser.Browser;
                    var exportFileName = browser.Equals("Firefox", StringComparison.OrdinalIgnoreCase) ? this.FileName : HttpUtility.UrlEncode(this.FileName, Encoding.UTF8);
                    context.HttpContext.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", exportFileName));

                    DataStream.Position = 0;
                    DataStream.WriteTo(context.HttpContext.Response.OutputStream);
                    DataStream.Close();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #8
0
        private static Texture2D CreateTex2DFromBitmap(Device device, BitmapSource bsource)
        {
            Texture2DDescription desc;

            desc.Width                     = bsource.Size.Width;
            desc.Height                    = bsource.Size.Height;
            desc.ArraySize                 = 1;
            desc.BindFlags                 = BindFlags.ShaderResource;
            desc.Usage                     = ResourceUsage.Default;
            desc.CpuAccessFlags            = CpuAccessFlags.None;
            desc.Format                    = Format.R8G8B8A8_UNorm;
            desc.MipLevels                 = 1;
            desc.OptionFlags               = ResourceOptionFlags.None;
            desc.SampleDescription.Count   = 1;
            desc.SampleDescription.Quality = 0;

            var s = new DataStream(bsource.Size.Height * bsource.Size.Width * 4, true, true);

            bsource.CopyPixels(bsource.Size.Width * 4, s);

            var rect = new DataRectangle(s.DataPointer, bsource.Size.Width * 4);

            var t2D = new Texture2D(device, desc, rect);

            s.Close();
            bsource.Dispose();

            return(t2D);
        }
Example #9
0
 public void Dispose()
 {
     m_MapIndex?.Close();
     m_MapStream?.Close();
     DataStream?.Close();
     m_IndexReader?.Close();
 }
Example #10
0
        public bool ParseScreen(Board board, out List <Block> nonZeroValues)
        {
            Surface       surface = dx.CaptureScreen();
            DataRectangle dr      = surface.LockRectangle(LockFlags.None);
            DataStream    gs      = dr.Data;

            nonZeroValues = new List <Block>();
            bool initialBoard = true;

            if (xoffset == 0 || yoffset == 0)
            {
                setOffset(gs);
            }

            byte[] buffer = new byte[blockWidth * 4 * blockHeight];
            PixelColor[,] pixels = new PixelColor[blockWidth, blockHeight];
            for (int i = 0; i < board.Width; i++)
            {
                for (int j = 0; j < board.Height; j++)
                {
                    for (int k = 0; k < blockHeight; k++)
                    {
                        gs.Position = (k + GetYCoord(j)) * screenWidth * 4 + GetXCoord(i) * 4;
                        gs.Read(buffer, blockWidth * 4 * k, blockWidth * 4);
                    }
                    for (int a = 0; a < blockWidth; a++)
                    {
                        for (int b = 0; b < blockHeight; b++)
                        {
                            int offset = b * blockWidth * 4 + (a * 4);
                            pixels[b, a].Red   = buffer[offset + 2];
                            pixels[b, a].Green = buffer[offset + 1];
                            pixels[b, a].Blue  = buffer[offset + 0];
                        }
                    }
                    board.Grid[i, j] = blockParser.Parse(i, j, pixels);

                    if (board.Grid[i, j].State == BlockState.ParseFailed)
                    {
                        throw new ParserException("Point [" + i + ", " + j + "] failed! Pixel [" + GetXCoord(i) + "," + GetYCoord(j) + "]");
                    }
                    if (board.Grid[i, j].Value > 0)
                    {
                        nonZeroValues.Add(board.Grid[i, j]);
                    }

                    if (board.Grid[i, j].State != BlockState.Unknown)
                    {
                        initialBoard = false;
                    }
                }
            }

            gs.Close();
            surface.UnlockRectangle();
            surface.Dispose();

            return(initialBoard);
        }
Example #11
0
 public void Dispose()
 {
     DataStream?.Close();
     DataStream?.Dispose();
     ControlStream?.Close();
     ControlStream?.Dispose();
     IsAlive = false;
 }
Example #12
0
        public void SetBufferData(DataStream stream)
        {
            var     context = GraphicsCore.D3D11ImmediateContext;
            DataBox box     = new DataBox(0, 0, stream);

            context.UpdateSubresource(box, buffer_, 0);
            stream.Close();
        }
Example #13
0
        public void SetBufferData(IntPtr data, int size)
        {
            var        context = GraphicsCore.D3D11ImmediateContext;
            DataStream stream  = new DataStream(data, size, true, false);
            DataBox    box     = new DataBox(0, 0, stream);

            context.UpdateSubresource(box, buffer_, 0);
            stream.Close();
        }
Example #14
0
        /// <summary>
        /// 矩形を追加する
        /// </summary>
        /// <param name="rect"></param>
        public void AddRect(ref Rect rect)
        {
            vertexNum_ = 6;

            // バッファデータ
            if ((vertexAttr_ & (uint)Shader.VertexAttr.TEXCOORD0) != 0)
            {
                // UV付き
                int vertex_stride = 20;
                int data_size     = vertex_stride * vertexNum_;
                var vtx_ary       = new[] {
                    new { p = rect.leftTop, uv = new Vector2(0, 0) },
                    new { p = rect.rightBottom, uv = new Vector2(1, 1) },
                    new { p = new Vector3(rect.rightBottom.X, rect.leftTop.Y, rect.leftTop.Z), uv = new Vector2(1, 0) },
                    new { p = rect.leftTop, uv = new Vector2(0, 0) },
                    new { p = new Vector3(rect.leftTop.X, rect.rightBottom.Y, rect.leftTop.Z), uv = new Vector2(0, 1) },
                    new { p = rect.rightBottom, uv = new Vector2(1, 1) },
                };
                var vertices = new DataStream(data_size, true, true);
                foreach (var a in vtx_ary)
                {
                    vertices.Write(a.p);
                    vertices.Write(a.uv);
                }
                vertices.Position = 0;

                // 頂点バッファ生成
                VertexBuffer.BufferDesc desc = new VertexBuffer.BufferDesc()
                {
                    data = vertices, data_size = data_size, stride = vertex_stride
                };
                vertexBuffer_ = new VertexBuffer(desc);
                vertices.Close();
            }
            else
            {
                // positionのみ
                int vertex_stride = 12;
                int data_size     = vertex_stride * vertexNum_;
                var vertices      = new DataStream(data_size, true, true);
                vertices.Write(rect.leftTop);
                vertices.Write(rect.rightBottom);
                vertices.Write(new Vector3(rect.rightBottom.X, rect.leftTop.Y, rect.leftTop.Z));
                vertices.Write(rect.leftTop);
                vertices.Write(new Vector3(rect.leftTop.X, rect.rightBottom.Y, rect.leftTop.Z));
                vertices.Write(rect.rightBottom);
                vertices.Position = 0;

                // 頂点バッファ生成
                VertexBuffer.BufferDesc desc = new VertexBuffer.BufferDesc()
                {
                    data = vertices, data_size = data_size, stride = vertex_stride
                };
                vertexBuffer_ = new VertexBuffer(desc);
                vertices.Close();
            }
        }
Example #15
0
 private void CloseCurrentBuffer()
 {
     if (rippleWriteOpen)
     {
         rippleWriteBuffer.Close();
         ImmediateContext.UnmapSubresource(_waveSwapChain.CurrentBuffer, 0);
     }
     rippleWriteOpen = false;
 }
Example #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="desc"></param>
        public void Initialize(BufferDesc desc)
        {
            var device = GraphicsCore.D3D11Device;

            stride_ = desc.stride;

            BindFlags flags = BindFlags.ShaderResource;

            if (desc.bindUAV)
            {
                flags |= BindFlags.UnorderedAccess;
            }

            BufferDescription bufDesc = new BufferDescription {
                SizeInBytes         = desc.size,
                StructureByteStride = desc.stride,
                BindFlags           = flags,
                OptionFlags         = ResourceOptionFlags.StructuredBuffer,
                Usage          = ResourceUsage.Default,
                CpuAccessFlags = CpuAccessFlags.None,
            };

            // 初期化データ
            if (desc.initData != null)
            {
                DataStream stream = new DataStream(desc.initData, true, false);
                buffer_ = new D3D11Buffer(device, stream, bufDesc);
                stream.Close();
            }
            else
            {
                buffer_ = new D3D11Buffer(device, bufDesc);
            }

            // SRV
            ShaderResourceViewDescription srvViewDesc = new ShaderResourceViewDescription {
                Format       = Format.Unknown,
                Dimension    = ShaderResourceViewDimension.Buffer,
                ElementWidth = desc.size / desc.stride,
            };

            shaderResourceView_ = new ShaderResourceView(device, buffer_, srvViewDesc);

            if (desc.bindUAV)
            {
                UnorderedAccessViewDescription uavDesc = new UnorderedAccessViewDescription {
                    Dimension    = UnorderedAccessViewDimension.Buffer,
                    ElementCount = desc.size / desc.stride,
                    Flags        = UnorderedAccessViewBufferFlags.None,
                    Format       = Format.Unknown,
                };
                unorderedAccessView_ = new UnorderedAccessView(device, buffer_, uavDesc);
            }
        }
Example #17
0
        static void SetUniformParams(ref Matrix worldMatrix)
        {
            uint flag = activeShader_.CBufferBindFlag;

            if ((flag & (uint)Shader.SystemCBufferFlag.TRANSFORM) != 0)
            {
                var     cbTrans = Shader.ConstantBufferDictionary["CB_Transform"];
                Camera  camera  = GraphicsCore.CurrentDrawCamera;
                dynamic cb      = cbTrans.inst_;

                // 行列キャッシュ
                if (worldMatrixCache_ != worldMatrix || viewMatrixCache_ != camera.ViewMatrix)
                {
                    // やっぱりコピーの無駄が多すぎる…ちょっと自前の実装考えたほうがいいかも…
                    Matrix mv = Matrix.Multiply(worldMatrix, camera.ViewMatrix);
                    cb.c_model_matrix      = Matrix.Transpose(worldMatrix);
                    cb.c_model_view_matrix = Matrix.Transpose(Matrix.Multiply(worldMatrix, camera.ViewMatrix));
                    mv = Matrix.Multiply(worldMatrix, camera.ViewMatrix);
                    cb.c_normal_matrix       = Matrix.Invert(mv);
                    cb.c_world_normal_matrix = Matrix.Invert(worldMatrix);

                    // キャッシュ
                    worldMatrixCache_ = worldMatrix;
                    viewMatrixCache_  = camera.ViewMatrix;
                }

                // TODO:カメラによるキャッシュ
                cb.c_view_matrix            = Matrix.Transpose(camera.ViewMatrix);
                cb.c_proj_matrix            = Matrix.Transpose(camera.ProjectionMatrix);
                cb.c_viewSpaceLightPosition = GraphicsCore.ViewSpaceLightPos;
                cb.c_worldSpaceViewPosition = new Vector4(camera.Position, 1);

                DataStream s   = new DataStream(cbTrans.inst_.Buffer, true, true);
                DataBox    box = new DataBox(0, 0, s);
                GraphicsCore.D3D11ImmediateContext.UpdateSubresource(box, cbTrans.buffer_, 0);
                s.Close();
            }


            // ユーザー定義バッファを更新
            var enumulate = activeShader_.ConstantBufferObjects.Where(o => (!o.isSystem_ && o.updateFunc_ != null));

            foreach (var o in enumulate)
            {
                if (o.updateFunc_(activeShader_, o.inst_))
                {
                    byte[]     data = o.inst_.Buffer;
                    DataStream s    = new DataStream(data, true, true);
                    DataBox    box  = new DataBox(0, 0, s);
                    GraphicsCore.D3D11ImmediateContext.UpdateSubresource(box, o.buffer_, 0);
                    s.Close();
                }
            }
        }
Example #18
0
File: Mesh.cs Project: allvie/IS16
        public Mesh(ICollection <Vertex> vertices, ICollection <short> indices)
        {
            DataStream outStream      = new DataStream(vertices.Count * Marshal.SizeOf(typeof(Vertex)), true, true);
            DataStream outStreamIndex = new DataStream(indices.Count * Marshal.SizeOf(typeof(short)), true, true);

            indexcount = indices.Count;

            foreach (Vertex v in vertices)
            {
                outStream.Write(v);
            }

            foreach (short i in indices)
            {
                outStreamIndex.Write(i);
            }

            outStream.Position      = 0;
            outStreamIndex.Position = 0;

            BufferDescription bufferDescription = new BufferDescription
            {
                BindFlags      = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,
                SizeInBytes    = vertices.Count * Marshal.SizeOf(typeof(Vertex)),
                Usage          = ResourceUsage.Immutable
            };

            BufferDescription bufferDescriptionIndex = new BufferDescription
            {
                BindFlags      = BindFlags.IndexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,
                SizeInBytes    = indices.Count * Marshal.SizeOf(typeof(short)),
                Usage          = ResourceUsage.Immutable
            };

            try // just in case were shutting down the application, dont die here.
            {
                vertexBuffer = new DX11.Buffer(RenderFrame.Instance.device, outStream, bufferDescription);
                indexBuffer  = new DX11.Buffer(RenderFrame.Instance.device, outStreamIndex, bufferDescriptionIndex);
                binding      = new VertexBufferBinding(vertexBuffer, Marshal.SizeOf(typeof(Vertex)), 0);
            }
            catch (ObjectDisposedException)
            {
            }

            outStream.Close();
            outStreamIndex.Close();
            outStream.Dispose();
            outStreamIndex.Dispose();
        }
 public void Destroy()
 {
     vertices.Close();
     vertexBuffer.Dispose();
     layout.Dispose();
     inputSignature.Dispose();
     vertexShader.Dispose();
     pixelShader.Dispose();
     renderTarget.Dispose();
     swapChain.Dispose();
     device.Dispose();
 }
Example #20
0
        public void Dispose()
        {
            Disposed = true;
            if (_streamCreated && DataStream != null)
            {
                DataStream.Close();
                DataStream.Dispose();
            }
            DataStream = null;

            // raise the events!
            OnDisposed();
        }
Example #21
0
        /////////////////////////////////////////////////////////////////////////////////
        // CONSTRUCTOR & DESTRUCTOR

        /// <summary>
        /// TODO doc
        /// </summary>
        /// <param name="origin"></param>
        /// <param name="span"></param>
        /// <param name="device"></param>
        /// <param name="context"></param>
        /// <param name="vertexShader"></param>
        /// <param name="vsSignature"></param>
        /// <param name="pixelShader"></param>
        /// <param name="resourceProviders"></param>
        public Rectangle(
            Vector2 origin,
            Vector2 span,
            EntityDescription desc)
            : base(desc)
        {
            // create rect vertices
            int vertexLength  = Vector3.SizeInBytes;    // should be 12:    3 * 4 bytes
            int uvCoordLength = Vector2.SizeInBytes;    // should be 8:     2 * 4 bytes

            DataStream data = new DataStream((vertexLength + uvCoordLength) * 4, true, true);

            origin.X = origin.X * 2 - 1;
            origin.Y = 1 - origin.Y * 2;

            float originPlusSpanX = origin.X + span.X * 2;
            float originPlusSpanY = origin.Y - span.Y * 2;

            // write 4 times: position vector & uv-coord vector ...
            data.Write(new Vector3(origin.X, origin.Y, 0));                             // vertex
            data.Write(new Vector2(0, 0));                                              // UV coord
            data.Write(new Vector3(originPlusSpanX, origin.Y, 0));                      // vertex
            data.Write(new Vector2(1, 0));                                              // UV coord
            data.Write(new Vector3(origin.X, originPlusSpanY, 0));                      // ...
            data.Write(new Vector2(0, 1));
            data.Write(new Vector3(originPlusSpanX, originPlusSpanY, 0));
            data.Write(new Vector2(1, 1));
            data.Position = 0;


            // create the vertex layout and buffer
            var elements = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                                   new InputElement("TEXTCOORD", 0, Format.R32G32_Float, vertexLength, 0) };

            InputLayout = new InputLayout(Device, VertexShaderSignature, elements);


            VertexBuffer = new D3DBuffer(Device,
                                         data,
                                         (int)data.Length,
                                         ResourceUsage.Default,
                                         BindFlags.VertexBuffer,
                                         CpuAccessFlags.None,
                                         ResourceOptionFlags.None,
                                         0);

            VertexBufferBinding = new VertexBufferBinding(VertexBuffer, vertexLength + uvCoordLength, 0);

            data.Close();
            data.Dispose();
        }
        private void BuildRandomTexture()
        {
            //
            // Create the random data.
            //
            var rand         = new Random();
            var randomValues = new Vector4[1024];

            for (int i = 0; i < 1024; ++i)
            {
                randomValues[i] = new Vector4(rand.RandF(-1.0f, 1.0f),
                                              rand.RandF(-1.0f, 1.0f),
                                              rand.RandF(-1.0f, 1.0f),
                                              rand.RandF(-1.0f, 1.0f));
            }

            //
            // Create the texture.
            //
            var texDesc = new Texture1DDescription
            {
                Width          = 1024,
                MipLevels      = 1,
                Format         = Format.R32G32B32A32_Float,
                Usage          = ResourceUsage.Immutable,
                BindFlags      = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,
                ArraySize      = 1
            };

            var ds        = new DataStream(randomValues, true, false);
            var randomTex = new Texture1D(_dxDevice, texDesc, ds);

            ds.Close();

            //
            // Create the resource view.
            //
            var viewDesc = new ShaderResourceViewDescription
            {
                Format          = texDesc.Format,
                Dimension       = ShaderResourceViewDimension.Texture1D,
                MipLevels       = texDesc.MipLevels,
                MostDetailedMip = 0
            };

            _randomTexRV = new ShaderResourceView(_dxDevice, randomTex, viewDesc);

            randomTex.Dispose();
        }
Example #23
0
        public void Dispose()
        {
            if (m_MapIndex != null)
            {
                m_MapIndex.Close();
            }
            else
            {
                MapStream?.Close();
            }

            DataStream?.Close();

            IndexReader?.Close();
        }
Example #24
0
        public string MakeRequest()
        {
            string         StrResponseValue = string.Empty;
            HttpWebRequest Request          = (HttpWebRequest)WebRequest.Create(Url);
            Stream         DataStream;
            WebResponse    Response = null;

            Request.Method = Method.ToString();

            try {
                if (Method == MethodType.POST || Method == MethodType.PUT)
                {
                    byte[] byteArray   = Encoding.UTF8.GetBytes(Payload);
                    string ContentType = "application/json";
                    Request.ContentType   = ContentType;
                    Request.MediaType     = ContentType;
                    Request.Accept        = ContentType;
                    Request.ContentLength = byteArray.Length;
                    DataStream            = Request.GetRequestStream();
                    DataStream.Write(byteArray, 0, byteArray.Length);
                    DataStream.Close();
                }
            } catch (Exception ex) {
                StrResponseValue = "{\"errorMessages\":[\"" + ex.Message.ToString() + "\"]}";
            }

            try {
                Response = Request.GetResponse();
                //Console.WriteLine(((HttpWebResponse)Response).StatusDescription);
                DataStream = Response.GetResponseStream();
                StreamReader reader = new StreamReader(DataStream);
                StrResponseValue = reader.ReadToEnd();
                //Console.WriteLine(StrResponseValue);
                reader.Close();
                DataStream.Close();
                Response.Close();
            }
            catch (Exception ex) {
                StrResponseValue = "{\"errorMessages\":[\"" + ex.Message.ToString() + "\"]}";
            }
            finally { if (Response != null)
                      {
                          ((IDisposable)Response).Dispose();
                      }
            }

            return(StrResponseValue);
        }
Example #25
0
 public void Close()
 {
     ByteStreamLogic = null;
     if (DataStream != null)
     {
         try
         {
             DataStream.Close();
             DataStream.Dispose();
         }
         catch (Exception)
         {
         }
         DataStream = null;
     }
     //Bytes = null;
 }
 private void GET(string url)
 {
     Request = (HttpWebRequest)System.Net.WebRequest.Create(url);
     Request.Method = "GET";
     Request.CookieContainer = CookieContainer;
     Response = Request.GetResponse();
     // Get the stream containing content returned by the server.
     DataStream = Response.GetResponseStream();
     // Open the stream using a StreamReader for easy access.
     Reader = new StreamReader(DataStream);
     // Read the content.
     Page = Reader.ReadToEnd();
     // Clean up the streams.
     Reader.Close();
     DataStream.Close();
     Response.Close();
 }
Example #27
0
        private static void WriteLevelDifferences()
        {
            DataStream s = new DataStream();

            s.WriteS32(LevelDifferences.Count);
            for (int i = 0; i < LevelDifferences.Count; i++)
            {
                var value = LevelDifferences[i];
                s.WriteS32(value.Difference);
                s.WriteS32(value.ProgressFactor);
                s.WriteS32(value.QualityFactor);
            }

            File.WriteAllBytes("LevelDifferences.db", s.GetBytes());
            s.Flush();
            s.Close();
        }
Example #28
0
        public static void ReadLevelDifferences(bool deleteCurrent = false)
        {
            if (deleteCurrent && File.Exists("LevelDifferences.db"))
            {
                File.Delete("LevelDifferences.db");
            }

            if (File.Exists("LevelDifferences.db"))
            {
                DataStream s      = new DataStream(File.ReadAllBytes("LevelDifferences.db"));
                int        length = s.ReadS32();
                LevelDifferences = new List <LevelDifferenceInfo>(length);
                for (ushort i = 0; i < length; i++)
                {
                    LevelDifferenceInfo info = new LevelDifferenceInfo
                    {
                        Difference     = s.ReadS32(),
                        ProgressFactor = s.ReadS32(),
                        QualityFactor  = s.ReadS32()
                    };
                    LevelDifferences.Add(info);
                }
                s.Flush();
                s.Close();
            }
            else
            {
                var   sheet = Game.GameData.GetSheet <CraftLevelDifference>();
                int   count = sheet.Count();
                int[] keys  = sheet.Keys.ToArray();
                LevelDifferences = new List <LevelDifferenceInfo>(count);
                for (int i = 0; i < count; i++)
                {
                    var value = sheet[keys[i]];
                    LevelDifferenceInfo info = new LevelDifferenceInfo
                    {
                        Difference     = (short)value.Difference,
                        ProgressFactor = (short)value.ProgressFactor,
                        QualityFactor  = (short)value.QualityFactor
                    };

                    LevelDifferences.Add(info);
                }
                WriteLevelDifferences();
            }
        }
Example #29
0
        static private void GenerateMoon()
        {
            QuadVertex3[] svQuad = new QuadVertex3[4];
            svQuad[0].pos = new Vector3(1, -1, 0);
            svQuad[0].tex = new Vector2(1, 1);
            svQuad[1].pos = new Vector3(-1, -1, 0);
            svQuad[1].tex = new Vector2(0, 1);
            svQuad[2].pos = new Vector3(-1, 1, 0);
            svQuad[2].tex = new Vector2(0, 0);
            svQuad[3].pos = new Vector3(1, 1, 0);
            svQuad[3].tex = new Vector2(1, 0);

            DataStream s = new DataStream(4 * Marshal.SizeOf(typeof(QuadVertex3)), true, true);

            s.WriteRange(svQuad);

            s.Position = 0;
            BufferDescription bufferDescription = new BufferDescription();

            bufferDescription.BindFlags      = BindFlags.VertexBuffer;
            bufferDescription.CpuAccessFlags = CpuAccessFlags.None;
            bufferDescription.OptionFlags    = ResourceOptionFlags.None;
            bufferDescription.SizeInBytes    = 4 * Marshal.SizeOf(typeof(QuadVertex3));
            bufferDescription.Usage          = ResourceUsage.Default;

            moonVerts = new D3D10.Buffer(Game.Device, s, bufferDescription);
            s.Close();

            short[] quadIb = new short[] { 0, 1, 2, 2, 3, 0 };
            s = new DataStream(6 * Marshal.SizeOf(typeof(short)), true, true);
            s.WriteRange(quadIb);

            s.Position                       = 0;
            bufferDescription                = new BufferDescription();
            bufferDescription.BindFlags      = BindFlags.IndexBuffer;
            bufferDescription.CpuAccessFlags = CpuAccessFlags.None;
            bufferDescription.OptionFlags    = ResourceOptionFlags.None;
            bufferDescription.SizeInBytes    = 6 * Marshal.SizeOf(typeof(short));
            bufferDescription.Usage          = ResourceUsage.Default;

            moonIndices = new D3D10.Buffer(Game.Device, s, bufferDescription);
            s.Close();
        }
Example #30
0
    /// <summary>
    /// Gets the specified region (identified in client coordinates) from the current surface
    /// </summary>
    /// <param name="region">The region (in client coordinates, e.g. <see cref="NativeMethods.GetClientRect"/> is the entire window content).</param>
    /// <returns>A new Bitmap object (must be Disposed by caller)</returns>
    public Bitmap GetSurfaceRegion(Rectangle region)
    {
        if (_captureHwnd == IntPtr.Zero)
        {
            return(null);
        }

        #region Create a copy of the surface image

        NativeMethods.UpdateWindowShared(_captureHwnd, 0, 0, 0, IntPtr.Zero, IntPtr.Zero);
        Surface.FromSurface(_renderTarget, _sharedSurface, Filter.None, 0);

        _deviceEx.GetRenderTargetData(_renderTarget, _systemMemorySurface);

        #endregion

        #region Put the data into a Bitmap

        // Note: during my tests I found that the captured area includes space for the window chrome
        //       but filled in black.

        // Take into consideration the window chrome
        Size chrome = NativeMethods.GetWindowChromeSize(_captureHwnd);
        region.X += chrome.Width;
        region.Y += chrome.Height;

        // We need to convert Width and Height to x2, and y2 respectively, because
        // Surface.ToStream(...) expects the rectangle to have x1,y1,x2,y2 not x1,y1,width,height
        // (SlimDX version 2.0.6.40)
        region.Width  += region.X;
        region.Height += region.Y;
        DataStream stream = Surface.ToStream(_systemMemorySurface, ImageFileFormat.Bmp, region);

        Bitmap surfaceBitmap = (Bitmap)Image.FromStream(stream);

        stream.Close();
        stream.Dispose();

        #endregion

        return(surfaceBitmap);
    }
Example #31
0
        public static void Create()
        {
            //without texcoord
            DataStream stream = new DataStream(12 * 6, true, true);
            stream.Write<Vector3>(new Vector3(-1, -1, 1));
            stream.Write<Vector3>(new Vector3(-1, 1, 1));
            stream.Write<Vector3>(new Vector3(1, 1, 1));
            stream.Write<Vector3>(new Vector3(1, 1, 1));
            stream.Write<Vector3>(new Vector3(1, -1, 1));
            stream.Write<Vector3>(new Vector3(-1, -1, 1));
            elements[0] = new SlimDX.Direct3D10.InputElement("POSITION", 0, SlimDX.DXGI.Format.R32G32B32_Float, 0, 0);
            stream.Position = 0;
            buffer = new SlimDX.Direct3D10.Buffer(Game.gameClass.GetDevice(), stream, (int)stream.Length, D3D10.ResourceUsage.Immutable,
                D3D10.BindFlags.VertexBuffer, D3D10.CpuAccessFlags.None, D3D10.ResourceOptionFlags.None);
            binding = new SlimDX.Direct3D10.VertexBufferBinding(buffer, 12, 0);
            stream.Close();

            //with texcoord
            stream = new DataStream(12 * 6*2, true, true);
            stream.Write<Vector3>(new Vector3(-1, -1, 1));
            stream.Write<Vector3>(Vector3.Zero);
            stream.Write<Vector3>(new Vector3(-1, 1, 1));
            stream.Write<Vector3>(Vector3.Zero);
            stream.Write<Vector3>(new Vector3(1, 1, 1));
            stream.Write<Vector3>(Vector3.Zero);
            stream.Write<Vector3>(new Vector3(1, 1, 1));
            stream.Write<Vector3>(Vector3.Zero);
            stream.Write<Vector3>(new Vector3(1, -1, 1));
            stream.Write<Vector3>(Vector3.Zero);
            stream.Write<Vector3>(new Vector3(-1, -1, 1));
            stream.Write<Vector3>(Vector3.Zero);

            elementsWithTexCoord[0] = new SlimDX.Direct3D10.InputElement("POSITION", 0, SlimDX.DXGI.Format.R32G32B32_Float, 0, 0);
            elementsWithTexCoord[1] = new SlimDX.Direct3D10.InputElement("TEXCOORD", 0, SlimDX.DXGI.Format.R32G32B32_Float, 12, 0);
            stream.Position = 0;
            bufferWithTexCoord = new SlimDX.Direct3D10.Buffer(Game.gameClass.GetDevice(), stream, (int)stream.Length, D3D10.ResourceUsage.Dynamic,
                D3D10.BindFlags.VertexBuffer, D3D10.CpuAccessFlags.Write, D3D10.ResourceOptionFlags.None);
            bindingWithTexCoord = new SlimDX.Direct3D10.VertexBufferBinding(bufferWithTexCoord, 24, 0);
            stream.Close();
        }
Example #32
0
        private void CreateVertexBuffer()
        {
            //create vertex buffer
                int size = 8 * quadSize * quadSize * 6; //end size of each quad will be quadSize+1
                DataStream stream = new DataStream(size, true, true);
                for (int i = 0; i < quadSize; i++)
                    for (int j = 0; j < quadSize; j++)
                    {
                        stream.Write(new Vector2(i, j));
                        stream.Write(new Vector2(i, j + 1));
                        stream.Write(new Vector2(i + 1, j + 1));

                        stream.Write(new Vector2(i + 1, j + 1));
                        stream.Write(new Vector2(i + 1, j));
                        stream.Write(new Vector2(i, j));
                    }
                stream.Position = 0;

                vertexBuffer = new SlimDX.Direct3D10.Buffer(Game.gameClass.GetDevice(), stream, size, SlimDX.Direct3D10.ResourceUsage.Immutable,
                    SlimDX.Direct3D10.BindFlags.VertexBuffer, SlimDX.Direct3D10.CpuAccessFlags.None, SlimDX.Direct3D10.ResourceOptionFlags.None);
                stream.Close();

            instances = new Vector4[(Globals.mapSize / quadSize) * (Globals.mapSize / quadSize)];
            vertexBufferBinding = new SlimDX.Direct3D10.VertexBufferBinding(vertexBuffer, sizeof(float) * 2, 0);
        }
Example #33
0
        static void BuildQuad()
        {
            ushort[] idx;
            TexturedVertex[] quad = CreateTexturedQuad(Vector3.Zero, size.Width, size.Height, out idx);

            // fill vertex and index buffers
            DataStream stream = new DataStream(4 * 24, true, true);
            stream.WriteRange(quad);
            stream.Position = 0;

            vertices = new SlimDX.Direct3D10.Buffer(device, stream, new BufferDescription()
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags =
                    ResourceOptionFlags.None,
                SizeInBytes = 4 * 24,
                Usage = ResourceUsage.Default
            });
            stream.Close();

            stream = new DataStream(6 * sizeof(ushort), true, true);
            stream.WriteRange(idx);
            stream.Position = 0;
            indices = new SlimDX.Direct3D10.Buffer(device, stream, new BufferDescription()
            {
                BindFlags = BindFlags.IndexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = 6 * sizeof(ushort),
                Usage = ResourceUsage.Default
            });
        }
Example #34
0
        private void CreateBatch(PositionTexCoordNormalVertex[] vertices, short[] indices, Renderer renderer)
        {
            Debug.Assert(vertices != null && indices != null);

            int vertexBufferSize = PositionTexCoordNormalVertex.SizeInBytes * vertices.Length;
            var verticesData = new DataStream(vertexBufferSize, true, true);
            verticesData.WriteRange(vertices);
            verticesData.Seek(0, SeekOrigin.Begin);
            var vertexBuffer = new Buffer(renderer.Device, verticesData, vertexBufferSize, ResourceUsage.Default,
                                          BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None);
            verticesData.Close();

            int indexBufferSize = sizeof(short) * indices.Length;
            var indicesData = new DataStream(indexBufferSize, true, true);
            indicesData.WriteRange(indices);
            indicesData.Seek(0, SeekOrigin.Begin);
            var indexBuffer = new Buffer(renderer.Device, indicesData, indexBufferSize, ResourceUsage.Default,
                                         BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None);
            indicesData.Close();

            // Create batch
            var vertexBufferBinding = new VertexBufferBinding(vertexBuffer, PositionTexCoordNormalVertex.SizeInBytes, 0);
            var inputLayout = new InputLayout(renderer.Device, PositionTexCoordNormalVertex.InputElements,
                                              effect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature);
            batch = new DrawIndexedBatch(renderer.Device, effect, new[] { vertexBufferBinding }, inputLayout, indexBuffer, Format.R16_UInt,
                                         indices.Length, 0, 0);
            batches.Add(batch);
        }
Example #35
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var form = new Form1();

            Device device;
            SwapChain swapChain;
            ShaderSignature inputSignature;
            VertexShader vertexShader;
            GeometryShader geometryShader;
            PixelShader pixelShader;

            var description = new SwapChainDescription()
            {
                BufferCount = 2,
                Usage = Usage.RenderTargetOutput,
                OutputHandle = form.Handle,
                IsWindowed = true,
                ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                Flags = SwapChainFlags.AllowModeSwitch,
                SwapEffect = SwapEffect.Discard
            };

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

            // create a view of our render target, which is the backbuffer of the swap chain we just created
            RenderTargetView renderTarget;
            using (var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0))
                renderTarget = new RenderTargetView(device, resource);

            // setting a viewport is required if you want to actually see anything
            var context = device.ImmediateContext;
            var viewport = new Viewport(0.0f, 0.0f, form.ClientSize.Width, form.ClientSize.Height);
            context.OutputMerger.SetTargets(renderTarget);
            context.Rasterizer.SetViewports(viewport);

            // load and compile the vertex shader
            using (var bytecode = ShaderBytecode.CompileFromFile("Voxel.fx", "VS", "vs_4_0", ShaderFlags.None, EffectFlags.None))
            {
                inputSignature = ShaderSignature.GetInputSignature(bytecode);
                vertexShader = new VertexShader(device, bytecode);
            }

            using (var bytecode = ShaderBytecode.CompileFromFile("Voxel.fx", "GS", "gs_4_0", ShaderFlags.None, EffectFlags.None))
            {
                geometryShader = new GeometryShader(device, bytecode);
            }

            // load and compile the pixel shader
            using (var bytecode = ShaderBytecode.CompileFromFile("Voxel.fx", "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None))
                pixelShader = new PixelShader(device, bytecode);

            // create test vertex data, making sure to rewind the stream afterward
            var vertices = new DataStream(12 * 3, true, true);
            vertices.Write(new Vector3(0.0f, 0.5f, 0.5f));
            vertices.Write(new Vector3(0.5f, -0.5f, 0.5f));
            vertices.Write(new Vector3(-0.5f, -0.5f, 0.5f));
            vertices.Position = 0;

            // create the vertex layout and buffer
            var elements = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0) };
            var layout = new InputLayout(device, inputSignature, elements);
            var vertexBuffer = new Buffer(device, vertices, 12 * 3, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            // configure the Input Assembler portion of the pipeline with the vertex data
            context.InputAssembler.InputLayout = layout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 12, 0));

            // set the shaders
            context.VertexShader.Set(vertexShader);
            // context.GeometryShader.Set(geometryShader);
            context.PixelShader.Set(pixelShader);

            // prevent DXGI handling of alt+enter, which doesn't work properly with Winforms
            using (var factory = swapChain.GetParent<Factory>())
                factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAltEnter);

            // handle alt+enter ourselves
            form.KeyDown += (o, e) =>
            {
                if (e.Alt && e.KeyCode == Keys.Enter)
                    swapChain.IsFullScreen = !swapChain.IsFullScreen;
            };

            // handle form size changes
            form.Resize += (o, e) =>
            {
                renderTarget.Dispose();

                swapChain.ResizeBuffers(2, 0, 0, Format.R8G8B8A8_UNorm, SwapChainFlags.AllowModeSwitch);
                using (var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0))
                    renderTarget = new RenderTargetView(device, resource);

                context.OutputMerger.SetTargets(renderTarget);
            };

            MessagePump.Run(form, () =>
            {
                // clear the render target to a soothing blue
                context.ClearRenderTargetView(renderTarget, new Color4(0.5f, 0.5f, 1.0f));

                // draw the triangle
                context.Draw(3, 0);
                swapChain.Present(0, PresentFlags.None);
            });

            // clean up all resources
            // anything we missed will show up in the debug output
            vertices.Close();
            vertexBuffer.Dispose();
            layout.Dispose();
            inputSignature.Dispose();
            vertexShader.Dispose();
            geometryShader.Dispose();
            pixelShader.Dispose();
            renderTarget.Dispose();
            swapChain.Dispose();
            device.Dispose();
        }
Example #36
0
        public void UpdateRectangles( IList< Image4ub > images, IList< Rect2i > targets )
        {
#if false
            var wrapper = D3D10Wrapper.Instance;

            var im = new Image4ub( this.Size, Color4ub.Red );
            fixed( void* ptr = im.Pixels )
            {
                var userBuffer = new IntPtr( ptr );
                var dataStream = new DataStream( userBuffer, 4 * im.NumPixels, true, true );
                var sourceBox = new DataBox( 4 * im.Width, 4 * im.Width * im.Height, dataStream );

                var targetRegion = new ResourceRegion
                {
                    Back = 1,
                    Front = 0,
                    Bottom = 4096,
                    Top = 0,
                    Left = 0,
                    Right = 4096
                };

                wrapper.Device.UpdateSubresource( sourceBox, Texture, 0, targetRegion );
                dataStream.Close();
            }

            return;
#endif
            if( images.Count != targets.Count )
            {
                throw new ArgumentException( "images and targets must be of the same length" );
            }

            var rect = Texture.Map( 0, MapMode.WriteDiscard, MapFlags.None );

            for( int i = 0; i < images.Count; ++i )
            {
                var im = images[ i ];
                var target = targets[ i ];

                for( int y = 0; y < im.Height; ++y )
                {
                    int sourceOffset = 4 * y * im.Width;
                    int sourceCount = 4 * im.Width;

                    rect.Data.Position = 4 * ( ( y + target.Origin.y ) * Width + target.Origin.x );
                    rect.Data.Write( im.Pixels, sourceOffset, sourceCount );
                }
            }

            rect.Data.Close();
            Texture.Unmap( 0 );
        }
        private void CreateVertexBuffer()
        {
            _vertexCount = _xRes*_yRes;

            var vertexStream = new DataStream(_vertexCount*PointVertex.SizeOf, true, true);

            // store pixel coordinates in each vertex
            for (short y = 0; y < _yRes; y++)
            {
                for (short x = 0; x < _xRes; x++)
                {
                    var pt = new PointVertex(x, y);
                    vertexStream.Write(pt);
                }
            }
            vertexStream.Position = 0;

            // create vertex buffer
            _vertexBuffer = new Buffer(_dxDevice, vertexStream,
                                       _vertexCount*PointVertex.SizeOf, ResourceUsage.Immutable,
                                       BindFlags.VertexBuffer,
                                       CpuAccessFlags.None, ResourceOptionFlags.None);

            vertexStream.Close();
        }
        private void SetRandomTex(int Seed)
        {
            // set the seed
            _Seed = Seed;

            // set the random size
            int RandNum_Size = 256;

            // set the description of the texture
            Texture1DDescription RandomTex_Desc = new Texture1DDescription();
            RandomTex_Desc.Format = Format.R8_UInt;
            RandomTex_Desc.CpuAccessFlags = CpuAccessFlags.None;
            RandomTex_Desc.Width = RandNum_Size * 2;
            RandomTex_Desc.Usage = ResourceUsage.Default;
            RandomTex_Desc.OptionFlags = ResourceOptionFlags.None;
            RandomTex_Desc.MipLevels = 1;
            RandomTex_Desc.BindFlags = BindFlags.ShaderResource;
            RandomTex_Desc.ArraySize = 1;

            // start the stream
            DataStream stream = new DataStream(RandNum_Size * 2, true, true);

            // Initialize the random generator
            Random generator = new Random(Seed);

            // allocate the random values
            byte[] RandNum_Host = new byte[RandNum_Size * 2];

            // Copy the source data twice to the generator array
            for (int i = 0; i < RandNum_Size; i++) {
                RandNum_Host[i] = (byte)generator.Next(256);
                RandNum_Host[i + RandNum_Size] = RandNum_Host[i];
            }

            // pass the randoms to the stream
            stream.WriteRange<byte>(RandNum_Host);
            stream.Position = 0;

            // create the texture and pass the data
            Texture1D RandomTex = new Texture1D(Engine.g_device, RandomTex_Desc, stream);

            // close the stream we don't need it any more
            stream.Close();

            // create the resource view to be able to pass it to the shader
            ShaderResourceView RandomResourceView = new ShaderResourceView(Engine.g_device, RandomTex);

            // set the Resource to the shader
            RandomTex_Variable.SetResource(RandomResourceView);
        }
        private void CreateIndexBuffer()
        {
            _indexCount = (_xRes - 1)*(_yRes - 1)*6;
            var indexStream = new DataStream(_indexCount* sizeof(uint), true, true);

            // create index buffer
            for (int y = 0; y < _yRes -1; y++)
            {
                for (int x = 0; x < _xRes -1; x++)
                {
                    // first triangle
                    indexStream.Write(y*_xRes + x);
                    indexStream.Write((y+1)*_xRes + x);
                    indexStream.Write(y * _xRes + x + 1);

                    // second triangle
                    indexStream.Write((y + 1)*_xRes + x);
                    indexStream.Write((y + 1)*_xRes + x + 1);
                    indexStream.Write(y * _xRes + x + 1);
                }
            }

            indexStream.Position = 0;

            _indexBuffer = new Buffer(_dxDevice, indexStream, _indexCount*sizeof (uint), ResourceUsage.Immutable,
                                      BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None);

            indexStream.Close();
        }
Example #40
0
        public static Buffer CreateScreenQuad(Device device)
        {
            var overlayVertices = new DataStream(VertexPositionTexture.SizeInBytes * 4, true, true);

            overlayVertices.Write(new VertexPositionTexture(new Vector3(-1, 1, 0), new Vector2(0, 0f)));
            overlayVertices.Write(new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(1, 0)));
            overlayVertices.Write(new VertexPositionTexture(new Vector3(-1, -1, 0), new Vector2(0, 1)));
            overlayVertices.Write(new VertexPositionTexture(new Vector3(1, -1, 0), new Vector2(1, 1)));

            // reset the vertex stream
            overlayVertices.Position = 0;

            // create the overlay vertex layout and buffer
            var vertexBufferOverlay = new Buffer(device, overlayVertices, (int)overlayVertices.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            overlayVertices.Close();

            return vertexBufferOverlay;

            //Buffer vertexBuffer;

            //// Top Left of screen is -1, +1
            //// Bottom Right of screen is +1, -1
            //var overlayVertices = new DataStream(VertexPositionTexture.SizeInBytes * 4, true, true);
            //overlayVertices.Write(new VertexPositionTexture(new Vector3(-1, 1, 0), new Vector2(0, 0f)));
            //overlayVertices.Write(new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(1, 0)));
            //overlayVertices.Write(new VertexPositionTexture(new Vector3(-1, -1, 0), new Vector2(0, 1)));
            //overlayVertices.Write(new VertexPositionTexture(new Vector3(1, -1, 0), new Vector2(1, 1)));

            //// reset the vertex stream
            //overlayVertices.Position = 0;

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

            //// create the overlay vertex layout and buffer
            //vertexBuffer = new Buffer(device, overlayVertices, vertexBufferDesc);
            //overlayVertices.Close();

            //using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true))
            //{
            //    data.Write(new VertexPositionTexture(new Vector3(-1, 1, 0), new Vector2(0, 0f)));
            //    data.Write(new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(1, 0)));
            //    data.Write(new VertexPositionTexture(new Vector3(-1, -1, 0), new Vector2(0, 1)));
            //    data.Write(new VertexPositionTexture(new Vector3(1, -1, 0), new Vector2(1, 1)));

            //    // reset the vertex stream
            //    //data.Position = 0;

            //    //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));
            //    vertexBuffer = new Buffer(device, data, vertexBufferDesc);

            //    //device.ImmediateContext.UnmapSubresource(vertexBuffer, 0);
            //}

            //return vertexBuffer;
        }
Example #41
0
        /// <summary>
        /// Create the mesh and stream it to the device
        /// </summary>
        public void CreateMesh()
        {
            Device dev = Engine.g_device;

            /// make a stream with the vertex to be able to insert it to the mesh
            DataStream stream = new DataStream(Marshal.SizeOf(typeof(Polygon)) * m_polygons.Count * 3, true, true);

            /// write the polygons to the stream
            stream.WriteRange<Polygon>(m_polygons.ToArray());

            /// reset the position in the stream
            stream.Position = 0;

            /// Fill the buffer with the vertices
            m_BufferVertices = new SharpDX.Direct3D11.Buffer(dev, stream, new BufferDescription() {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = (int)stream.Length,
                Usage = ResourceUsage.Default
            });

            // create the binder for the vertex
            m_VertexBufferBinding = new VertexBufferBinding(m_BufferVertices, 56 /* the size of the Vertex */ , 0);

            // close the stream
            stream.Close();

            /*
            /// make a stream with the Indices to be able to insert it to the mesh
            stream = new DataStream(sizeof(uint) * m_polygons.Count * 3, true, true);
            for (uint i = 0; i < m_polygons.Count * 3; i++)
                stream.Write<uint>(i);

            /// reset the position in the stream
            stream.Position = 0;

            m_BufferIndices = new SharpDX.Direct3D11.Buffer(dev, stream, new BufferDescription() {
                BindFlags = BindFlags.IndexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = (int)stream.Length,
                Usage = ResourceUsage.Default
            });

            // close the stream
            stream.Close();
            */

            // create the input layout
            m_input_layout = new InputLayout(
                Engine.g_device,
                m_shader.m_VertexShaderByteCode,
                m_layout);
        }
Example #42
0
        public Direct3D11Driver(Form form, Configuration config)
            : base(form, new SwapChainDescription()
			             {
				             IsWindowed = true,
				             BufferCount = 1,
				             SwapEffect = SwapEffect.Discard,
				             Usage = Usage.RenderTargetOutput,
				             Flags = SwapChainFlags.None,
				             SampleDescription = new SampleDescription(1, 0),
				             ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(), Format.R8G8B8A8_UNorm)
			             })
        {
            IsDisposed = false;

            try
            {
                _workerThread = new WorkerThread();
                _isBusy = new WaitableBool(false);

                _context = D3D11Device.ImmediateContext;
                _backBufferView = GetBackBufferView();
                _context.OutputMerger.SetTargets(_backBufferView);

                Viewport viewPort = new Viewport()
                {
                    X = 0,
                    Y = 0,
                    Width = form.ClientSize.Width,
                    Height = form.ClientSize.Height,
                    MinZ = 0.0F,
                    MaxZ = 1.0F
                };
                _context.Rasterizer.SetViewports(viewPort);

                _effectBytecode = ShaderBytecode.CompileFromFile("Effect.fx", " ", "fx_5_0", ShaderFlags.None, EffectFlags.None, null, null);
                _effect = new Effect(D3D11Device, _effectBytecode, EffectFlags.None);

                _technique = _effect.GetTechniqueByIndex(0);
                _pass = _technique.GetPassByIndex(0);

                InputElement[] elements = new InputElement[]
                {
                    new InputElement("POSITION", 0, Format.R32G32B32A32_Float,  0, 0),
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float,       16, 0)
                };
                _layout = new InputLayout(D3D11Device, _pass.Description.Signature, elements);

                DataStream stream = new DataStream(4 * Marshal.SizeOf(typeof(Vertex)), true, true);
                stream.Write(new Vector4(-1.0F, 1.0F, 0.5F, 1.0F));
                stream.Write(new Vector2(0.0F, 0.0F));
                stream.Write(new Vector4(1.0F, 1.0F, 0.5F, 1.0F));
                stream.Write(new Vector2(1.0F, 0.0F));
                stream.Write(new Vector4(-1.0F, -1.0F, 0.5F, 1.0F));
                stream.Write(new Vector2(0.0F, 1.0F));
                stream.Write(new Vector4(1.0F, -1.0F, 0.5F, 1.0F));
                stream.Write(new Vector2(1.0F, 1.0F));

                stream.Position = 0;

                _vertices = new Buffer(D3D11Device, stream, new BufferDescription()
                {
                    SizeInBytes = (int)stream.Length,
                    BindFlags = BindFlags.VertexBuffer,
                    Usage = ResourceUsage.Default,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None
                });
                stream.Close();

                _texture = new Texture2D(D3D11Device, new Texture2DDescription()
                {
                    Width = 512,
                    Height = 512,
                    Format = Format.R8G8B8A8_UNorm,
                    ArraySize = 1,
                    MipLevels = 1,
                    Usage = ResourceUsage.Dynamic,
                    CpuAccessFlags = CpuAccessFlags.Write,
                    BindFlags = BindFlags.ShaderResource,
                    SampleDescription = SwapChainDescription.SampleDescription
                });

                _textureView = new ShaderResourceView(D3D11Device, _texture);

                _effect.GetVariableByName("InputTexture").AsResource().SetResource(_textureView);
            }
            catch
            {
                Dispose();
                throw;
            }
        }
Example #43
0
        public RenderObject(Device device)
        {
            cb.vp = Matrix.Identity;
            cb.world = Matrix.Identity;

            // load and compile the vertex shader
            using (var bytecode = ShaderBytecode.CompileFromFile("simple.fx", "VShader", "vs_4_0", ShaderFlags.None, EffectFlags.None))
            {
                vsInputSignature = ShaderSignature.GetInputSignature(bytecode);
                vertexShader = new VertexShader(device, bytecode);
            }

            // load and compile the pixel shader
            using (var bytecode = ShaderBytecode.CompileFromFile("simple.fx", "PShader", "ps_4_0", ShaderFlags.None, EffectFlags.None))
                pixelShader = new PixelShader(device, bytecode);

            // Old school style.
            /*
            vertexSize = 24;
            vertexCount = 3;
            var vertexStream = new DataStream(vertexSize * vertexCount, true, true);
            vertexStream.Write(new Vector3(0.0f, 5.0f, 0.5f));
            vertexStream.Write(new Vector3(1, 0, 0)); // color
            vertexStream.Write(new Vector3(5.0f, -5.0f, 0.5f));
            vertexStream.Write(new Vector3(0, 1, 0)); // color
            vertexStream.Write(new Vector3(-5.0f, -5.0f, 0.5f));
            vertexStream.Write(new Vector3(0, 0, 1)); // color
            vertexStream.Position = 0;
            */

            // Use struct
            Vertex[] vertices = new Vertex[] {
                new Vertex() { pos = new Vector3(0.0f, 50.0f, 0.5f), col = new Vector3(1, 0, 0), uv = new Vector2(0, 0) },
                new Vertex() { pos = new Vector3(50.0f, -50.0f, 0.5f), col = new Vector3(1, 1, 0), uv = new Vector2(1, 0) },
                new Vertex() { pos = new Vector3(-50.0f, -50.0f, 0.5f), col = new Vector3(0, 1, 1), uv = new Vector2(1, 1) },
            };
            vertexSize = Marshal.SizeOf(typeof(Vertex));
            vertexCount = vertices.Length;
            var vertexStream = new DataStream(vertexSize * vertexCount, true, true);
            foreach (var vertex in vertices)
            {
                vertexStream.Write(vertex);
            }
            vertexStream.Position = 0;

            // create the vertex layout and buffer
            var elements = new[] {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0),
                new InputElement("COLOR", 0, Format.R32G32B32_Float, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 0)
            };
            vertexBufferLayout = new InputLayout(device, vsInputSignature, elements);
            vertexBuffer = new Buffer(device, vertexStream, vertexSize * vertexCount, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            vertexStream.Close();

            // Setup Constant Buffers
            constantBuffer = new Buffer(device, Marshal.SizeOf(typeof(ConstantBuffer)), ResourceUsage.Dynamic, BindFlags.ConstantBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0);

            // http://asc-chalmers-project.googlecode.com/svn-history/r26/trunk/Source/AdvGraphicsProject/Program.cs
            // Try load a texture
            SamplerDescription samplerDescription = new SamplerDescription();
            samplerDescription.AddressU = TextureAddressMode.Wrap;
            samplerDescription.AddressV = TextureAddressMode.Wrap;
            samplerDescription.AddressW = TextureAddressMode.Wrap;
            samplerDescription.Filter = Filter.MinPointMagMipLinear;
            samplerLinear = SamplerState.FromDescription(device, samplerDescription);

            texture = Texture2D.FromFile(device, "Data/cco.png");
            textureView = new ShaderResourceView(device, texture);

            var desc = new BlendStateDescription()
            {
                AlphaToCoverageEnable = true,
                IndependentBlendEnable = true
            };

            desc.RenderTargets[0].BlendEnable = false;
            desc.RenderTargets[0].BlendOperation = BlendOperation.Add;
            desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add;
            desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.Alpha;
            desc.RenderTargets[0].SourceBlend = BlendOption.SourceAlpha;
            desc.RenderTargets[0].DestinationBlend = BlendOption.InverseSourceAlpha;
            desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.InverseSourceAlpha;
            desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

            blendState = BlendState.FromDescription(device, desc);
        }
        public void Run()
        {
            var form = new RenderForm("2d and 3d combined...it's like magic");
            form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) form.Close(); };

            // DirectX DXGI 1.1 factory
            var factory1 = new Factory1();

            // The 1st graphics adapter
            var adapter1 = factory1.GetAdapter1(0);

            // ---------------------------------------------------------------------------------------------
            // Setup direct 3d version 11. It's context will be used to combine the two elements
            // ---------------------------------------------------------------------------------------------

            var description = new SwapChainDescription
                {
                    BufferCount = 1,
                    ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    IsWindowed = true,
                    OutputHandle = form.Handle,
                    SampleDescription = new SampleDescription(1, 0),
                    SwapEffect = SwapEffect.Discard,
                    Usage = Usage.RenderTargetOutput,
                    Flags = SwapChainFlags.AllowModeSwitch
                };

            Device11 device11;
            SwapChain swapChain;

            Device11.CreateWithSwapChain(adapter1, DeviceCreationFlags.None, description, out device11, out swapChain);

            // create a view of our render target, which is the backbuffer of the swap chain we just created
            RenderTargetView renderTargetView;
            using (var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0))
                renderTargetView = new RenderTargetView(device11, resource);

            // setting a viewport is required if you want to actually see anything
            var context = device11.ImmediateContext;

            var viewport = new Viewport(0.0f, 0.0f, form.ClientSize.Width, form.ClientSize.Height);
            context.OutputMerger.SetTargets(renderTargetView);
            context.Rasterizer.SetViewports(viewport);

            //
            // Create the DirectX11 texture2D. This texture will be shared with the DirectX10 device.
            //
            // The DirectX10 device will be used to render text onto this texture.
            // DirectX11 will then draw this texture (blended) onto the screen.
            // The KeyedMutex flag is required in order to share this resource between the two devices.
            var textureD3D11 = new Texture2D(device11, new Texture2DDescription
            {
                Width = form.ClientSize.Width,
                Height = form.ClientSize.Height,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.B8G8R8A8_UNorm,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.SharedKeyedmutex
            });

            // ---------------------------------------------------------------------------------------------
            // Setup a direct 3d version 10.1 adapter
            // ---------------------------------------------------------------------------------------------
            var device10 = new Device10(adapter1, SharpDX.Direct3D10.DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_0);

            // ---------------------------------------------------------------------------------------------
            // Setup Direct 2d
            // ---------------------------------------------------------------------------------------------

            // Direct2D Factory
            var factory2D = new SharpDX.Direct2D1.Factory(FactoryType.SingleThreaded, DebugLevel.Information);

            // Here we bind the texture we've created on our direct3d11 device through the direct3d10
            // to the direct 2d render target....
            var sharedResource = textureD3D11.QueryInterface<SharpDX.DXGI.Resource>();
            var textureD3D10 = device10.OpenSharedResource<SharpDX.Direct3D10.Texture2D>(sharedResource.SharedHandle);

            var surface = textureD3D10.AsSurface();
            var rtp = new RenderTargetProperties
                {
                    MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_10,
                    Type = RenderTargetType.Hardware,
                    PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)
                };

            var renderTarget2D = new RenderTarget(factory2D, surface, rtp);
            var solidColorBrush = new SolidColorBrush(renderTarget2D, Colors.Red);

            // ---------------------------------------------------------------------------------------------------
            // Setup the rendering data
            // ---------------------------------------------------------------------------------------------------

            // Load Effect. This includes both the vertex and pixel shaders.
            // Also can include more than one technique.
            ShaderBytecode shaderByteCode = ShaderBytecode.CompileFromFile(
                "effectDx11.fx",
                "fx_5_0",
                ShaderFlags.EnableStrictness);

            var effect = new Effect(device11, shaderByteCode);

            // create triangle vertex data, making sure to rewind the stream afterward
            var verticesTriangle = new DataStream(VertexPositionColor.SizeInBytes * 3, true, true);
            verticesTriangle.Write(new VertexPositionColor(new Vector3(0.0f, 0.5f, 0.5f),new Color4(1.0f, 0.0f, 0.0f, 1.0f)));
            verticesTriangle.Write(new VertexPositionColor(new Vector3(0.5f, -0.5f, 0.5f),new Color4(0.0f, 1.0f, 0.0f, 1.0f)));
            verticesTriangle.Write(new VertexPositionColor(new Vector3(-0.5f, -0.5f, 0.5f),new Color4(0.0f, 0.0f, 1.0f, 1.0f)));

            verticesTriangle.Position = 0;

            // create the triangle vertex layout and buffer
            var layoutColor = new InputLayout(device11, effect.GetTechniqueByName("Color").GetPassByIndex(0).Description.Signature, VertexPositionColor.inputElements);
            var vertexBufferColor = new Buffer(device11, verticesTriangle, (int)verticesTriangle.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            verticesTriangle.Close();

            // create overlay vertex data, making sure to rewind the stream afterward
            // Top Left of screen is -1, +1
            // Bottom Right of screen is +1, -1
            var verticesText = new DataStream(VertexPositionTexture.SizeInBytes * 4, true, true);
            verticesText.Write(new VertexPositionTexture(new Vector3(-1, 1, 0),new Vector2(0, 0f)));
            verticesText.Write(new VertexPositionTexture(new Vector3(1, 1, 0),new Vector2(1, 0)));
            verticesText.Write(new VertexPositionTexture(new Vector3(-1, -1, 0),new Vector2(0, 1)));
            verticesText.Write(new VertexPositionTexture(new Vector3(1, -1, 0),new Vector2(1, 1)));

            verticesText.Position = 0;

            // create the overlay vertex layout and buffer
            var layoutOverlay = new InputLayout(device11, effect.GetTechniqueByName("Overlay").GetPassByIndex(0).Description.Signature, VertexPositionTexture.inputElements);
            var vertexBufferOverlay = new Buffer(device11, verticesText, (int)verticesText.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            verticesText.Close();

            // Think of the shared textureD3D10 as an overlay.
            // The overlay needs to show the 2d content but let the underlying triangle (or whatever)
            // show thru, which is accomplished by blending.
            var bsd = new BlendStateDescription();
            bsd.RenderTarget[0].IsBlendEnabled = true;
            bsd.RenderTarget[0].SourceBlend = BlendOption.SourceColor;
            bsd.RenderTarget[0].DestinationBlend = BlendOption.BlendFactor;
            bsd.RenderTarget[0].BlendOperation = BlendOperation.Add;
            bsd.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
            bsd.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
            bsd.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
            bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

            var blendStateTransparent = new BlendState(device11, bsd);

            // ---------------------------------------------------------------------------------------------------
            // Create and tesselate an ellipse
            // ---------------------------------------------------------------------------------------------------
            var center = new DrawingPointF(form.ClientSize.Width/2.0f, form.ClientSize.Height/2.0f);
            var ellipse = new EllipseGeometry(factory2D, new Ellipse(center, form.ClientSize.Width / 2.0f, form.ClientSize.Height / 2.0f));

            // Populate a PathGeometry from Ellipse tessellation
            var tesselatedGeometry = new PathGeometry(factory2D);
            _geometrySink = tesselatedGeometry.Open();

            // Force RoundLineJoin otherwise the tesselated looks buggy at line joins
            _geometrySink.SetSegmentFlags(PathSegment.ForceRoundLineJoin);

            // Tesselate the ellipse to our TessellationSink
            ellipse.Tessellate(1, this);

            _geometrySink.Close();

            // ---------------------------------------------------------------------------------------------------
            // Acquire the mutexes. These are needed to assure the device in use has exclusive access to the surface
            // ---------------------------------------------------------------------------------------------------

            var device10Mutex = textureD3D10.QueryInterface<KeyedMutex>();
            var device11Mutex = textureD3D11.QueryInterface<KeyedMutex>();

            // ---------------------------------------------------------------------------------------------------
            // Main rendering loop
            // ---------------------------------------------------------------------------------------------------

            bool first = true;

            RenderLoop
                .Run(form,
                     () =>
                         {
                             if(first)
                             {
                                 form.Activate();
                                 first = false;
                             }

                             // clear the render target to black
                             context.ClearRenderTargetView(renderTargetView, Colors.DarkSlateGray);

                             // Draw the triangle
                             context.InputAssembler.InputLayout = layoutColor;
                             context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
                             context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferColor, VertexPositionColor.SizeInBytes, 0));
                             context.OutputMerger.BlendState = null;
                             var currentTechnique = effect.GetTechniqueByName("Color");
                             for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass)
                             {
                                 using (var effectPass = currentTechnique.GetPassByIndex(pass))
                                 {
                                     System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass");
                                     effectPass.Apply(context);
                                 }
                                 context.Draw(3, 0);
                             };

                             // Draw Ellipse on the shared Texture2D
                             device10Mutex.Acquire(0, 100);
                             renderTarget2D.BeginDraw();
                             renderTarget2D.Clear(Colors.Black);
                             renderTarget2D.DrawGeometry(tesselatedGeometry, solidColorBrush);
                             renderTarget2D.DrawEllipse(new Ellipse(center, 200, 200), solidColorBrush, 20, null);
                             renderTarget2D.EndDraw();
                             device10Mutex.Release(0);

                             // Draw the shared texture2D onto the screen, blending the 2d content in
                             device11Mutex.Acquire(0, 100);
                             var srv = new ShaderResourceView(device11, textureD3D11);
                             effect.GetVariableByName("g_Overlay").AsShaderResource().SetResource(srv);
                             context.InputAssembler.InputLayout = layoutOverlay;
                             context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
                             context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferOverlay, VertexPositionTexture.SizeInBytes, 0));
                             context.OutputMerger.BlendState = blendStateTransparent;
                             currentTechnique = effect.GetTechniqueByName("Overlay");

                             for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass)
                             {
                                 using (var effectPass = currentTechnique.GetPassByIndex(pass))
                                 {
                                     System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass");
                                     effectPass.Apply(context);
                                 }
                                 context.Draw(4, 0);
                             }
                             srv.Dispose();
                             device11Mutex.Release(0);

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

            // dispose everything
            vertexBufferColor.Dispose();
            vertexBufferOverlay.Dispose();
            layoutColor.Dispose();
            layoutOverlay.Dispose();
            effect.Dispose();
            shaderByteCode.Dispose();
            renderTarget2D.Dispose();
            swapChain.Dispose();
            device11.Dispose();
            device10.Dispose();
            textureD3D10.Dispose();
            textureD3D11.Dispose();
            factory1.Dispose();
            adapter1.Dispose();
            sharedResource.Dispose();
            factory2D.Dispose();
            surface.Dispose();
            solidColorBrush.Dispose();
            blendStateTransparent.Dispose();

            device10Mutex.Dispose();
            device11Mutex.Dispose();
        }
Example #45
0
        public PointCloud(List<FxMaths.Vector.FxVector3f> Points, List<FxMaths.Vector.FxVector3f> Colors)
        {
            Device dev = Engine.g_device;

            /// make a stream with the vertex to be able to insert it to the mesh
            DataStream stream = new DataStream(Marshal.SizeOf(typeof(PointCloudParticle)) * Points.Count, true, true);

            /// Init the shader
            m_shader = new Shaders.ShaderPointCloud();
            m_numParticles = Points.Count;

            m_shader.SetTexture("c://Particle.png");

            /// write the particles to the stream
            for (int i = 0; i < m_numParticles; i++)
            {
                Points[i].WriteToDataStream(stream);
                Colors[i].WriteToDataStream(stream);
            }
            /// reset the position in the stream
            stream.Position = 0;

            /// Fill the buffer with the vertices
            m_BufferParticles = ComputeShader.CreateBuffer(m_numParticles, ComputeShader.SizeOfFloat3 * 2, AccessViewType.SRV, stream);
            m_BufferParticles.DebugName = "ParticleBuffer";

            m_srvBufferParticles = FXResourceVariable.InitSRVResource(dev, m_BufferParticles);
            m_rvBufferParticles = m_shader.m_effect.GetResourceByName("particleBuffer");
            m_rvBufferParticles.SetResource(m_srvBufferParticles);

            // set the world matrix
            m_WorldMatrix = Matrix.Scaling(_scale) * Matrix.RotationYawPitchRoll(_rotation.Y, _rotation.X, _rotation.Z) * Matrix.Translation(_position);

            // close the stream
            stream.Close();
        }
        public void Run()
        {
            using (var form = EmptyWindow.CreateForm())
            {
                Device device;
                SwapChain swapChain;
                RenderTargetView renderTarget;

                EmptyWindow.CreateDeviceSwapChainAndRenderTarget(form, out device, out swapChain, out renderTarget);

                Vertex[] vertices = CreateVertices();

                var stream = new DataStream(vertices.Length * Marshal.SizeOf(typeof(Vertex)), true, true);

                foreach (var vertex in vertices)
                {
                    stream.Write(vertex.Position);
                    stream.Write(vertex.Color);
                }

                // Important: when specifying initial buffer data like this, the buffer will
                // read from the current DataStream position; we must rewind the stream to
                // the start of the data we just wrote.
                stream.Position = 0;

                var bufferDescription = new BufferDescription
                {
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None,
                    SizeInBytes = (3 * Marshal.SizeOf(typeof (Vertex))),
                    Usage = ResourceUsage.Default
                };

                var buffer = new Buffer(device, stream, bufferDescription);
                stream.Close();

                Effect effect;
                string errors = string.Empty;
                try
                {
                    effect = Effect.FromFile(device, "MyShader10.fx", "fx_4_0",
                        ShaderFlags.Debug, EffectFlags.None, null, null, out errors);
                    Console.WriteLine(errors);
                }
                catch (Exception)
                {
                    TestLog.Warnings.WriteLine(errors);

                    throw;
                }

                var technique = effect.GetTechniqueByIndex(0);
                var pass = technique.GetPassByIndex(0);

                var inputElements = new[]
                {
                    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                    new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0)
                };

                var inputLayout = new InputLayout(device, inputElements, pass.Description.Signature);

                Application.Idle +=
                   delegate
                   {
                       device.ClearRenderTargetView(renderTarget, new Color4(0, 0, 0));

                       device.InputAssembler.SetInputLayout(inputLayout);
                       device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList);
                       device.InputAssembler.SetVertexBuffers(0,
                           new VertexBufferBinding(buffer, Marshal.SizeOf(typeof(Vertex)), 0));

                       Matrix view = Matrix.LookAtRH(new Vector3(0, 0, 3), new Vector3(), new Vector3(0, 1, 0));
                       Matrix projection = Matrix.PerspectiveFovRH((float)(System.Math.PI / 3), 800f / 600.0f, 0.01f, 100f);
                       Matrix world = Matrix.Identity;
                       Matrix worldViewProjection = world * view * projection;

                       effect.GetVariableBySemantic("WorldViewProjection")
                           .AsMatrix().SetMatrix(worldViewProjection);

                       for (int actualPass = 0; actualPass < technique.Description.PassCount; ++actualPass)
                       {
                           pass.Apply();
                           device.Draw(vertices.Length, 0);
                       }

                       swapChain.Present(0, PresentFlags.None);

                       Application.DoEvents();
                   };

                Application.Run(form);
            }
        }
Example #47
0
        private Buffer CreateBuffer(Device device)
        {
            Vertex[] vertices = CreateVertices();

            var stream = new DataStream(vertices.Length * Marshal.SizeOf(typeof(Vertex)), true, true);

            foreach (var vertex in vertices)
            {
                stream.Write(vertex.Position);
                stream.Write(vertex.Color);
                stream.Write(vertex.Normal);
            }

            // Important: when specifying initial buffer data like this, the buffer will
            // read from the current DataStream position; we must rewind the stream to
            // the start of the data we just wrote.
            stream.Position = 0;

            var bufferDescription = new BufferDescription
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = (3 * Marshal.SizeOf(typeof(Vertex))),
                Usage = ResourceUsage.Default
            };

            var buffer = new Buffer(device, stream, bufferDescription);
            stream.Close();
            return buffer;
        }