Exemplo n.º 1
1
        protected void Blit(D3D9.Device d3d9Device, HardwarePixelBuffer rsrc, BasicBox srcBox, BasicBox dstBox,
                            BufferResources srcBufferResources, BufferResources dstBufferResources)
        {
            if (dstBufferResources.Surface != null && srcBufferResources.Surface != null)
            {
                // Surface-to-surface
                var dsrcRect  = ToD3DRectangle(srcBox);
                var ddestRect = ToD3DRectangle(dstBox);

                var srcDesc = srcBufferResources.Surface.Description;

                // If we're blitting from a RTT, try GetRenderTargetData
                // if we're going to try to use GetRenderTargetData, need to use system mem pool

                // romeoxbm: not used even in Ogre
                //var tryGetRenderTargetData = false;

                if ((srcDesc.Usage & D3D9.Usage.RenderTarget) != 0 && srcDesc.MultiSampleType == D3D9.MultisampleType.None)
                {
                    // Temp texture
                    var tmptex = new D3D9.Texture(d3d9Device, srcDesc.Width, srcDesc.Height, 1,
                                                  // 1 mip level ie topmost, generate no mipmaps
                                                  0, srcDesc.Format, D3D9.Pool.SystemMemory);

                    var tmpsurface = tmptex.GetSurfaceLevel(0);

                    d3d9Device.GetRenderTargetData(srcBufferResources.Surface, tmpsurface);
                    D3D9.Surface.FromSurface(dstBufferResources.Surface, tmpsurface, D3D9.Filter.Default, 0, dsrcRect,
                                             ddestRect);
                    tmpsurface.SafeDispose();
                    tmptex.SafeDispose();
                    return;
                }

                // Otherwise, try the normal method
                D3D9.Surface.FromSurface(dstBufferResources.Surface, srcBufferResources.Surface, D3D9.Filter.Default, 0,
                                         dsrcRect, ddestRect);
            }
            else if (dstBufferResources.Volume != null && srcBufferResources.Volume != null)
            {
                // Volume-to-volume
                var dsrcBox  = ToD3DBox(srcBox);
                var ddestBox = ToD3DBox(dstBox);

                D3D9.Volume.FromVolume(dstBufferResources.Volume, srcBufferResources.Volume, D3D9.Filter.Default, 0,
                                       dsrcBox, ddestBox);
            }
            else
            {
                // Software fallback
                base.Blit(rsrc, srcBox, dstBox);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Sets the back buffer of the <see cref="D3D11Image"/>.
        /// </summary>
        /// <param name="texture">The Direct3D 11 texture to be used as the back buffer.</param>
        public void SetBackBuffer(Texture2D texture)
        {
            ThrowIfDisposed();

            var previousBackBuffer = _backBuffer;

            // Create shared texture on Direct3D 9 device.
            _backBuffer = _d3D9.GetSharedTexture(texture);
            if (_backBuffer != null)
            {
                // Set texture as new back buffer.
                using (Surface surface = _backBuffer.GetSurfaceLevel(0))
                {
                    Lock();
                    SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer);
                    Unlock();
                }
            }
            else
            {
                // Reset back buffer.
                Lock();
                SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero);
                Unlock();
            }

            if (previousBackBuffer != null)
            {
                previousBackBuffer.Dispose();
            }
        }
        public void SetRenderTargetDX10(SharpDX.Direct3D10.Texture2D renderTarget)
        {
            if (RenderTarget != null)
            {
                RenderTarget = null;

                base.Lock();
                base.SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero);
                base.Unlock();
            }

            if (renderTarget == null)
                return;

            if (!IsShareable(renderTarget))
                throw new ArgumentException("Texture must be created with ResourceOptionFlags.Shared");

            Format format = DX10ImageSource.TranslateFormat(renderTarget);
            if (format == Format.Unknown)
                throw new ArgumentException("Texture format is not compatible with OpenSharedResource");

            IntPtr handle = GetSharedHandle(renderTarget);
            if (handle == IntPtr.Zero)
                throw new ArgumentNullException("Handle");

            RenderTarget = new Texture(DX10ImageSource.D3DDevice, renderTarget.Description.Width, renderTarget.Description.Height, 1, Usage.RenderTarget, format, Pool.Default, ref handle);
            using (Surface surface = RenderTarget.GetSurfaceLevel(0))
            {
                base.Lock();
                base.SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer);
                base.Unlock();
            }
        }
Exemplo n.º 4
0
        public void ConstructRenderAndResource(double width, double height)
        {
            float dpiX, dpiY;

            this.GetDpi(out dpiX, out dpiY);
            D2D.RenderTargetProperties prop = new D2D.RenderTargetProperties(
                D2D.RenderTargetType.Default,
                new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied),
                dpiX,
                dpiY,
                D2D.RenderTargetUsage.None,
                D2D.FeatureLevel.Level_DEFAULT);

            D3D11.Texture2DDescription desc = new D3D11.Texture2DDescription();
            desc.Width             = (int)width;
            desc.Height            = (int)height;
            desc.MipLevels         = 1;
            desc.ArraySize         = 1;
            desc.Format            = DXGI.Format.B8G8R8A8_UNorm;
            desc.SampleDescription = new DXGI.SampleDescription(1, 0);
            desc.Usage             = D3D11.ResourceUsage.Default;
            desc.BindFlags         = D3D11.BindFlags.RenderTarget | D3D11.BindFlags.ShaderResource;
            desc.CpuAccessFlags    = D3D11.CpuAccessFlags.None;
            desc.OptionFlags       = D3D11.ResourceOptionFlags.Shared;
            this.d3d11Texture      = new D3D11.Texture2D(this.device, desc);

            this.surface = this.d3d11Texture.QueryInterface <DXGI.Surface>();

            DXGI.Resource resource = this.d3d11Texture.QueryInterface <DXGI.Resource>();
            IntPtr        handel   = resource.SharedHandle;

            D3D9.Texture texture = new D3D9.Texture(
                this.device9,
                this.d3d11Texture.Description.Width,
                this.d3d11Texture.Description.Height,
                1,
                D3D9.Usage.RenderTarget,
                D3D9.Format.A8R8G8B8,
                D3D9.Pool.Default,
                ref handel);
            this.surface9 = texture.GetSurfaceLevel(0);
            resource.Dispose();
            texture.Dispose();

            D2D.BitmapProperties bmpProp = new D2D.BitmapProperties();
            bmpProp.DpiX        = dpiX;
            bmpProp.DpiY        = dpiY;
            bmpProp.PixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied);
            this.bmpd2d         = new D2D.Bitmap(this.render, this.surface, bmpProp);
            this.cachedBitMap   = new D2D.Bitmap(this.render, new Size2((int)width, (int)height), bmpProp);
            this.hasCache       = false;

            this.render.Target = this.bmpd2d;

            this.renderSize = new Size(width, height);
        }
Exemplo n.º 5
0
 public void SetBackBuffer(SharpDX.Direct3D9.Texture texture)
 {
     if (texture == null)
     {
         ReleaseBackBuffer();
     }
     else
     {
         using (Surface Surface = texture.GetSurfaceLevel(0))
         {
             d3dImage.Lock();
             d3dImage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, Surface.NativePointer);
             d3dImage.Unlock();
         }
     }
 }
            //---------------------------------------------------------------------------------------------------------
            /// <summary>
            /// Установка в качестве источника поверхности ренденинга текстуры Direct3D11
            /// </summary>
            /// <param name="render_target">Текстура Direct3D11</param>
            //---------------------------------------------------------------------------------------------------------
            public void SetRenderTarget(Direct3D11.Texture2D render_target)
            {
                // Если есть наша поверхность ренденинга то обнуляем ее
                if (mRenderTarget != null)
                {
                    mRenderTarget = null;

                    base.Lock();
                    base.SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero);
                    base.Unlock();
                }

                if (render_target == null)
                {
                    return;
                }

                if (!XDirect2DManager.IsShareable(render_target))
                {
                    throw new ArgumentException("Texture must be created with ResourceOptionFlags.Shared");
                }

                Direct3D9.Format format = XDirect2DManager.TranslateFormat(render_target);
                if (format == Direct3D9.Format.Unknown)
                {
                    throw new ArgumentException("Texture format is not compatible with OpenSharedResource");
                }

                IntPtr handle = XDirect2DManager.GetSharedHandle(render_target);

                if (handle == IntPtr.Zero)
                {
                    throw new ArgumentNullException("Handle");
                }

                // Создаем в текстура для ренденинга
                mRenderTarget = new Direct3D9.Texture(XDirect2DManager.D3DDevice, render_target.Description.Width,
                                                      render_target.Description.Height, 1, Direct3D9.Usage.RenderTarget, format, Direct3D9.Pool.Default, ref handle);

                // Получаем поверхность и обновляем представление
                using (Direct3D9.Surface surface = mRenderTarget.GetSurfaceLevel(0))
                {
                    base.Lock();
                    base.SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer);
                    base.Unlock();
                }
            }
        /// <summary>
        ///
        /// </summary>
        /// <param name="texture"></param>
        public void SetBackBuffer(SharpDX.Direct3D9.Texture texture)
        {
            if (IsDisposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            SharpDX.Direct3D9.Texture toDelete = null;
            try
            {
                if (texture != m_backBuffer)
                {
                    // if it's from the private (SDX9ImageSource) D3D9 device, dispose of it
                    if (m_backBuffer != null && m_backBuffer.Device.NativePointer == s_d3d9.Device.NativePointer)
                    {
                        toDelete = m_backBuffer;
                    }
                    m_backBuffer = texture;
                }

                if (texture != null)
                {
                    using (Surface surface = texture.GetSurfaceLevel(0))
                    {
                        Lock();
                        SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer);
                        AddDirtyRect(new Int32Rect(0, 0, base.PixelWidth, base.PixelHeight));
                        Unlock();
                    }
                }
                else
                {
                    Lock();
                    SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero);
                    AddDirtyRect(new Int32Rect(0, 0, base.PixelWidth, base.PixelHeight));
                    Unlock();
                }
            }
            finally
            {
                if (toDelete != null)
                {
                    toDelete.Dispose();
                }
            }
        }
Exemplo n.º 8
0
    private void InitTexture(BluRayAPI.OSDTexture item)
    {
      if (item.Width == 0 || item.Height == 0 || item.Texture == IntPtr.Zero)
      {
        FreeResources();
        return;
      }

      if (_combinedOsdTexture == null || _combinedOsdTexture.IsDisposed)
      {
        _combinedOsdTexture = new Texture(_device, _fullOsdSize.Width, _fullOsdSize.Height, 1, Usage.RenderTarget, FORMAT, Pool.Default);
        _combinedOsdSurface = _combinedOsdTexture.GetSurfaceLevel(0);

        _sprite = new Sprite(_device);

        Rectangle dstRect = new Rectangle(0, 0, _fullOsdSize.Width, _fullOsdSize.Height);
        _device.ColorFill(_combinedOsdSurface, dstRect, _transparentColor);
      }
    }
Exemplo n.º 9
0
        public void SetBackBufferDX11(D3D11.Texture2D texture)
        {
            if (m_sharedTexture != null)
            {
                m_sharedTexture.Dispose();
                m_sharedTexture = null;
            }

            if (texture == null)
            {
                Lock();
                SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero);
                Unlock();
            }
            else
            {
                if (IsShareable(texture) == false)
                    throw new ArgumentException("Texture must be created with ResourceOptionFlags.Shared");

                D3D9.Format format = TranslateFormat(texture);
                if (format == D3D9.Format.Unknown)
                    throw new ArgumentException("Texture format is not compatible with OpenSharedResource");

                IntPtr handle = GetSharedHandle(texture);
                if (handle == IntPtr.Zero)
                    throw new ArgumentNullException("Handle");

                m_sharedTexture = new D3D9.Texture(s_device, texture.Description.Width, texture.Description.Height, 1,
                    D3D9.Usage.RenderTarget, format, D3D9.Pool.Default, ref handle);

                using (D3D9.Surface surface = m_sharedTexture.GetSurfaceLevel(0))
                {
                    Lock();
                    SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer);
                    Unlock();
                }
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Creates new instance of <see cref="D3D11Image"/> Associates an D3D11 render target with the current instance.
        /// </summary>
        /// <param name="device">A valid D3D9 DeviceEx.</param>
        /// <param name="renderTarget">A valid D3D11 render target. It must be created with the "Shared" flag.</param>
        public D3D11Image(DeviceEx device, Direct3D11.Texture2D renderTarget)
        {
            using (var resource = renderTarget.QueryInterface<DXGI.Resource>())
            {
                var handle = resource.SharedHandle;
                texture = new Texture(device,
                                      renderTarget.Description.Width,
                                      renderTarget.Description.Height,
                                      1,
                                      Usage.RenderTarget,
                                      Format.A8R8G8B8,
                                      Pool.Default,
                                      ref handle);
            }

            using (var surface = texture.GetSurfaceLevel(0))
            {
                textureSurfaceHandle = surface.NativePointer;
                TrySetBackbufferPointer(textureSurfaceHandle);
            }

            this.IsFrontBufferAvailableChanged += HandleIsFrontBufferAvailableChanged;
        }
Exemplo n.º 11
0
        private void SetRenderTarget(D3D11.Texture2D target)
        {
            var format = TranslateFormat(target);
            var handle = GetSharedHandle(target);

            var presentParams = GetPresentParameters();
            var createFlags   = D3D9.CreateFlags.HardwareVertexProcessing | D3D9.CreateFlags.Multithreaded |
                                D3D9.CreateFlags.FpuPreserve;

            var d3DContext = new D3D9.Direct3DEx();
            var d3DDevice  = new D3D9.DeviceEx(d3DContext, 0, D3D9.DeviceType.Hardware, IntPtr.Zero, createFlags,
                                               presentParams);

            _renderTarget = new D3D9.Texture(d3DDevice, target.Description.Width, target.Description.Height, 1,
                                             D3D9.Usage.RenderTarget, format, D3D9.Pool.Default, ref handle);

            using (var surface = _renderTarget.GetSurfaceLevel(0))
            {
                _d3D.Lock();
                _d3D.SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer);
                _d3D.Unlock();
            }
        }
Exemplo n.º 12
0
        public void SetRenderTarget( SharpDX.Direct3D11.Texture2D target ) {
            if( renderTarget != null ) {
                renderTarget = null;

                base.Lock();
                base.SetBackBuffer( D3DResourceType.IDirect3DSurface9, IntPtr.Zero );
                base.Unlock();
            }

            if( target == null ) {
                return;
            }

            var format = Dx11ImageSource.TranslateFormat( target );
            var handle = GetSharedHandle( target );

            if ( !IsShareable( target ) ) {
                throw new ArgumentException( "Texture must be created with ResouceOptionFlags.Shared" );
            }

            if ( format == Format.Unknown ) {
                throw new ArgumentException( "Texture format is not compatible with OpenSharedResouce" );
            }

            if ( handle == IntPtr.Zero ) {
                throw new ArgumentException( "Invalid handle" );
            }

            renderTarget = new Texture( Dx11ImageSource.D3DDevice, target.Description.Width, target.Description.Height, 1, Usage.RenderTarget, format, Pool.Default, ref handle );

            using( var surface = renderTarget.GetSurfaceLevel( 0 ) ) {
                base.Lock();
                base.SetBackBuffer( D3DResourceType.IDirect3DSurface9, surface.NativePointer );
                base.Unlock();
            }
        }
Exemplo n.º 13
0
		internal void SetRenderTargetDX10(global::SharpDX.Direct3D11.Texture2D renderTarget)
		{
			if (_renderTarget != null)
			{
				_renderTarget = null;

				Lock();
				SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero);
				Unlock();
			}

			if (renderTarget == null)
				return;

			if (!renderTarget.IsShareable())
				throw new ArgumentException("Texture must be created with ResourceOptionFlags.Shared");

			var format = renderTarget.GetTranslatedFormat();
			if (format == Format.Unknown)
				throw new ArgumentException("Texture format is not compatible with OpenSharedResource");

			var handle = renderTarget.GetSharedHandle();
			if (handle == IntPtr.Zero)
				throw new ArgumentException("Handle could not be retrieved");

			_renderTarget = new Texture(DeviceService.D3DDevice, 
				renderTarget.Description.Width, 
				renderTarget.Description.Height, 
				1, Usage.RenderTarget, format, 
				Pool.Default, ref handle);

			using (Surface surface = _renderTarget.GetSurfaceLevel(0))
			{
				Lock();
				SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer);
				Unlock();
			}
		}
Exemplo n.º 14
0
 private void DrawFullscreenQuad(Texture texture, Texture renderTarget)
 {
     //set the render target.
     Surface savedRenderTarget = _graphics.GetRenderTarget(0);
     _graphics.SetRenderTarget(0, renderTarget.GetSurfaceLevel(0));
     DrawFullscreenQuad(texture);
     _graphics.SetRenderTarget(0, savedRenderTarget);
 }
Exemplo n.º 15
0
    public void DrawItem(BluRayAPI.OSDTexture item)
    {
      try
      {
        lock (_syncObj)
        {
          InitTexture(item);
          if (_combinedOsdSurface != null)
          {
            Rectangle sourceRect = new Rectangle(0, 0, item.Width, item.Height);
            Rectangle dstRect = new Rectangle(item.X, item.Y, item.Width, item.Height);

            using (Texture itemTexture = new Texture(item.Texture))
              _device.StretchRectangle(itemTexture.GetSurfaceLevel(0), sourceRect, _combinedOsdSurface, dstRect, TextureFilter.None);
          }
        }
      }
      catch (Exception ex)
      {
        BluRayPlayerBuilder.LogError(ex.ToString());
      }

      if (_onTextureInvalidated != null)
        _onTextureInvalidated();
    }
Exemplo n.º 16
0
 protected static Texture CreateTextureCopy(Texture sourceTexture, out SizeF textureSize)
 {
   if (sourceTexture == null)
   {
     textureSize = new SizeF();
     return null;
   }
   SurfaceDescription desc = sourceTexture.GetLevelDescription(0);
   textureSize = new SizeF(desc.Width, desc.Height);
   DeviceEx device = SkinContext.Device;
   Texture result = new Texture(device, desc.Width, desc.Height, 1, Usage.None, Format.A8R8G8B8, Pool.Default);
   using(Surface target = result.GetSurfaceLevel(0))
   using(Surface source = sourceTexture.GetSurfaceLevel(0))
     device.StretchRectangle(source, target, TextureFilter.None);
   return result;
 }
Exemplo n.º 17
0
        public static void SaveScreenshot(Texture texture2D, string file)
        {      
            MyMwcLog.WriteLine("MyScreenshot.SaveTexture2D() - START");
            MyMwcLog.IncreaseIndent();

            Texture systemTex =  new Texture(MinerWars.AppCode.App.MyMinerGame.Static.GraphicsDevice, texture2D.GetLevelDescription(0).Width, texture2D.GetLevelDescription(0).Height, 0, Usage.None, Format.A8R8G8B8, Pool.SystemMemory);


            Surface sourceSurface = texture2D.GetSurfaceLevel(0);
            Surface destSurface = systemTex.GetSurfaceLevel(0);
            MinerWars.AppCode.App.MyMinerGame.Static.GraphicsDevice.GetRenderTargetData(sourceSurface, destSurface);
            sourceSurface.Dispose();
            destSurface.Dispose();

            texture2D = systemTex;

            try
            {
                MyMwcLog.WriteLine("File: " + file);

                MyFileSystemUtils.CreateFolderForFile(file);

                Stack<SharpDX.Rectangle> tiles = new Stack<SharpDX.Rectangle>();

                int tileWidth = texture2D.GetLevelDescription(0).Width;
                int tileHeight = texture2D.GetLevelDescription(0).Height;

                while (tileWidth > 3200)
                {
                    tileWidth /= 2;
                    tileHeight /= 2;
                }

                int widthOffset = 0;
                int heightOffset = 0;

                while (widthOffset < texture2D.GetLevelDescription(0).Width)
                {
                    while (heightOffset < texture2D.GetLevelDescription(0).Height)
                    {
                        tiles.Push(new SharpDX.Rectangle(widthOffset, heightOffset, tileWidth, tileHeight));
                        heightOffset += tileHeight;
                    }

                    heightOffset = 0;
                    widthOffset += tileWidth;
                }

                int sc = 0;
                while (tiles.Count > 0)
                {
                    SharpDX.Rectangle rect = tiles.Pop();

                    byte[] data = new byte[rect.Width * rect.Height * 4];
                    SharpDX.Rectangle rect2 = new SharpDX.Rectangle(rect.X, rect.Y, rect.Width, rect.Height);
                    //texture2D.GetData<byte>(0, rect2, data, 0, data.Length);
                    DataStream ds;
                    texture2D.LockRectangle(0, rect2, LockFlags.None, out ds); 

                    ds.Read(data, 0, data.Length);
                            /*
                    for (int i = 0; i < data.Length; i += 4)
                    {
                        //Swap ARGB <-> RGBA
                        byte b = data[i + 0];
                        byte g = data[i + 1];
                        byte r = data[i + 2];
                        byte a = data[i + 3];
                        data[i + 0] = r;  //Blue
                        data[i + 1] = g; //Green
                        data[i + 2] = b; //Red
                        data[i + 3] = a; //Alpha
                    }         */

                    ds.Seek(0, SeekOrigin.Begin);
                    ds.WriteRange(data);

                    texture2D.UnlockRectangle(0);

                    string filename = file.Replace(".png", "_" + sc.ToString("##00") + ".png");
                    using (Stream stream = File.Create(filename))
                    {        
                        System.Drawing.Bitmap image = new System.Drawing.Bitmap(rect.Width, rect.Height);

                        System.Drawing.Imaging.BitmapData imageData = image.LockBits(new System.Drawing.Rectangle(0,0,rect.Width, rect.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                        System.Runtime.InteropServices.Marshal.Copy(data, 0, imageData.Scan0, data.Length);

                        image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);

                        image.UnlockBits(imageData);
                        image.Dispose();
                               
                        //texture2D.SaveAsPng(stream, texture2D.Width, texture2D.Height);
                        //BaseTexture.ToStream(texture2D, ImageFileFormat.Png);
                    }

                    sc++;
                    GC.Collect();
                }
            }
            catch (Exception exc)
            {
                //  Write exception to log, but continue as if nothing wrong happened
                MyMwcLog.WriteLine(exc);
            }

            texture2D.Dispose();

            //BaseTexture.ToFile(texture2D, "c:\\test.png", ImageFileFormat.Png);

            MyMwcLog.DecreaseIndent();
            MyMwcLog.WriteLine("MyScreenshot.SaveTexture2D() - END");   
        }
Exemplo n.º 18
0
 protected override void PostProcessTexture(Texture targetTexture)
 {
   if (_zapping)
   {
     // While zapping fill the current video frame with black. This avoids a frozen last frame from previous channel.
     using (Surface surface = targetTexture.GetSurfaceLevel(0))
       SkinContext.Device.ColorFill(surface, Color.Black);
   }
   else
     base.PostProcessTexture(targetTexture);
 }
Exemplo n.º 19
0
		protected void Blit( D3D9.Device d3d9Device, HardwarePixelBuffer rsrc, BasicBox srcBox, BasicBox dstBox,
		                     BufferResources srcBufferResources, BufferResources dstBufferResources )
		{
			if ( dstBufferResources.Surface != null && srcBufferResources.Surface != null )
			{
				// Surface-to-surface
				var dsrcRect = ToD3DRectangle( srcBox );
				var ddestRect = ToD3DRectangle( dstBox );

				var srcDesc = srcBufferResources.Surface.Description;

				// If we're blitting from a RTT, try GetRenderTargetData
				// if we're going to try to use GetRenderTargetData, need to use system mem pool

				// romeoxbm: not used even in Ogre
				//var tryGetRenderTargetData = false;

				if ( ( srcDesc.Usage & D3D9.Usage.RenderTarget ) != 0 && srcDesc.MultiSampleType == D3D9.MultisampleType.None )
				{
					// Temp texture
					var tmptex = new D3D9.Texture( d3d9Device, srcDesc.Width, srcDesc.Height, 1,
					                               // 1 mip level ie topmost, generate no mipmaps
					                               0, srcDesc.Format, D3D9.Pool.SystemMemory );

					var tmpsurface = tmptex.GetSurfaceLevel( 0 );

					if ( d3d9Device.GetRenderTargetData( srcBufferResources.Surface, tmpsurface ).Success )
					{
						// Hey, it worked
						// Copy from this surface instead
						var res = D3D9.Surface.FromSurface( dstBufferResources.Surface, tmpsurface, D3D9.Filter.Default, 0, dsrcRect,
						                                    ddestRect );
						if ( res.Failure )
						{
							tmpsurface.SafeDispose();
							tmptex.SafeDispose();
							throw new AxiomException( "D3D9.Surface.FromSurface failed in D3D9HardwarePixelBuffer.Blit" );
						}
						tmpsurface.SafeDispose();
						tmptex.SafeDispose();
						return;
					}
				}

				// Otherwise, try the normal method
				var res2 = D3D9.Surface.FromSurface( dstBufferResources.Surface, srcBufferResources.Surface, D3D9.Filter.Default, 0,
				                                     dsrcRect, ddestRect );
				if ( res2.Failure )
				{
					throw new AxiomException( "D3D9.Surface.FromSurface failed in D3D9HardwarePixelBuffer.Blit" );
				}
			}
			else if ( dstBufferResources.Volume != null && srcBufferResources.Volume != null )
			{
				// Volume-to-volume
				var dsrcBox = ToD3DBox( srcBox );
				var ddestBox = ToD3DBox( dstBox );

				var res = D3D9.Volume.FromVolume( dstBufferResources.Volume, srcBufferResources.Volume, D3D9.Filter.Default, 0,
				                                  dsrcBox, ddestBox );
				if ( res.Failure )
				{
					throw new AxiomException( "D3D9.Volume.FromVolume failed in D3D9HardwarePixelBuffer.Blit" );
				}
			}
			else
			{
				// Software fallback
				base.Blit( rsrc, srcBox, dstBox );
			}
		}
Exemplo n.º 20
0
        public static void Draw(bool draw = true)
        {
            RenderTimeInMS += MyRenderConstants.RENDER_STEP_IN_MILLISECONDS;

            MyPerformanceCounter.PerCameraDrawWrite.Reset();

            UpdateInterpolationLag();
            
            GetRenderProfiler().StartProfilingBlock("ProcessMessages");
            ProcessMessageQueue();
            GetRenderProfiler().EndProfilingBlock();

            if (draw)
            {
                Texture rt = null;
                Texture dt = null;

                if (m_screenshot != null)
                {
                    m_renderSetup.CallerID = MyRenderCallerEnum.Main;

                    Viewport viewport = MyRenderCamera.Viewport;
                    m_sizeMultiplierForStrings = m_screenshot.SizeMultiplier;

                    UpdateScreenSize();
                    MyEnvironmentMap.Reset();

                    MyRenderCamera.ChangeFov(MyRenderCamera.FieldOfView); // Refresh projection
                    MyRenderCamera.UpdateCamera();
                    MyRender.SetDeviceViewport(MyRenderCamera.Viewport);

                    CreateRenderTargets();
                    m_renderSetup.ShadowRenderer = MyRender.GetShadowRenderer();
                    //We need depth n stencil because stencil is used for drawing hud
                    rt = new Texture(GraphicsDevice, (int)(MyRenderCamera.Viewport.Width), (int)(MyRenderCamera.Viewport.Height), 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default);
                    dt = new Texture(GraphicsDevice, (int)(MyRenderCamera.Viewport.Width), (int)(MyRenderCamera.Viewport.Height), 1, Usage.DepthStencil, Format.D24S8, Pool.Default);
                    m_renderSetup.RenderTargets = new Texture[] { rt };
                    m_renderSetup.AspectRatio = MyRenderCamera.AspectRatio;
                    m_renderSetup.ProjectionMatrix = MyRenderCamera.ProjectionMatrix;

                    m_screenshot.DefaultSurface = rt.GetSurfaceLevel(0);
                    m_screenshot.DefaultDepth = dt.GetSurfaceLevel(0);

                    // To have render target with large size on device (screen.Draw calls MyCamera.EnableForward, which sets Viewport on device)
                    SetRenderTargets(m_renderSetup.RenderTargets, dt);
                    PushRenderSetupAndApply(m_renderSetup, ref m_backupRenderSetup);

                    m_backupRenderSetup.Viewport = viewport;
                }

                GetRenderProfiler().StartProfilingBlock("DrawMessageQueue");
                DrawMessageQueue();
                GetRenderProfiler().EndProfilingBlock();

                if (null != m_texturesToRender && m_texturesToRender.Count > 0)
                {
                    RenderColoredTextures();
                }

                if (m_screenshot != null)
                {                 
                    MyRender.PopRenderSetupAndRevert(m_backupRenderSetup);
                    
                    MyRender.TakeScreenshot("FinalScreen", GetScreenshotTexture(), Effects.MyEffectScreenshot.ScreenshotTechniqueEnum.Color);

                    var screen = m_screenshot;
                    m_screenshot = null; // Need to clear before SetRenderTarget(null, null)

                    SetRenderTarget(null, null);
                    MyRender.Blit(GetScreenshotTexture(), true, MyEffectScreenshot.ScreenshotTechniqueEnum.Color);

                    GetScreenshotTexture().Dispose();

                    screen.DefaultSurface.Dispose();
                    screen.DefaultDepth.Dispose();

                    rt.Dispose();
                    dt.Dispose();

                    MyRender.GraphicsDevice.Viewport = m_backupRenderSetup.Viewport.Value;
                    UpdateScreenSize();
                    MyRender.CreateRenderTargets();
                    MyEnvironmentMap.Reset();
                    RestoreDefaultTargets();
                    m_sizeMultiplierForStrings = Vector2.One;
                } 
            }

            GetRenderProfiler().StartProfilingBlock("ClearDrawMessages");
            ClearDrawMessages();
            GetRenderProfiler().EndProfilingBlock();

            if (m_spriteBatch != null)
                Debug.Assert(m_spriteBatch.ScissorStack.Empty);
        }
Exemplo n.º 21
0
        public void Init(SharpDX.Direct3D11.Texture2D sharedTexture)
        {
            logger.Debug("D3DRenderer::Setup()");

            if (state != RendererState.Closed)
            {
                throw new InvalidOperationException("Invalid capture state " + State);
            }

            try
            {
                var descr = sharedTexture.Description;
                logger.Verb(string.Join(", ", descr.Width + "x" + descr.Height, descr.Format));

                if (descr.Format != SharpDX.DXGI.Format.B8G8R8A8_UNorm)
                {
                    throw new InvalidOperationException("Invalid renderer state " + State);
                }

                direct3D = new Direct3DEx();

                var hWnd = NativeAPIs.User32.GetDesktopWindow();

                var presentParams = new PresentParameters
                {
                    //Windowed = true,
                    //SwapEffect = SharpDX.Direct3D9.SwapEffect.Discard,
                    //DeviceWindowHandle = IntPtr.Zero,
                    //PresentationInterval = SharpDX.Direct3D9.PresentInterval.Default
                    //BackBufferCount = 1,

                    Windowed        = true,
                    MultiSampleType = MultisampleType.None,
                    SwapEffect      = SwapEffect.Discard,
                    PresentFlags    = PresentFlags.None,
                };

                var flags = CreateFlags.HardwareVertexProcessing |
                            CreateFlags.Multithreaded |
                            CreateFlags.FpuPreserve;

                int adapterIndex = 0;

                device = new DeviceEx(direct3D, adapterIndex, DeviceType.Hardware, hWnd, flags, presentParams);

                using (var resource = sharedTexture.QueryInterface <SharpDX.DXGI.Resource>())
                {
                    var handle = resource.SharedHandle;

                    if (handle == IntPtr.Zero)
                    {
                        throw new ArgumentNullException(nameof(handle));
                    }

                    // D3DFMT_A8R8G8B8 или D3DFMT_X8R8G8B8
                    // D3DUSAGE_RENDERTARGET
                    // D3DPOOL_DEFAULT
                    using (var texture3d9 = new SharpDX.Direct3D9.Texture(device,
                                                                          descr.Width, descr.Height, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default,
                                                                          ref handle))
                    {
                        surface = texture3d9.GetSurfaceLevel(0);
                    };
                }

                this.texture2D11 = sharedTexture;
                var pSurface = surface.NativePointer;

                state = RendererState.Initialized;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Close();

                throw;
            }
        }
Exemplo n.º 22
0
        public static void SetRenderTarget(Texture rt, Texture depth, SetDepthTargetEnum depthOp = SetDepthTargetEnum.NoChange)
        {
            if (rt == null)
            {
                RestoreDefaultTargets();
            }
            else
            {
                Surface surface = rt.GetSurfaceLevel(0);
                MyMinerGame.Static.GraphicsDevice.SetRenderTarget(0, surface);
                surface.Dispose();
                MyMinerGame.Static.GraphicsDevice.SetRenderTarget(1, null);
                MyMinerGame.Static.GraphicsDevice.SetRenderTarget(2, null);
                if (depth != null)
                {
                    Surface dsurface = depth.GetSurfaceLevel(0);
                    MyMinerGame.Static.GraphicsDevice.DepthStencilSurface = dsurface;
                    dsurface.Dispose();
                }
                else if (depthOp == SetDepthTargetEnum.RestoreDefault)
                {
                    MyMinerGame.Static.GraphicsDevice.DepthStencilSurface = DefaultDepth;
                }

                m_renderTargetsCount = 1;
            }
        }
Exemplo n.º 23
0
 public static void SetRenderTargets(Texture[] rts, Texture depth, SetDepthTargetEnum depthOp = SetDepthTargetEnum.NoChange)
 {
     if (rts == null)
     {
         RestoreDefaultTargets();
     }
     else
     {
         for (int i = 0; i < 3; i++)
         {
             if (i < rts.Length)
             {
                 Surface surface = rts[i].GetSurfaceLevel(0);
                 MyMinerGame.Static.GraphicsDevice.SetRenderTarget(i, surface);
                 surface.Dispose();
             }
             else
                 MyMinerGame.Static.GraphicsDevice.SetRenderTarget(i, null);
         }
         if (depth != null)
         {
             Surface surface = depth.GetSurfaceLevel(0);
             MyMinerGame.Static.GraphicsDevice.DepthStencilSurface = surface;
             surface.Dispose();
         }
         else if (depthOp == SetDepthTargetEnum.RestoreDefault)
         {
             MyMinerGame.Static.GraphicsDevice.DepthStencilSurface = DefaultDepth;
         }
             
         m_renderTargetsCount = rts.Length;
     }
 }                                    
Exemplo n.º 24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="texture"></param>
        public void SetBackBuffer(Texture texture)
        {
            if (IsDisposed)
                throw new ObjectDisposedException(GetType().Name);

            Texture toDelete = null;
            try
            {
                if (texture != m_backBuffer)
                {
                    // if it's from the private (SDX9ImageSource) D3D9 device, dispose of it
                    if (m_backBuffer != null && m_backBuffer.Device.NativePointer == s_d3d9.Device.NativePointer)
                        toDelete = m_backBuffer;
                    m_backBuffer = texture;
                }

                if (texture != null)
                {
                    using (Surface surface = texture.GetSurfaceLevel(0))
                    {
                        Lock();
                        SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer);
                        AddDirtyRect(new Int32Rect(0, 0, base.PixelWidth, base.PixelHeight));
                        Unlock();
                    }
                }
                else
                {
                    Lock();
                    SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero);
                    AddDirtyRect(new Int32Rect(0, 0, base.PixelWidth, base.PixelHeight));
                    Unlock();
                }
            }
            finally
            {
                if (toDelete != null)
                {
                    toDelete.Dispose();
                }
            }
        }
Exemplo n.º 25
0
 /// <summary>
 /// コンストラクタです。
 /// </summary>
 /// <param name="texture"></param>
 /// <param name="pa"></param>
 public Texture(SharpDX.Direct3D9.Texture texture, bool pa)
 {
     this.pa  = pa;
     _Texture = texture;
     Surface  = new Surface(_Texture.GetSurfaceLevel(0));
 }
Exemplo n.º 26
0
        /// <summary>
        /// Associates an D3D11 render target with the current instance.
        /// </summary>
        /// <param name="renderTarget">An valid D3D11 render target. It must be created with the "Shared" flag.</param>
        internal void SetBackbuffer(Direct3D11.Texture2D renderTarget)
        {
            DisposedGuard();

            DisposeD3D9Backbuffer();

            using (var resource = renderTarget.QueryInterface<DXGI.Resource>())
            {
                var handle = resource.SharedHandle;
                texture = new Texture(device9,
                                      renderTarget.Description.Width,
                                      renderTarget.Description.Height,
                                      1,
                                      Usage.RenderTarget,
                                      Format.A8R8G8B8,
                                      Pool.Default,
                                      ref handle);
            }

            using (var surface = texture.GetSurfaceLevel(0))
                TrySetBackbufferPointer(surface.NativePointer);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Sets the back buffer of the <see cref="D3D11Image"/>.
        /// </summary>
        /// <param name="texture">The Direct3D 11 texture to be used as the back buffer.</param>
        public void SetBackBuffer(Texture2D texture)
        {
            ThrowIfDisposed();

            var previousBackBuffer = _backBuffer;

            // Create shared texture on Direct3D 9 device.
            _backBuffer = _d3D9.GetSharedTexture(texture);
            if (_backBuffer != null)
            {
                // Set texture as new back buffer.
                using (Surface surface = _backBuffer.GetSurfaceLevel(0))
                {
                    Lock();
                    SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer);
                    Unlock();
                }
            }
            else
            {
                // Reset back buffer.
                Lock();
                SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero);
                Unlock();                
            }

            if (previousBackBuffer != null)
                previousBackBuffer.Dispose();
        }
Exemplo n.º 28
0
        protected void BlitToMemory(BasicBox srcBox, PixelBox dst, BufferResources srcBufferResources, D3D9.Device d3d9Device)
        {
            // Decide on pixel format of temp surface
            PixelFormat tmpFormat = Format;

            if (D3D9Helper.ConvertEnum(dst.Format) != D3D9.Format.Unknown)
            {
                tmpFormat = dst.Format;
            }

            if (srcBufferResources.Surface != null)
            {
                Debug.Assert(srcBox.Depth == 1 && dst.Depth == 1);
                var srcDesc  = srcBufferResources.Surface.Description;
                var temppool = D3D9.Pool.Scratch;

                // if we're going to try to use GetRenderTargetData, need to use system mem pool
                var tryGetRenderTargetData = false;
                if (((srcDesc.Usage & D3D9.Usage.RenderTarget) != 0) && (srcBox.Width == dst.Width) &&
                    (srcBox.Height == dst.Height) && (srcBox.Width == Width) && (srcBox.Height == Height) &&
                    (Format == tmpFormat))
                {
                    tryGetRenderTargetData = true;
                    temppool = D3D9.Pool.SystemMemory;
                }

                // Create temp texture
                var tmp = new D3D9.Texture(d3d9Device, dst.Width, dst.Height, 1,                  // 1 mip level ie topmost, generate no mipmaps
                                           0, D3D9Helper.ConvertEnum(tmpFormat), temppool);

                var surface = tmp.GetSurfaceLevel(0);

                // Copy texture to this temp surface
                var srcRect  = ToD3DRectangle(srcBox);
                var destRect = ToD3DRectangle(dst);

                // Get the real temp surface format
                var dstDesc = surface.Description;
                tmpFormat = D3D9Helper.ConvertEnum(dstDesc.Format);

                // Use fast GetRenderTargetData if we are in its usage conditions
                var fastLoadSuccess = false;
                if (tryGetRenderTargetData)
                {
                    var result = d3d9Device.GetRenderTargetData(srcBufferResources.Surface, surface);
                    fastLoadSuccess = result.Success;
                }
                if (!fastLoadSuccess)
                {
                    var res = D3D9.Surface.FromSurface(surface, srcBufferResources.Surface, D3D9.Filter.Default, 0, srcRect, destRect);
                    if (res.Failure)
                    {
                        surface.SafeDispose();
                        tmp.SafeDispose();
                        throw new AxiomException("D3D9.Surface.FromSurface failed in D3D9HardwarePixelBuffer.BlitToMemory");
                    }
                }

                // Lock temp surface and copy it to memory
                var lrect = surface.LockRectangle(D3D9.LockFlags.ReadOnly);

                // Copy it
                var locked = new PixelBox(dst.Width, dst.Height, dst.Depth, tmpFormat);
                FromD3DLock(locked, lrect);
                PixelConverter.BulkPixelConversion(locked, dst);
                surface.UnlockRectangle();
                // Release temporary surface and texture
                surface.SafeDispose();
                tmp.SafeDispose();
            }
            else if (srcBufferResources.Volume != null)
            {
                // Create temp texture
                var tmp = new D3D9.VolumeTexture(d3d9Device, dst.Width, dst.Height, dst.Depth, 0, 0,
                                                 D3D9Helper.ConvertEnum(tmpFormat), D3D9.Pool.Scratch);

                var surface = tmp.GetVolumeLevel(0);

                // Volume
                var ddestBox = ToD3DBoxExtent(dst);
                var dsrcBox  = ToD3DBox(srcBox);

                var res = D3D9.Volume.FromVolume(surface, srcBufferResources.Volume, D3D9.Filter.Default, 0, dsrcBox, ddestBox);
                if (res.Failure)
                {
                    surface.SafeDispose();
                    tmp.SafeDispose();
                    throw new AxiomException("D3D9.Surface.FromVolume failed in D3D9HardwarePixelBuffer.BlitToMemory");
                }

                // Lock temp surface and copy it to memory
                var lbox = surface.LockBox(D3D9.LockFlags.ReadOnly);                   // Filled in by D3D

                // Copy it
                var locked = new PixelBox(dst.Width, dst.Height, dst.Depth, tmpFormat);
                FromD3DLock(locked, lbox);
                PixelConverter.BulkPixelConversion(locked, dst);
                surface.UnlockBox();
                // Release temporary surface and texture
                surface.SafeDispose();
                tmp.SafeDispose();
            }
        }
Exemplo n.º 29
0
		protected void BlitToMemory( BasicBox srcBox, PixelBox dst, BufferResources srcBufferResources, D3D9.Device d3d9Device )
		{
			// Decide on pixel format of temp surface
			PixelFormat tmpFormat = Format;
			if ( D3D9Helper.ConvertEnum( dst.Format ) != D3D9.Format.Unknown )
			{
				tmpFormat = dst.Format;
			}

			if ( srcBufferResources.Surface != null )
			{
				Debug.Assert( srcBox.Depth == 1 && dst.Depth == 1 );
				var srcDesc = srcBufferResources.Surface.Description;
				var temppool = D3D9.Pool.Scratch;

				// if we're going to try to use GetRenderTargetData, need to use system mem pool
				var tryGetRenderTargetData = false;
				if ( ( ( srcDesc.Usage & D3D9.Usage.RenderTarget ) != 0 ) && ( srcBox.Width == dst.Width ) &&
				     ( srcBox.Height == dst.Height ) && ( srcBox.Width == Width ) && ( srcBox.Height == Height ) &&
				     ( Format == tmpFormat ) )
				{
					tryGetRenderTargetData = true;
					temppool = D3D9.Pool.SystemMemory;
				}

				// Create temp texture
				var tmp = new D3D9.Texture( d3d9Device, dst.Width, dst.Height, 1, // 1 mip level ie topmost, generate no mipmaps
				                            0, D3D9Helper.ConvertEnum( tmpFormat ), temppool );

				var surface = tmp.GetSurfaceLevel( 0 );

				// Copy texture to this temp surface
				var srcRect = ToD3DRectangle( srcBox );
				var destRect = ToD3DRectangle( dst );

				// Get the real temp surface format
				var dstDesc = surface.Description;
				tmpFormat = D3D9Helper.ConvertEnum( dstDesc.Format );

				// Use fast GetRenderTargetData if we are in its usage conditions
				var fastLoadSuccess = false;
				if ( tryGetRenderTargetData )
				{
					var result = d3d9Device.GetRenderTargetData( srcBufferResources.Surface, surface );
					fastLoadSuccess = result.Success;
				}
				if ( !fastLoadSuccess )
				{
					var res = D3D9.Surface.FromSurface( surface, srcBufferResources.Surface, D3D9.Filter.Default, 0, srcRect, destRect );
					if ( res.Failure )
					{
						surface.SafeDispose();
						tmp.SafeDispose();
						throw new AxiomException( "D3D9.Surface.FromSurface failed in D3D9HardwarePixelBuffer.BlitToMemory" );
					}
				}

				// Lock temp surface and copy it to memory
				var lrect = surface.LockRectangle( D3D9.LockFlags.ReadOnly );

				// Copy it
				var locked = new PixelBox( dst.Width, dst.Height, dst.Depth, tmpFormat );
				FromD3DLock( locked, lrect );
				PixelConverter.BulkPixelConversion( locked, dst );
				surface.UnlockRectangle();
				// Release temporary surface and texture
				surface.SafeDispose();
				tmp.SafeDispose();
			}
			else if ( srcBufferResources.Volume != null )
			{
				// Create temp texture
				var tmp = new D3D9.VolumeTexture( d3d9Device, dst.Width, dst.Height, dst.Depth, 0, 0,
				                                  D3D9Helper.ConvertEnum( tmpFormat ), D3D9.Pool.Scratch );

				var surface = tmp.GetVolumeLevel( 0 );

				// Volume
				var ddestBox = ToD3DBoxExtent( dst );
				var dsrcBox = ToD3DBox( srcBox );

				var res = D3D9.Volume.FromVolume( surface, srcBufferResources.Volume, D3D9.Filter.Default, 0, dsrcBox, ddestBox );
				if ( res.Failure )
				{
					surface.SafeDispose();
					tmp.SafeDispose();
					throw new AxiomException( "D3D9.Surface.FromVolume failed in D3D9HardwarePixelBuffer.BlitToMemory" );
				}

				// Lock temp surface and copy it to memory
				var lbox = surface.LockBox( D3D9.LockFlags.ReadOnly ); // Filled in by D3D

				// Copy it
				var locked = new PixelBox( dst.Width, dst.Height, dst.Depth, tmpFormat );
				FromD3DLock( locked, lbox );
				PixelConverter.BulkPixelConversion( locked, dst );
				surface.UnlockBox();
				// Release temporary surface and texture
				surface.SafeDispose();
				tmp.SafeDispose();
			}
		}
Exemplo n.º 30
0
    public void Allocate(int width, int height, Usage usage, Format format)
    {
      bool free;
      lock (_syncObj)
        free = width != _size.Width || height != _size.Height || usage != _usage || format != _format;
      if (free)
        Free();
      lock (_syncObj)
      {
        if (_texture != null)
          return;

        _size.Width = width;
        _size.Height = height;
        _usage = usage;
        _format = format;

        // Note that it doesn't seem to be possible to create a texture with multisample surfaces inside. So rendering to that texture
        // won't provide multisample antialiasing.
        _texture = new Texture(GraphicsDevice.Device, width, height, 1, usage, format, Pool.Default);
        _surface0 = _texture.GetSurfaceLevel(0);

        SurfaceDescription desc = _texture.GetLevelDescription(0);
        _maxU = _size.Width/((float) desc.Width);
        _maxV = _size.Height/((float) desc.Height);
      }
      AllocationChanged(AllocationSize);
      KeepAlive();
    }
Exemplo n.º 31
0
 /// <summary>
 /// Constructs a <see cref="TemporaryRenderTarget"/> instance.
 /// </summary>
 /// <param name="renderTargetIndex">Render target index</param>
 /// <param name="targetTexture">Target texture to render on</param>
 public TemporaryRenderTarget(int renderTargetIndex, Texture targetTexture)
   : this(renderTargetIndex, targetTexture.GetSurfaceLevel(0))
 {
   _disposeSurface = true;
 }
Exemplo n.º 32
0
        public static string SaveScreenshot(Texture tex, string file)
        {
            MyRender.Log.WriteLine("MyScreenshot.SaveTexture2D() - START");
            MyRender.Log.IncreaseIndent();

            string filename = null;

            using (Texture systemTex = new Texture(MyRender.GraphicsDevice, tex.GetLevelDescription(0).Width, tex.GetLevelDescription(0).Height, 1, Usage.None, Format.A8R8G8B8, Pool.SystemMemory))
            {
                string extension = Path.GetExtension(file);

                using (Surface sourceSurface = tex.GetSurfaceLevel(0))
                using (Surface destSurface = systemTex.GetSurfaceLevel(0))
                {
                    MyRender.GraphicsDevice.GetRenderTargetData(sourceSurface, destSurface);
                }
                
                try
                {
                    MyRender.Log.WriteLine("File: " + file);

                    Stack<SharpDX.Rectangle> tiles = new Stack<SharpDX.Rectangle>();

                    int tileWidth = systemTex.GetLevelDescription(0).Width;
                    int tileHeight = systemTex.GetLevelDescription(0).Height;

                    while (tileWidth > 3200)
                    {
                        tileWidth /= 2;
                        tileHeight /= 2;
                    }

                    int widthOffset = 0;
                    int heightOffset = 0;

                    while (widthOffset < systemTex.GetLevelDescription(0).Width)
                    {
                        while (heightOffset < systemTex.GetLevelDescription(0).Height)
                        {
                            tiles.Push(new SharpDX.Rectangle(widthOffset, heightOffset, widthOffset + tileWidth, heightOffset + tileHeight));
                            heightOffset += tileHeight;
                        }

                        heightOffset = 0;
                        widthOffset += tileWidth;
                    }

                    bool multipleTiles = tiles.Count > 1;

                    int sc = 0;
                    byte[] data = new byte[tileWidth * tileHeight * 4];

                    int sysTexWidth = systemTex.GetLevelDescription(0).Width;
                    int sysTexHeight = systemTex.GetLevelDescription(0).Height;
                    while (tiles.Count > 0)
                    {
                        SharpDX.Rectangle rect = tiles.Pop();
                        //texture2D.GetData<byte>(0, rect2, data, 0, data.Length);
                        DataStream ds;
                        //DataRectangle dr = texture2D.LockRectangle(0, rect2, LockFlags.ReadOnly, out ds);
                        DataRectangle dr = systemTex.LockRectangle(0, LockFlags.ReadOnly, out ds);

                        //we have to go line by line..
                        ds.Seek(rect.Y * sysTexWidth * 4, SeekOrigin.Begin);
                        int targetOffset = 0;

                        int linesCount = tileHeight;

                        int pixelsBefore = rect.X;
                        int pixelsAfter = sysTexWidth - tileWidth - rect.X;

                        while (linesCount-- > 0)
                        {
                            if (pixelsBefore > 0)
                                ds.Seek(pixelsBefore * 4, SeekOrigin.Current);
                            
                            ds.Read(data, targetOffset, tileWidth * 4);
                            targetOffset += tileWidth * 4;
                            
                            if (pixelsAfter > 0 && linesCount > 0)
                                ds.Seek(pixelsAfter * 4, SeekOrigin.Current);
                        }

                        systemTex.UnlockRectangle(0);
                        filename = file;

                        if (multipleTiles)
                        {
                            filename = file.Replace(extension, "_" + sc.ToString("##00") + extension);
                        }

                        using (var stream = MyFileSystem.OpenWrite(MyFileSystem.UserDataPath, filename))
                        {
                            using (System.Drawing.Bitmap image = new System.Drawing.Bitmap(tileWidth, tileHeight))
                            {
                                System.Drawing.Imaging.BitmapData imageData = image.LockBits(new System.Drawing.Rectangle(0, 0, tileWidth, tileHeight), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                                System.Runtime.InteropServices.Marshal.Copy(data, 0, imageData.Scan0, data.Length);

                                if (extension == ".png")
                                    image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                                else if (extension == ".jpg" || extension == ".jpeg")
                                    image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                                else if (extension == ".bmp")
                                    image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
                                else
                                    throw new InvalidOperationException("Invalid file extension: " + extension + ", please use png, jpg or bmp");

                                image.UnlockBits(imageData);
                            }

                            //texture2D.SaveAsPng(stream, texture2D.Width, texture2D.Height);
                            //BaseTexture.ToStream(texture2D, ImageFileFormat.Png);
                        }

                        sc++;
                        GC.Collect();
                    }
                }
                catch (Exception exc)
                {
                    //  Write exception to log, but continue as if nothing wrong happened
                    MyRender.Log.WriteLine(exc);
                    filename = null;
                }
            }
            //BaseTexture.ToFile(texture2D, "c:\\test.png", ImageFileFormat.Png);

            MyRender.Log.DecreaseIndent();
            MyRender.Log.WriteLine("MyScreenshot.SaveTexture2D() - END");

            return filename;
        }