static byte[] CreateRaw(IntPtr pixels, int width, int height) { using (var bitmap = new System.Drawing.Bitmap(width, height, width * 4, System.Drawing.Imaging.PixelFormat.Format32bppArgb, pixels)) { using (var stream = new MemoryStream()) { bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp); var factory = new ImagingFactory2(); using (var decoder = new BitmapDecoder(factory, stream, DecodeOptions.CacheOnDemand)) { using (var formatConverter = new FormatConverter(factory)) { formatConverter.Initialize(decoder.GetFrame(0), PixelFormat.Format32bppPRGBA); var stride = formatConverter.Size.Width * 4; using (var dataStream = new SharpDX.DataStream(formatConverter.Size.Height * stride, true, true)) { formatConverter.CopyPixels(stride, dataStream); byte[] b; using (BinaryReader br = new BinaryReader(dataStream)) { b = br.ReadBytes((int)dataStream.Length); } return(b); } } } } } }
public void Update(Bitmap bmp) { _textureIsDirty.ReleaseAll(); _dataBuffer.ReleaseAll(); int dataSize = bmp.Width * bmp.Height * 4; if (_dataStream != null && _dataStream.Length != dataSize) { _dataStream.Dispose(); _dataStream = null; } if (_dataStream == null) { _dataStream = new SharpDX.DataStream(dataSize, true, true); } Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); _dataStreamRowPitch = bmpData.Stride; _dataStream.Position = 0; _dataStream.WriteRange(bmpData.Scan0, dataSize); bmp.UnlockBits(bmpData); }
public static SharpDX.Direct3D11.Texture2D CreateTex2DFromBitmap(SharpDX.WIC.BitmapSource bsource, GraphicsDevice device) { SharpDX.Direct3D11.Texture2DDescription desc; desc.Width = bsource.Size.Width; desc.Height = bsource.Size.Height; desc.ArraySize = 1; desc.BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource; desc.Usage = SharpDX.Direct3D11.ResourceUsage.Default; desc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None; desc.Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm; desc.MipLevels = 1; desc.OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None; desc.SampleDescription.Count = 1; desc.SampleDescription.Quality = 0; SharpDX.Direct3D11.Texture2D dx11Texture; using(SharpDX.DataStream s = new SharpDX.DataStream(bsource.Size.Height * bsource.Size.Width * 4, true, true)) { bsource.CopyPixels(bsource.Size.Width * 4, s); SharpDX.DataRectangle rect = new SharpDX.DataRectangle(s.DataPointer, bsource.Size.Width * 4); dx11Texture = new SharpDX.Direct3D11.Texture2D(device._d3dDevice, desc, rect); } return dx11Texture; }
// the code below failing due to GC /*public static SharpDX.WIC.BitmapSource LoadBitmap(DirectXContext directXContext, Stream stream) * { * var bitmapDecoder = new SharpDX.WIC.BitmapDecoder( * directXContext.ImagingFactory2, * stream, * SharpDX.WIC.DecodeOptions.CacheOnLoad); * * var formatConverter = new SharpDX.WIC.FormatConverter(directXContext.ImagingFactory2); * * formatConverter.Initialize( * bitmapDecoder.GetFrame(0), * SharpDX.WIC.PixelFormat.Format32bppPRGBA, * SharpDX.WIC.BitmapDitherType.None, * null, * 0.0, * SharpDX.WIC.BitmapPaletteType.Custom); * * return formatConverter; * }*/ public static DirectXResource CreateTexture2DFromBitmap(DirectXContext directXContext, SharpDX.WIC.BitmapSource bitmapSource) { // Allocate DataStream to receive the WIC image pixels int stride = bitmapSource.Size.Width * 4; using (var buffer = new SharpDX.DataStream(bitmapSource.Size.Height * stride, true, true)) { try { // Copy the content of the WIC to the buffer bitmapSource.CopyPixels(stride, buffer); } catch (Exception e) { Core.LogError(e, "Failed to load image into Dx"); } return(directXContext.Pool.Get("loadbitmap", DirectXResource.Desc(bitmapSource.Size.Width, bitmapSource.Size.Height, SharpDX.DXGI.Format.R8G8B8A8_UNorm, SharpDX.Direct3D11.BindFlags.ShaderResource, SharpDX.Direct3D11.ResourceUsage.Immutable), new SharpDX.DataRectangle(buffer.DataPointer, stride))); } }
public static Bitmap ToD2D1Bitmap(this SdBitmap bitmap, RenderTarget renderTarget, PixelFormat pixelFormat) { var sourceArea = new SdRect(0, 0, bitmap.Width, bitmap.Height); var bitmapProperties = new BitmapProperties(pixelFormat); var size = new SharpDX.Size2(bitmap.Width, bitmap.Height); // Transform pixels from BGRA to RGBA. var stride = bitmap.Width * sizeof(int); using (var tempStream = new SharpDX.DataStream(bitmap.Height * stride, true, true)) { // Lock System.Drawing.Bitmap var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); // Convert all pixels. for (var y = 0; y < bitmap.Height; y++) { var offset = bitmapData.Stride * y; for (var x = 0; x < bitmap.Width; x++) { // Not optimized. var B = Marshal.ReadByte(bitmapData.Scan0, offset++); var G = Marshal.ReadByte(bitmapData.Scan0, offset++); var R = Marshal.ReadByte(bitmapData.Scan0, offset++); var A = Marshal.ReadByte(bitmapData.Scan0, offset++); tempStream.Write(R | (G << 8) | (B << 16) | (A << 24)); } } bitmap.UnlockBits(bitmapData); tempStream.Position = 0; return(new Bitmap(renderTarget, size, tempStream, stride, bitmapProperties)); } }
internal static void WritePixelsToTextureDataStream(SharpDX.DataStream stream, byte[] pixels, int actualWidth, int actualHeight) { for (int i = 0; i < actualHeight; i++) { stream.Write(pixels, i * actualWidth * 4, actualWidth * 4); } }
protected SharpDX.Direct3D11.Buffer CreateIndexBuffer(Renderer renderer) { int dataSize = Marshal.SizeOf(typeof(int)) * _indices.Length; BufferDescription bufferDescription = new BufferDescription(); bufferDescription.Usage = ResourceUsage.Default; bufferDescription.SizeInBytes = dataSize; bufferDescription.BindFlags = BindFlags.IndexBuffer; SharpDX.Direct3D11.Buffer buffer = null; using (SharpDX.DataStream stream = new SharpDX.DataStream(dataSize, true, true)) { for (int i = 0; i < _indices.Length; i++) { stream.Write <int>(_indices[i]); } stream.Position = 0; buffer = new SharpDX.Direct3D11.Buffer(renderer.Device, stream, bufferDescription); } _indexBuffer.Set(renderer, buffer); return(buffer); }
protected SharpDX.Direct3D11.Buffer CreateVertexBuffer(Renderer renderer) { //Logger.LogInfo(this, "Creating geometry with " + _vertices.Length + " vertices."); int dataSize = Marshal.SizeOf(typeof(T)) * _vertices.Length; BufferDescription bufferDescription = new BufferDescription(); bufferDescription.Usage = ResourceUsage.Default; bufferDescription.SizeInBytes = dataSize; bufferDescription.BindFlags = BindFlags.VertexBuffer; SharpDX.Direct3D11.Buffer buffer = null; using (SharpDX.DataStream stream = new SharpDX.DataStream(dataSize, true, true)) { for (int i = 0; i < _vertices.Length; i++) { stream.Write <T>(_vertices[i]); } stream.Position = 0; buffer = new SharpDX.Direct3D11.Buffer(renderer.Device, stream, bufferDescription); } _vertexBuffer.Set(renderer, buffer); return(buffer); }
public static Texture2D CreateTex2DFromBitmap(SharpDX.Direct3D11.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 SharpDX.DataStream(bsource.Size.Height * bsource.Size.Width * 4, true, true); bsource.CopyPixels(bsource.Size.Width * 4, s); var rect = new SharpDX.DataRectangle(s.DataPointer, bsource.Size.Width * 4); var t2D = new Texture2D(device, desc, rect); return(t2D); }
private Texture2D CreateTexture2DFromBitmap(BitmapSource bitmapSource) { Device device = engine.GraphicsServices.GetService <Device>(); // Allocate DataStream to receive the WIC image pixels int stride = bitmapSource.Size.Width * 4; using (var buffer = new SharpDX.DataStream(bitmapSource.Size.Height * stride, true, true)) { // Copy the content of the WIC to the buffer bitmapSource.CopyPixels(stride, buffer); return(new Texture2D(device, new Texture2DDescription() { Width = bitmapSource.Size.Width, Height = bitmapSource.Size.Height, ArraySize = 1, BindFlags = BindFlags.ShaderResource, Usage = ResourceUsage.Immutable, CpuAccessFlags = CpuAccessFlags.None, Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), }, new SharpDX.DataRectangle(buffer.DataPointer, stride))); } }
private static SharpDX.Direct2D1.Bitmap SDXBitmapFromSysBitmap(SharpDX.Direct2D1.WindowRenderTarget device, System.Drawing.Bitmap bitmap) { var sourceArea = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height); var bitmapProperties = new BitmapProperties(new PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied)); var size = new SharpDX.Size2(bitmap.Width, bitmap.Height); // Transform pixels from BGRA to RGBA int stride = bitmap.Width * sizeof(int); using (var tempStream = new SharpDX.DataStream(bitmap.Height * stride, true, true)) { // Lock System.Drawing.Bitmap var bitmapData = bitmap.LockBits(sourceArea, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); // Convert all pixels for (int y = 0; y < bitmap.Height; y++) { int offset = bitmapData.Stride * y; for (int x = 0; x < bitmap.Width; x++) { // Not optimized byte B = Marshal.ReadByte(bitmapData.Scan0, offset++); byte G = Marshal.ReadByte(bitmapData.Scan0, offset++); byte R = Marshal.ReadByte(bitmapData.Scan0, offset++); byte A = Marshal.ReadByte(bitmapData.Scan0, offset++); int rgba = R | (G << 8) | (B << 16) | (A << 24); tempStream.Write(rgba); } } bitmap.UnlockBits(bitmapData); tempStream.Position = 0; return(new SharpDX.Direct2D1.Bitmap(device, size, tempStream, stride, bitmapProperties)); } }
public static void CopyToD2D1Bitmap(this SdBitmap bitmap, Bitmap targetBitmap) { var sourceArea = new SdRect(0, 0, bitmap.Width, bitmap.Height); // Transform pixels from BGRA to RGBA. var stride = bitmap.Width * sizeof(int); var length = bitmap.Height * stride; using (var tempStream = new SharpDX.DataStream(length, true, true)) { // Lock System.Drawing.Bitmap var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); // Convert all pixels. for (var y = 0; y < bitmap.Height; y++) { var offset = bitmapData.Stride * y; for (var x = 0; x < bitmap.Width; x++) { // Not optimized. var B = Marshal.ReadByte(bitmapData.Scan0, offset++); var G = Marshal.ReadByte(bitmapData.Scan0, offset++); var R = Marshal.ReadByte(bitmapData.Scan0, offset++); var A = Marshal.ReadByte(bitmapData.Scan0, offset++); tempStream.Write(R | (G << 8) | (B << 16) | (A << 24)); } } bitmap.UnlockBits(bitmapData); tempStream.Position = 0; targetBitmap.CopyFromStream(tempStream, stride, length); } }
public unsafe Stream GetStream(int length) { var capacity = VVVV.Utils.Streams.StreamUtils.NextHigher(length); var memory = FUnmanagedMemoryPool.GetMemory(capacity); var stream = new SharpDX.DataStream(memory.Pointer, length, true, true); return(stream); }
internal Texture2D Texture2DRaw(DeviceResources deviceResources, MemoryStream rawData, SharpDX.Size2 size) { using (var dataStream = new SharpDX.DataStream((int)rawData.Length, true, true)) { dataStream.Write(rawData.ToArray(), 0, (int)rawData.Length); var texture2D = Texture2D(deviceResources, dataStream, size); return(texture2D); } }
public void tryb_Podstawowy_11(Collection <Collection <long> > pozycje) { SharpDX.DataStream gs = sc11.CaptureScreen(); kolory.Clear(); for (int k = 0; k < pozycje.Count; k++) { kolory.Add(avcs(gs, pozycje[k])); } sc11.dataStream.Close(); }
internal static Texture2D Texture2D(DeviceResources deviceResources, SharpDX.DataStream stream, SharpDX.Size2 size) { var textDesc = TextureDescription(1, size.Width, size.Height, ResourceOptionFlags.None); SharpDX.DataBox[] dataRects = { new SharpDX.DataBox(stream.DataPointer, size.Width * 4, 0) }; var texture2D = new Texture2D(deviceResources.D3DDevice, textDesc, dataRects); return(texture2D); }
//SharpDX.DataBox src = context.MapSubresource(lightDataBuffer, 1, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out SharpDX.DataStream stream); //stream.Write(light.GetStructLayoutResource()); //context.UnmapSubresource(lightDataBuffer, LightStructLayout.RegisterResourceSlot); public void UpdateDynamicBuffer <T>(T[] newdata, SharpDX.Direct3D11.Buffer buffer, int slot) where T : struct { SharpDX.DataStream stream = null; try { SharpDX.DataBox src = ImmediateContext.MapSubresource(buffer, slot, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out stream); stream.WriteRange(newdata); ImmediateContext.UnmapSubresource(buffer, slot); } finally { } }
public SharpDX.Direct2D1.Bitmap GetD2DBitmap(SharpDX.Direct2D1.DeviceContext dc) { BitmapSource src = Frame; // PixelFormat settings/conversion if (src.Format != System.Windows.Media.PixelFormats.Bgra32) { // Convert BitmapSource FormatConvertedBitmap fcb = new FormatConvertedBitmap(); fcb.BeginInit(); fcb.Source = src; fcb.DestinationFormat = PixelFormats.Bgra32; fcb.EndInit(); src = fcb; } if (src.PixelHeight > _maxImageSize || src.PixelWidth > _maxImageSize) { double scale = (src.PixelWidth > src.PixelHeight) ? _maxImageSize / src.PixelWidth : _maxImageSize / src.PixelHeight; TransformedBitmap tb = new TransformedBitmap(); tb.BeginInit(); tb.Source = src; tb.Transform = new ScaleTransform(scale, scale); tb.EndInit(); src = tb; } SharpDX.Direct2D1.Bitmap retval = null; GCHandle pinnedArray = GCHandle.Alloc(null); try { int stride = src.PixelWidth * (src.Format.BitsPerPixel + 7) / 8; int bufferSize = stride * src.PixelHeight; byte[] buffer = new byte[bufferSize]; src.CopyPixels(System.Windows.Int32Rect.Empty, buffer, stride, 0); pinnedArray = GCHandle.Alloc(buffer, GCHandleType.Pinned); using (SharpDX.DataStream datastream = new SharpDX.DataStream(pinnedArray.AddrOfPinnedObject(), bufferSize, true, false)) { var bmpProps1 = new SharpDX.Direct2D1.BitmapProperties1(dc.PixelFormat, dc.Factory.DesktopDpi.Width, dc.Factory.DesktopDpi.Height); retval = new SharpDX.Direct2D1.Bitmap1(dc, new SharpDX.Size2(src.PixelWidth, src.PixelHeight), datastream, stride, bmpProps1); } } catch { } finally { if (pinnedArray.IsAllocated) { pinnedArray.Free(); } } return(retval); }
public H1ImageWrapper(String filePath) { // to manipulate WIC objects ImagingFactory imagingFactory = new ImagingFactory(); // to open the file that holds the bitmap data NativeFileStream fileStream = new NativeFileStream( filePath, NativeFileMode.Open, NativeFileAccess.Read); BitmapDecoder bitmapDecoder = new BitmapDecoder(imagingFactory, fileStream, DecodeOptions.CacheOnDemand // for the time being as we won't be needing to take advantage of special cache handling ); // to retrieve the frame index 0 (static image only have one frame) const Int32 StaticFrame = 0; BitmapFrameDecode frame = bitmapDecoder.GetFrame(StaticFrame); // convert out bitmaps to the same pixel format for the shake of normalization FormatConverter converter = new FormatConverter(imagingFactory); converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA); // set the pixel format SetPixelFormat(converter.PixelFormat); // having the correct pixel format, we can finally create the desired SharpDX.Direct2D1.Bitmap1 Int32 width = converter.Size.Width; Int32 height = converter.Size.Height; Int32 stride = converter.Size.Width * 4; Int32 dataSize = height * stride; using (var buffer = new SharpDX.DataStream(dataSize, true, true)) { // copy the data to the buffer converter.CopyPixels(stride, buffer); H1GeneralBuffer generalBuffer = H1Global <H1ManagedRenderer> .Instance.CreateGeneralBuffer(Convert.ToUInt32(dataSize)); // mapping the data to the resource (buffer) generalBuffer.WriteData(buffer.DataPointer, dataSize); // first create texture resource //H1Texture2D textureObject = H1Global<H1ManagedRenderer>.Instance.CreateTexture2D(PixelFormat, width, height, new SharpDX.Vector4(), null); m_tempTextureObject = H1Global <H1ManagedRenderer> .Instance.CreateTexture2D(PixelFormat, width, height, new SharpDX.Vector4(), null); // copy texture region //H1Global<H1ManagedRenderer>.Instance.CopyTextureRegion(textureObject, generalBuffer); H1Global <H1ManagedRenderer> .Instance.CopyTextureRegion(m_tempTextureObject, generalBuffer); } //https://english.r2d2rigo.es/2014/08/12/loading-and-drawing-bitmaps-with-direct2d-using-sharpdx/ //http://stackoverflow.com/questions/9602102/loading-textures-with-sharpdx-in-windows-store-app //http://sharpdx.org/wiki/class-library-api/wic/ }
public void Update(Renderer renderer, byte[] buffer, int bufferOffset, int rowPitch) { _textureIsDirty.Release(renderer); _dataStream = null; _dataBuffer.Set(renderer, buffer); _dataBufferOffset.Set(renderer, bufferOffset); _dataBufferRowPitch.Set(renderer, rowPitch); Preload(renderer); }
/// <summary> /// Creates a <see cref="SharpDX.Direct3D11.Texture2D"/> from a WIC <see cref="SharpDX.WIC.BitmapSource"/> /// </summary> /// <param name="device">The Direct3D11 device</param> /// <param name="bitmapSource">The WIC bitmap source</param> /// <returns>A Texture2D</returns> public static SharpDX.Direct3D11.Texture2D CreateTexture2DFromBitmap(SharpDX.Direct3D11.Device device, SharpDX.WIC.BitmapSource bitmapSource, SharpDX.Direct3D11.Texture2DDescription textDesc) { // Allocate DataStream to receive the WIC image pixels int stride = bitmapSource.Size.Width * 4; using (var buffer = new SharpDX.DataStream(bitmapSource.Size.Height * stride, true, true)) { // Copy the content of the WIC to the buffer bitmapSource.CopyPixels(stride, buffer); return(new SharpDX.Direct3D11.Texture2D(device, textDesc, new SharpDX.DataRectangle(buffer.DataPointer, stride))); } }
public static SharpDX.Direct2D1.Bitmap ToBitmap(DUIRenderTarget renderTarget, Bitmap bitmap) { if (bitmap == null) { throw new ArgumentNullException("bitmap"); } System.Drawing.Imaging.BitmapData bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat); var dataStream = new SharpDX.DataStream(bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, true, false); var properties = new SharpDX.Direct2D1.BitmapProperties { PixelFormat = new SharpDX.Direct2D1.PixelFormat { Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode = SharpDX.Direct2D1.AlphaMode.Premultiplied } }; // ToDo apply scaling here! //var scaler = new SharpDX.WIC.BitmapScaler(renderTarget.Factory.NativePointer); //scaler. //Load the image from the gdi resource var result = new SharpDX.Direct2D1.Bitmap(renderTarget, new SharpDX.Size2(bitmap.Width, bitmap.Height), dataStream, bitmapData.Stride, properties); bitmap.UnlockBits(bitmapData); return(result); //System.Drawing.Bitmap desBitmap;//预定义要是使用的bitmap ////如果原始的图像像素格式不是32位带alpha通道,需要转换为32位带alpha通道的格式,否则无法和Direct2D的格式对应 //if (bitmap.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppPArgb) //{ // desBitmap = new System.Drawing.Bitmap(bitmap.Width, bitmap.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); // using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(desBitmap)) // { // g.DrawImage(bitmap, new System.Drawing.Rectangle(0, 0, desBitmap.Width, desBitmap.Height), new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.GraphicsUnit.Pixel); // } //} //else //{ // desBitmap = bitmap; //} ////直接内存copy会非常快 ////如果使用循环逐点转换会非常慢 //System.Drawing.Imaging.BitmapData bmpData = desBitmap.LockBits(new System.Drawing.Rectangle(0, 0, desBitmap.Width, desBitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, desBitmap.PixelFormat); //int numBytes = bmpData.Stride * desBitmap.Height; //byte[] byteData = new byte[numBytes]; //IntPtr ptr = bmpData.Scan0; //System.Runtime.InteropServices.Marshal.Copy(ptr, byteData, 0, numBytes); //desBitmap.UnlockBits(bmpData); //SharpDX.Direct2D1.PixelFormat pixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied); //SharpDX.Direct2D1.BitmapProperties bp = new SharpDX.Direct2D1.BitmapProperties(pixelFormat, desBitmap.HorizontalResolution, desBitmap.VerticalResolution); //SharpDX.Direct2D1.Bitmap tempBitmap = new SharpDX.Direct2D1.Bitmap(renderTarget, new SharpDX.Size2(desBitmap.Width, desBitmap.Height), bp); //tempBitmap.CopyFromMemory(byteData, bmpData.Stride); //return tempBitmap; }
void IView.Initialize(RenderContext context) { if (vertexBuffer != null) { vertexBuffer.Dispose(); } vertexBuffer = new VertexBuffer(context.Device, provider.Size * vertices.Length, Usage.WriteOnly, provider.Format, Pool.Managed); using (SharpDX.DataStream stream = vertexBuffer.Lock(0, 0, LockFlags.None)) { stream.WriteRange(vertices); } vertexBuffer.Unlock(); }
//SharpDX.DataBox src = context.MapSubresource(lightDataBuffer, 1, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out SharpDX.DataStream stream); //stream.Write(light.GetStructLayoutResource()); //context.UnmapSubresource(lightDataBuffer, LightStructLayout.RegisterResourceSlot); public void UpdateDynamicBuffer <T>(T[] newdata, SharpDX.Direct3D11.Buffer buffer) where T : struct { SharpDX.DataStream stream = null; try { SharpDX.DataBox src = ImmediateContext.MapSubresource(buffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out stream); // src.DataPointer stream.WriteRange(newdata); } finally { // Every buffer is defined as a single subresource (unlike textures). So subresource is always equals 0. ImmediateContext.UnmapSubresource(buffer, 0); } }
internal Direct3D9IndexBuffer(SharpDX.Direct3D9.Device device, uint[] data) { _length = data.Length; _buffer = new SharpDX.Direct3D9.IndexBuffer(device, data.Length * sizeof(uint), Usage.WriteOnly, Pool.Managed, false); SharpDX.DataStream ds = _buffer.Lock(0, _length * sizeof(uint), LockFlags.None); for (int i = 0; i < data.Length; i++) { ds.Write(data[i]); } _buffer.Unlock(); }
public void PrepareForDirectX(Device device) { CleanupDirectX(); //When drawing with a single index buffer inside of DirectX, all primitives must be the same type. //Furthermore, there are no polygons inside of DirectX, only triangles. Therefore, at this point //we break down all faces from polygons into triangles inside of the triangle list so all faces //can be drawn using triangles only. This also allows us to optimize face order for increased //rendering efficiency. List <int> listTriangles = new List <int>(); for (int i = 0; i < Faces.Count; i++) { for (int j = 1; j < Faces[i].IndexList.Count - 1; j++) { //We create a triangle fan out of the indices here for simplicity, preserving the original polygon normal directionality. listTriangles.Add(Faces[i].IndexList[0]); listTriangles.Add(Faces[i].IndexList[j]); listTriangles.Add(Faces[i].IndexList[j + 1]); } } //Calculate the number of unique indicies so we know exactly now many verticies are referenced //and then we can properly optimize our face order with OptimizeFaces() below. List <int> uniqueIndicies = new List <int> (); for (int i = 0; i < listTriangles.Count; i++) { if (uniqueIndicies.IndexOf(listTriangles[i]) < 0) { uniqueIndicies.Add(listTriangles[i]); } } //Optimize the triangle order for excellent vertex caching. //OptimizeFaces() returns a list of triangle indices which must be converted back into a list vertex indices (3 per triangle). int[] arrayOptimizedIndices = SharpDX.Direct3D9.D3DX.OptimizeFaces(listTriangles.ToArray(), listTriangles.Count / 3, uniqueIndicies.Count); List <int> listOptimalTriangles = new List <int>(); for (int f = 0; f < arrayOptimizedIndices.Length; f++) //Each value in arrayOptimizedIndicies represents one triangle. Enumerating triangles. { int firstVertexIndex = 3 * arrayOptimizedIndices[f]; //Index of first vertex for current triangle. listOptimalTriangles.Add(listTriangles[firstVertexIndex]); listOptimalTriangles.Add(listTriangles[firstVertexIndex + 1]); listOptimalTriangles.Add(listTriangles[firstVertexIndex + 2]); } int[] arrayTriangles = listOptimalTriangles.ToArray(); facesDirectX = new IndexBuffer(device, sizeof(int) * arrayTriangles.Length, Usage.None, Pool.Managed, false); SharpDX.DataStream ds = facesDirectX.Lock(0, 0, LockFlags.None); ds.WriteRange(arrayTriangles); facesDirectX.Unlock(); NumIndicies = arrayTriangles.Length; }
public override void SetData <T>(T[] data, int startIndex, int elementCount) { if (_usage == VertexBufferUsage.Static) { throw new Exception("Cannot update a VertexBuffer that's Static"); } int size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)); SharpDX.DataStream ds = _buffer.Lock(0, size * elementCount, LockFlags.None); ds.WriteRange(data, startIndex, elementCount); _buffer.Unlock(); }
Color avcs(SharpDX.DataStream gs, Collection <long> positions) { byte[] bu = new byte[4]; int r = 0; int g = 0; int b = 0; int i = 0; foreach (long pos in positions) { gs.Position = pos; if (gs.Length > positions[positions.Count - 1]) { if (gs.CanRead) { try { gs.Read(bu, 0, 4); } catch { } } } r += bu[2]; g += bu[1]; b += bu[0]; i++; } if (i == 0) { return(Color.Black); } else { int r_Usr = r / i; int g_Usr = g / i; int b_Usr = b / i; if (r_Usr == 0xAA) { r_Usr += 1; } if (g_Usr == 0xAA) { g_Usr += 1; } if (b_Usr == 0xAA) { b_Usr += 1; } return(Color.FromArgb(r_Usr, g_Usr, b_Usr)); } }
static void FillRandomVectors(SharpDX.DataStream stream) { float maxTapMag = -1; for (uint i = 0; i < NUM_SAMPLES; i++) { float curr = m_filterKernel[i].Length(); maxTapMag = (float)System.Math.Max(maxTapMag, curr); } float maxTapMagInv = 1.0f / maxTapMag; float rsum = 0.0f; Vector4[] occluderPoints = new Vector4[NUM_SAMPLES]; Vector4[] occluderPointsFlipped = new Vector4[NUM_SAMPLES]; for (uint i = 0; i < NUM_SAMPLES; i++) { Vector2 tapOffs = new Vector2(m_filterKernel[i].X * maxTapMagInv, m_filterKernel[i].Y * maxTapMagInv); occluderPoints[i].X = tapOffs.X; occluderPoints[i].Y = tapOffs.Y; occluderPoints[i].Z = 0; occluderPoints[i].W = (float)System.Math.Sqrt(1 - tapOffs.X * tapOffs.X - tapOffs.Y * tapOffs.Y); rsum += occluderPoints[i].W; // occluderPointsFlipped[i].X = tapOffs.X; occluderPointsFlipped[i].Y = -tapOffs.Y; } var colorScale = 1.0f / (2 * rsum); colorScale *= Params.ColorScale; for (uint i = 0; i < NUM_SAMPLES; i++) { stream.Write(occluderPoints[i]); } for (uint i = 0; i < NUM_SAMPLES; i++) { stream.Write(occluderPointsFlipped[i]); } }
public void DrawDebugWorld(DynamicsWorld world) { world.DebugDrawWorld(); if (lines.Count == 0) { return; } inputAssembler.InputLayout = inputLayout; if (lineArray.Length != lines.Count) { lineArray = new PositionColored[lines.Count]; lines.CopyTo(lineArray); if (vertexBuffer != null) { vertexBuffer.Dispose(); } vertexBufferDesc.SizeInBytes = PositionColored.Stride * lines.Count; using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(lineArray); data.Position = 0; vertexBuffer = new Buffer(device, data, vertexBufferDesc); } vertexBufferBinding.Buffer = vertexBuffer; } else { lines.CopyTo(lineArray); DataStream data; device.ImmediateContext.MapSubresource(vertexBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out data); data.WriteRange(lineArray); device.ImmediateContext.UnmapSubresource(vertexBuffer, 0); data.Dispose(); } inputAssembler.SetVertexBuffers(0, vertexBufferBinding); inputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.LineList; device.ImmediateContext.Draw(lines.Count, 0); lines.Clear(); }
public static Texture2D CreateTexture2DFromBitmap(Device device, BitmapSource bitmapSource) { // Allocate DataStream to receive the WIC image pixels int stride = bitmapSource.Size.Width * 4; using (var buffer = new SharpDX.DataStream(bitmapSource.Size.Height * stride, true, true)) { // Copy the content of the WIC to the buffer bitmapSource.CopyPixels(stride, buffer); return new SharpDX.Direct3D11.Texture2D(device, new SharpDX.Direct3D11.Texture2DDescription() { Width = bitmapSource.Size.Width, Height = bitmapSource.Size.Height, ArraySize = 1, BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource, Usage = SharpDX.Direct3D11.ResourceUsage.Immutable, CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None, Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm, MipLevels = 1, OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), }, new SharpDX.DataRectangle(buffer.DataPointer, stride)); } }
internal static SharpDX.Direct2D1.Bitmap ToD2DBitmap(this System.Drawing.Bitmap bitmap, SharpDX.Direct2D1.RenderTarget renderTarget) { var sourceArea = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height); var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties( new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied)); var size = new SharpDX.Size2(bitmap.Width, bitmap.Height); // Transform pixels from BGRA to RGBA int stride = bitmap.Width * sizeof(int); using (var tempStream = new SharpDX.DataStream(bitmap.Height * stride, true, true)) { // Lock System.Drawing.Bitmap var bitmapData = bitmap.LockBits(sourceArea, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); // Convert all pixels for (int y = 0; y < bitmap.Height; y++) { int offset = bitmapData.Stride * y; for (int x = 0; x < bitmap.Width; x++) { // Not optimized byte B = Marshal.ReadByte(bitmapData.Scan0, offset++); byte G = Marshal.ReadByte(bitmapData.Scan0, offset++); byte R = Marshal.ReadByte(bitmapData.Scan0, offset++); byte A = Marshal.ReadByte(bitmapData.Scan0, offset++); int rgba = B | (G << 8) | (R << 16) | (A << 24); tempStream.Write(rgba); } } bitmap.UnlockBits(bitmapData); tempStream.Position = 0; return new SharpDX.Direct2D1.Bitmap(renderTarget, size, tempStream, stride, bitmapProperties); } }
internal static SharpDX.Direct3D11.ShaderResourceView CreateArrayView(float[] values, Device device, out SharpDX.DataStream data, out SharpDX.Direct3D11.Buffer buff) { data = new SharpDX.DataStream(values.Length * Marshal.SizeOf(typeof(float)), true, true); data.WriteRange<float>(values); // Create the compute shader buffer and views for common data buff = CreateBuffer(device, data, Marshal.SizeOf(typeof(float))); return CreateView(device, buff); }
protected override void OnPreRender(RenderArgs dstArgs, RenderArgs srcArgs) { KeyValueConfigurationElement displayTimer = GetDllConfig().AppSettings.Settings["Timer"]; CleanUp(); if (displayTimer != null && displayTimer.Value == "1") { this.tmr = new System.Diagnostics.Stopwatch(); this.tmr.Start(); } base.OnPreRender(dstArgs, srcArgs); this.IsLargeImage = (srcArgs.Width > base.MaxTextureSize || srcArgs.Height > base.MaxTextureSize); try { if (this.IsInitialized) { // Copy source image pixels imageData = SurfaceToStream(srcArgs.Surface); if (this.IsLargeImage) { // Create the source image buffer and views imageBuffer = CreateBuffer(base.Device, imageData, BUFF_SIZE); imageView = CreateView(base.Device, imageBuffer); } else { // Create the source texture view imageView = CreateView(out texture, base.Device, imageData, srcArgs.Width, srcArgs.Height); } } } catch (SharpDX.SharpDXException ex) { MessageBox.Show(ex.Message); this.IsInitialized = false; } }
/// <summary> /// Constructor. /// </summary> /// <param name="graphicsDevice"></param> /// <param name="vertexBufferSize"></param> /// <param name="matrixStackSize"></param> /// <param name="colorStackSize"></param> public GraphicsBatch(GraphicsDevice graphicsDevice, int vertexBufferSize, int matrixStackSize) { if (graphicsDevice == null) throw new ArgumentNullException("graphicsDevice"); graphicsDevice.EnsureDeviceCreated(); this.GraphicsDevice = graphicsDevice; this.vertexDeclaration = new D3D.VertexDeclaration(this.GraphicsDevice.InternalDevice, new[] { new D3D.VertexElement(0, 0, D3D.DeclarationType.Float4, D3D.DeclarationMethod.Default, D3D.DeclarationUsage.Position, 0), new D3D.VertexElement(0, 16, D3D.DeclarationType.Float4, D3D.DeclarationMethod.Default, D3D.DeclarationUsage.Color, 0), new D3D.VertexElement(0, 32, D3D.DeclarationType.Float2, D3D.DeclarationMethod.Default, D3D.DeclarationUsage.TextureCoordinate, 0), D3D.VertexElement.VertexDeclarationEnd }); this.vertices = new Vertex[vertexBufferSize * 4]; this.vertexCount = 0; this.indices = new short[vertexBufferSize * 6]; for (short i = 0, vertex = 0; i < this.indices.Length; i += 6, vertex += 4) { this.indices[i] = vertex; this.indices[i + 1] = (short)(vertex + 1); this.indices[i + 2] = (short)(vertex + 2); this.indices[i + 3] = vertex; this.indices[i + 4] = (short)(vertex + 2); this.indices[i + 5] = (short)(vertex + 3); } this.basicEffect = new BasicEffect(this.GraphicsDevice); this.pixel = D3DHelper.CreateTexture(this.GraphicsDevice.InternalDevice, 1, 1, TextureUsage.None); SharpDX.DataRectangle dataRectangle = this.pixel.LockRectangle(0, D3D.LockFlags.None); using (SharpDX.DataStream dataStream = new SharpDX.DataStream(dataRectangle.DataPointer, dataRectangle.Pitch, true, true)) { dataStream.WriteRange(new Color[] { Color.White }); } this.pixel.UnlockRectangle(0); this.pixelSource = new Rectangle(0, 0, 1, 1); this.matrixStack = new Matrix[matrixStackSize]; this.matrixStackCount = 0; this.texture = null; }
protected override void OnPreRender(RenderArgs dstArgs, RenderArgs srcArgs) { string shaderPath; CleanUpLocal(); base.OnPreRender(dstArgs, srcArgs); try { if (this.repeatEdgePixels) { shaderPath = "ComputeShaderEffects.Shaders.MotionBlurClamp.fx"; } else { shaderPath = "ComputeShaderEffects.Shaders.MotionBlur.fx"; } base.Consts = new Constants(); base.SetShader(shaderPath); if (base.IsInitialized) { // Copy points pointData = new SharpDX.DataStream(this.points.Length * Marshal.SizeOf(typeof(PointType)), true, true); foreach (PointType pt in this.points) { pointData.Write<PointType>(pt); } // Create the compute shader buffer and views for common data pointBuffer = CreateBuffer(base.Device, pointData, Marshal.SizeOf(typeof(PointType))); pointView = CreateView(base.Device, pointBuffer); base.AddResourceViews(new ShaderResourceView[] { pointView } ); base.ApronSize = (int)Math.Ceiling(Math.Max( Math.Abs(this.points[this.points.Length-1].X), Math.Abs(this.points[this.points.Length-1].Y))); } } catch (SharpDX.SharpDXException ex) { MessageBox.Show(ex.Message); base.IsInitialized = false; } }
private void CreateInternalTexture(GraphicsDevice graphicsDevice, D3D.Texture texture) { this.CalculateInternalSize(graphicsDevice); // Check if we need to resize if (this.InternalWidth == this.Width && this.InternalHeight == this.Height) { this.InternalTexture = texture; return; } this.InternalTexture = D3DHelper.CreateTexture(graphicsDevice.InternalDevice, this.InternalWidth, this.InternalHeight, TextureUsage.None); SharpDX.DataRectangle input = texture.LockRectangle(0, D3D.LockFlags.ReadOnly); SharpDX.DataStream inputStream = new SharpDX.DataStream(input.DataPointer, this.Height * input.Pitch, true, false); SharpDX.DataRectangle output = this.InternalTexture.LockRectangle(0, D3D.LockFlags.None); SharpDX.DataStream outputStream = new SharpDX.DataStream(output.DataPointer, this.InternalHeight * output.Pitch, true, true); byte[] buffer = new byte[4]; for (int y = 0; y < this.Height; y++) { for (int x = 0; x < this.Width; x++) { inputStream.Seek((y * input.Pitch) + (x * 4), SeekOrigin.Begin); inputStream.Read(buffer, 0, 4); outputStream.Seek((y * output.Pitch) + (x * 4), SeekOrigin.Begin); outputStream.Write(buffer, 0, 4); } } texture.UnlockRectangle(0); this.InternalTexture.UnlockRectangle(0); texture.Dispose(); // Get rid of old texture }
/// <summary> /// Gets the pixels of the Texture. /// </summary> /// <returns></returns> public Color[] GetColorData() { Color[] colorData = new Color[this.Width * this.Height]; SharpDX.DataRectangle dataRectangle = this.InternalTexture.LockRectangle(0, D3D.LockFlags.ReadOnly); using (SharpDX.DataStream dataStream = new SharpDX.DataStream(dataRectangle.DataPointer, this.InternalWidth * dataRectangle.Pitch, true, false)) { int x = 0; int y = 0; for (int i = 0; i < colorData.Length; i++) { dataStream.Seek((y * dataRectangle.Pitch) + (x * 4), SeekOrigin.Begin); byte b = (byte)dataStream.ReadByte(); byte g = (byte)dataStream.ReadByte(); byte r = (byte)dataStream.ReadByte(); byte a = (byte)dataStream.ReadByte(); colorData[i] = new Color(r, g, b, a); x++; if (x >= this.Width) { x = 0; y++; } } } this.InternalTexture.UnlockRectangle(0); return colorData; }
protected override void OnRenderRegion(Rectangle[] rois, RenderArgs dstArgs, RenderArgs srcArgs) { Surface dst; Surface src; Rectangle previousRect = new Rectangle(); SharpDX.Direct3D11.Buffer resultBuffer = null; SharpDX.Direct3D11.Buffer copyBuf = null; UnorderedAccessView resultView = null; SharpDX.Direct3D11.Buffer constBuffer = null; dst = dstArgs.Surface; src = srcArgs.Surface; constBuffer = CreateConstantBuffer(base.Device, Marshal.SizeOf(this.Consts)); foreach (Rectangle rect in rois) { if (!this.IsInitialized || base.IsCancelRequested) return; // Compute Shader Parameters this.Consts = SetRenderOptions(rect, this.Consts); // Result buffer and view if (previousRect.Width != rect.Width || previousRect.Height != rect.Height) { resultView.DisposeIfNotNull(); resultBuffer.DisposeIfNotNull(); copyBuf.DisposeIfNotNull(); resultBuffer = CreateBuffer(base.Device, rect.Width * rect.Height * BUFF_SIZE, BUFF_SIZE); resultView = CreateUnorderedAccessView(base.Device, resultBuffer); copyBuf = CreateStagingBuffer(base.Device, base.Context, resultBuffer); } // Update constants resource using (SharpDX.DataStream data = new SharpDX.DataStream(Marshal.SizeOf(this.Consts), true, true)) { byte[] constsBytes = RawSerialize(this.Consts); data.Write(constsBytes, 0, constsBytes.Length); data.Position = 0; base.Context.UpdateSubresource(new SharpDX.DataBox(data.DataPointer), constBuffer, 0); } resourceViews[0] = imageView; RunComputeShader(base.Context, shader, resourceViews, new UnorderedAccessView[] { resultView }, constBuffer, (int)Math.Ceiling(rect.Width / (float)DimensionX), (int)Math.Ceiling(rect.Height / (float)DimensionY)); base.Context.CopyResource(resultBuffer, copyBuf); // Copy to destination pixels SharpDX.DataBox mappedResource = base.Context.MapSubresource(copyBuf, 0, MapMode.Read, MapFlags.None); CopyStreamToSurface(mappedResource, dst, rect); base.Context.UnmapSubresource(copyBuf, 0); previousRect = rect; if (this.tmr != null && rect.Top + rect.Height == src.Height && rect.Right == src.Width) { this.tmr.Stop(); System.Windows.Forms.MessageBox.Show(this.tmr.ElapsedMilliseconds.ToString() + "ms"); } } resultView.DisposeIfNotNull(); resultBuffer.DisposeIfNotNull(); copyBuf.DisposeIfNotNull(); constBuffer.DisposeIfNotNull(); }
public static Texture2D CreateTexture2DFromBitmap(Device device, SharpDX.WIC.BitmapSource bitmapSource, Texture2DDescription texDesc) { // Allocate DataStream to receive the WIC image pixels int stride = bitmapSource.Size.Width * 4; using(var buffer = new SharpDX.DataStream(bitmapSource.Size.Height * stride, true, true)) { // Copy the content of the WIC to the buffer bitmapSource.CopyPixels(stride, buffer); return new Texture2D(device, texDesc, new SharpDX.DataRectangle(buffer.DataPointer, stride)); } }