Пример #1
0
        public void DestroyD3DResources()
        {
            // FIXME: Ogre doesn't do this Dispose call here (just sets to null).
            if (renderSurface != null)
            {
                renderSurface.Dispose();
                renderSurface = null;
            }
            // renderSurface = null;

            if (isSwapChain)
            {
                if (renderZBuffer != null)
                {
                    renderZBuffer.Dispose();
                    renderZBuffer = null;
                }
                if (swapChain != null)
                {
                    swapChain.Dispose();
                    swapChain = null;
                }
            }
            else
            {
                // FIXME: Ogre doesn't do this Dispose call here (just sets to null).
                if (renderZBuffer != null)
                {
                    renderZBuffer.Dispose();
                    renderZBuffer = null;
                }
                // renderZBuffer = null;
            }
        }
        private bool Initialize(TextureManager manager, D3d.Format format, int size, bool mipmap,int multisample )
        {
            D3d.Pool d3dPool = D3d.Pool.Default;
            D3d.Usage d3dUsage = manager.GetUsageFlags( false,mipmap,true );

            try
            {
                d3dTexture = new D3d.CubeTexture( manager.Device.D3dDevice,size,manager.GetMipLevelCount(mipmap),d3dUsage,format,d3dPool);

                // Create depth buffer.
                d3dDepthBuffer = manager.Device.D3dDevice.CreateDepthStencilSurface(size, size, manager.Device.Settings.depthBufferFormat, (D3d.MultiSampleType)multisample, 0, true);

                this.Initialize(manager, format, size,size,6, d3dTexture);

                return true;
            }
            catch (D3d.InvalidCallException e)
            {
                log.Warning("Unable to create render cube texture: {0}", e.Message);
            }
            catch (D3d.OutOfVideoMemoryException e)
            {
                log.Warning("Unable to create render cube texture: {0}", e.Message);
            }
            catch (OutOfMemoryException e)
            {
                log.Warning("Unable to create render cube texture: {0}", e.Message);
            }

            return false;
        }
        private bool Initialize(TextureManager manager, D3d.Format format, int size, bool mipmap, int multisample)
        {
            D3d.Pool  d3dPool  = D3d.Pool.Default;
            D3d.Usage d3dUsage = manager.GetUsageFlags(false, mipmap, true);

            try
            {
                d3dTexture = new D3d.CubeTexture(manager.Device.D3dDevice, size, manager.GetMipLevelCount(mipmap), d3dUsage, format, d3dPool);

                // Create depth buffer.
                d3dDepthBuffer = manager.Device.D3dDevice.CreateDepthStencilSurface(size, size, manager.Device.Settings.depthBufferFormat, (D3d.MultiSampleType)multisample, 0, true);

                this.Initialize(manager, format, size, size, 6, d3dTexture);

                return(true);
            }
            catch (D3d.InvalidCallException e)
            {
                log.Warning("Unable to create render cube texture: {0}", e.Message);
            }
            catch (D3d.OutOfVideoMemoryException e)
            {
                log.Warning("Unable to create render cube texture: {0}", e.Message);
            }
            catch (OutOfMemoryException e)
            {
                log.Warning("Unable to create render cube texture: {0}", e.Message);
            }

            return(false);
        }
Пример #4
0
        void CreateTexture()
        {
            Size tsz = TextureSize();

            if (texture == null)
            {
                texture = TextureManager.Instance.GetByName(textureName);
            }
            if (texture != null)
            {
                log.InfoFormat("BrowserCodec[{0}]: Removing old texture \"{1}\"",
                               ID(), textureName);
                TextureManager.Instance.Remove(texture.Name);
                texture.Unload();
                texture = null;
                //d3dsurface = null;
            }
            texture = TextureManager.Instance.CreateManual(
                textureName,
                TextureType.TwoD,
                tsz.Width, tsz.Height,
                0, // no mip maps
                D3DHelper.ConvertEnum(D3D.Format.X8R8G8B8),
                TextureUsage.Dynamic);
            if (texture is D3DTexture)
            {
                D3D.Surface d3dsurface = ((texture as D3DTexture).DXTexture as D3D.Texture).GetSurfaceLevel(0);
                Graphics    g          = d3dsurface.GetGraphics();
                g.Clear(Color.Black);
                d3dsurface.ReleaseGraphics();
            }
        }
Пример #5
0
 public override D3d.Surface Lock(int surface)
 {
     if (!textureLock)
     {
         D3d.Surface lockedSurface = d3dTexture.GetCubeMapSurface((D3d.CubeMapFace)surface, 0);
         textureLock = true;
         return(lockedSurface);
     }
     return(null);
 }
 public override Microsoft.DirectX.Direct3D.Surface Lock(int surface)
 {
     if (!textureLock)
     {
         D3d.Surface lockedSurface = d3dTexture.GetSurfaceLevel(0);
         textureLock = true;
         return(lockedSurface);
     }
     return(null);
 }
Пример #7
0
 public D3DHardwarePixelBuffer(BufferUsage usage) :
     base(0, 0, 0, Axiom.Media.PixelFormat.Unknown, usage, false, false)
 {
     device      = null;
     surface     = null;
     volume      = null;
     tempSurface = null;
     tempVolume  = null;
     doMipmapGen = false;
     HWMipmaps   = false;
     mipTex      = null;
     sliceTRT    = new List <RenderTexture>();
 }
 /// <summary>
 /// Sets up the secondary blit buffer
 /// </summary>
 /// <param name="BufferSize">Size of the secondary buffer</param>
 /// <remarks>It is recommended that the Size be the same as the Front Buffer one's</remarks>
 public void SetUpBlitBuffer(Size BufferSize)
 {
     try
     {
         DisposeBlitBuffer();
         blit = display.CreateOffscreenPlainSurface(BufferSize.Width, BufferSize.Height, Format.A8R8G8B8, Pool.SystemMemory);
     }
     catch (Exception)
     {
         System.Windows.Forms.MessageBox.Show("Error creating Blit Buffer");
         throw;
     }
 }
 /// <summary>
 /// Sets up the front buffer
 /// </summary>
 /// <param name="BufferSize">Size of the buffer</param>
 public void SetUpFrontBuffer(Size BufferSize)
 {
     try
     {
         DisposeFrontBuffer();
         this.front = display.CreateRenderTarget(BufferSize.Width, BufferSize.Height, Format.A8R8G8B8, MultiSampleType.None, 0, true);
         display.SetRenderTarget(0, front);
     }
     catch (Exception)
     {
         System.Windows.Forms.MessageBox.Show("Error creating Front Buffer");
         throw;
     }
 }
Пример #10
0
        private void CreateBackBuffer()
        {
            if (mBackBuffer != null)
            {
                mBackBuffer.Dispose();
            }
            if (mSwap != null)
            {
                mSwap.Dispose();
            }

            mSwap = mDisplay.CreateSwapChain(this, mChooseWidth, mChooseHeight,
                                             mChooseBitDepth, mChooseFullscreen);
            mBackBuffer = mSwap.GetBackBuffer(0, BackBufferType.Mono);
        }
Пример #11
0
        ///<summary>
        ///    Call this to associate a D3D surface with this pixel buffer
        ///</summary>
        public void Bind(D3D.Device device, D3D.Surface surface, bool update)
        {
            this.device  = device;
            this.surface = surface;

            D3D.SurfaceDescription desc = surface.Description;
            width  = desc.Width;
            height = desc.Height;
            depth  = 1;
            format = D3DHelper.ConvertEnum(desc.Format);
            // Default
            rowPitch    = width;
            slicePitch  = height * width;
            sizeInBytes = PixelUtil.GetMemorySize(width, height, depth, format);

            if (((int)usage & (int)TextureUsage.RenderTarget) != 0)
            {
                CreateRenderTextures(update);
            }
        }
Пример #12
0
        /// <summary>
        /// Initializes the Composite buffer
        /// </summary>
        public void InitCompositeTexture()
        {
            DisposeComposite();

            try
            {
                Texture compositeScreen = new Texture(display, 512, Convert.ToInt32((Global.Configuration.Fonts.DescriptionSize + Global.Configuration.Fonts.LabelSize + 5) * 3f / 2f), 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default);
                this.CompositeScreen = new OrbitTexture(compositeScreen);
                this.CompositeScreen.GetReference();
                composite = CompositeScreen.Texture.GetSurfaceLevel(0);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message + "\n" + ex.StackTrace);
                try
                {
                    CompositeScreen.FreeReference();
                    CompositeScreen = null;
                }
                catch (Exception) {}
            }
        }
        public void Load(bool forceDynamic)
        {
            if (available && (!loaded || forceDynamic))
            {
                if( forceDynamic && textureName.Equals( "zero.png" ) )
                {
                    textureName = string.Format( "{0}_x{1}y{2}.{3}", parent.BaseName, m_tileLocationX, m_loadTileZ,
                                                 parent.MosaicDesc.FileExt );
                }

                // Attempt to load the texture.  If the texture
                // is already loaded, then this will just return the
                // already loaded texture, so no extra work will be done.

                Texture texture = TextureManager.Instance.GetByName(textureName);
                if (texture != null)
                {
                    if (forceDynamic)
                    {
                        if (texture.Usage == DYNAMIC_TEXTURE_USAGE)
                        {
                            loaded = true;
                            return;
                        }
                    }
                    texture.Unload();
                    texture = null;
                }

                if (dynamicSurface != null)
                {
                    dynamicSurface.Dispose();
                    dynamicSurface = null;
                }

                if (!forceDynamic)
                {
                    try
                    {
                        texture = TextureManager.Instance.Load(textureName);
                    } // ReSharper disable EmptyGeneralCatchClause
                    catch // ReSharper restore EmptyGeneralCatchClause
                    {
                        // Ignore
                    }
                }

                // If we failed to load the texture, manually create it
                if (texture == null) {
                    texture = TextureManager.Instance.CreateManual(textureName, TextureType.TwoD, parent.MosaicDesc.TileSizeSamples,
                        parent.MosaicDesc.TileSizeSamples, 0, DEFAULT_IMAGE_FORMAT, DYNAMIC_TEXTURE_USAGE);
                    texture.Load();
                    if (texture is D3DTexture)
                    {
                        D3D.Texture t = (texture as D3DTexture).DXTexture as D3D.Texture;
                        if (t != null)
                        {
                            dynamicSurface = t.Device.CreateOffscreenPlainSurface(texture.Width, texture.Height,
                                D3DHelper.ConvertEnum(texture.Format), D3D.Pool.Default);
                        }
                    }
                }

                loaded = true;
            }
        }
Пример #14
0
        /// <summary>
        /// Specifies the custom attribute by converting this to a string and passing to GetCustomAttribute()
        /// </summary>
        // public enum CustomAttribute { D3DDEVICE, D3DZBUFFER, D3DBACKBUFFER }

        public void CreateD3DResources()
        {
            // access device via driver
            Device device = driver.Device;

            if (isSwapChain && device == null)
            {
                throw new Exception("Secondary window has not been given the device from the primary!");
            }

            DeviceType devType = DeviceType.Hardware;

            presentParams            = new PresentParameters();
            presentParams.Windowed   = !isFullScreen;
            presentParams.SwapEffect = SwapEffect.Discard;
            // triple buffer if VSync is on
            presentParams.BackBufferCount           = isVSync ? 2 : 1;
            presentParams.EnableAutoDepthStencil    = isDepthBuffered;
            presentParams.DeviceWindow              = windowHandle;
            presentParams.BackBufferWidth           = width;
            presentParams.BackBufferHeight          = height;
            presentParams.FullScreenRefreshRateInHz = isFullScreen ? displayFrequency : 0;

            if (isVSync)
            {
                presentParams.PresentationInterval = PresentInterval.One;
            }
            else
            {
                // NB not using vsync in windowed mode in D3D9 can cause jerking at low
                // frame rates no matter what buffering modes are used (odd - perhaps a
                // timer issue in D3D9 since GL doesn't suffer from this)
                // low is < 200fps in this context
                if (!isFullScreen)
                {
                    log.Debug("Disabling VSync in windowed mode can cause timing issues at lower " +
                              "frame rates, turn VSync on if you observe this problem.");
                }
                presentParams.PresentationInterval = PresentInterval.Immediate;
            }

            presentParams.BackBufferFormat = Format.R5G6B5;
            if (colorDepth > 16)
            {
                presentParams.BackBufferFormat = Format.X8R8G8B8;
            }

            if (colorDepth > 16)
            {
                // Try to create a 32-bit depth, 8-bit stencil
                if (!D3D.Manager.CheckDeviceFormat(driver.AdapterNumber, devType,
                                                   presentParams.BackBufferFormat,
                                                   Usage.DepthStencil,
                                                   ResourceType.Surface, DepthFormat.D24S8))
                {
                    // Bugger, no 8-bit hardware stencil, just try 32-bit zbuffer
                    if (!D3D.Manager.CheckDeviceFormat(driver.AdapterNumber, devType,
                                                       presentParams.BackBufferFormat,
                                                       Usage.DepthStencil,
                                                       ResourceType.Surface, DepthFormat.D32))
                    {
                        // Jeez, what a naff card. Fall back on 16-bit depth buffering
                        presentParams.AutoDepthStencilFormat = DepthFormat.D16;
                    }
                    else
                    {
                        presentParams.AutoDepthStencilFormat = DepthFormat.D32;
                    }
                }
                else
                {
                    // Woohoo!
                    if (D3D.Manager.CheckDepthStencilMatch(driver.AdapterNumber, devType,
                                                           presentParams.BackBufferFormat,
                                                           presentParams.BackBufferFormat,
                                                           DepthFormat.D24S8))
                    {
                        presentParams.AutoDepthStencilFormat = DepthFormat.D24S8;
                    }
                    else
                    {
                        presentParams.AutoDepthStencilFormat = DepthFormat.D24X8;
                    }
                }
            }
            else
            {
                // 16-bit depth, software stencil
                presentParams.AutoDepthStencilFormat = DepthFormat.D16;
            }

            presentParams.MultiSample        = fsaaType;
            presentParams.MultiSampleQuality = fsaaQuality;

            if (isSwapChain)
            {
                swapChain = new SwapChain(device, presentParams);
                if (swapChain == null)
                {
                    // Try a second time, may fail the first time due to back buffer count,
                    // which will be corrected by the runtime
                    swapChain = new SwapChain(device, presentParams);
                }
                // Store references to buffers for convenience
                renderSurface = swapChain.GetBackBuffer(0, BackBufferType.Mono);
                // Additional swap chains need their own depth buffer
                // to support resizing them
                if (isDepthBuffered)
                {
                    renderZBuffer =
                        device.CreateDepthStencilSurface(width, height,
                                                         presentParams.AutoDepthStencilFormat,
                                                         presentParams.MultiSample,
                                                         presentParams.MultiSampleQuality,
                                                         false);
                }
                else
                {
                    renderZBuffer = null;
                }
                // Ogre releases the mpRenderSurface here (but not the mpRenderZBuffer)
                // release immediately so we don't hog them
                // mpRenderSurface->Release();
                // We'll need the depth buffer for rendering the swap chain
                // //mpRenderZBuffer->Release();
            }
            else
            {
                if (device == null)
                {
#if !USE_D3D_EVENTS
                    // Turn off default event handlers, since Managed DirectX seems confused.
                    Device.IsUsingEventHandlers = false;
#endif

                    // We haven't created the device yet, this must be the first time

                    // Do we want to preserve the FPU mode? Might be useful for scientific apps
                    CreateFlags extraFlags = 0;
                    if (multiThreaded)
                    {
                        extraFlags |= CreateFlags.MultiThreaded;
                    }
                    // TODO: query and preserve the fpu mode

                    // Set default settings (use the one Ogre discovered as a default)
                    int adapterToUse = driver.AdapterNumber;
                    if (useNVPerfHUD)
                    {
                        // Look for 'NVIDIA NVPerfHUD' adapter
                        // If it is present, override default settings
                        foreach (AdapterInformation identifier in D3D.Manager.Adapters)
                        {
                            log.Info("Device found: " + identifier.Information.Description);
                            if (identifier.Information.Description.Contains("PerfHUD"))
                            {
                                log.Info("Attempting to use PerfHUD");
                                adapterToUse = identifier.Adapter;
                                devType      = DeviceType.Reference;
                                break;
                            }
                        }
                    }

                    try
                    {
                        device = new D3D.Device(adapterToUse, devType, windowHandle,
                                                CreateFlags.HardwareVertexProcessing | extraFlags,
                                                presentParams);
                    }
                    catch (Exception) {
                        log.Info("First device creation failed");
                        try
                        {
                            // Try a second time, may fail the first time due to back buffer count,
                            // which will be corrected down to 1 by the runtime
                            device = new D3D.Device(adapterToUse, devType, windowHandle,
                                                    CreateFlags.HardwareVertexProcessing | extraFlags,
                                                    presentParams);
                        }
                        catch (Exception)
                        {
                            try
                            {
                                // Looks like we can't use HardwareVertexProcessing, so try Mixed
                                device = new D3D.Device(adapterToUse, devType, windowHandle,
                                                        CreateFlags.MixedVertexProcessing | extraFlags,
                                                        presentParams);
                            }
                            catch (Exception)
                            {
                                // Ok, one last try. Try software.  If this fails, just throw up.
                                device = new D3D.Device(adapterToUse, devType, windowHandle,
                                                        CreateFlags.SoftwareVertexProcessing | extraFlags,
                                                        presentParams);
                            }
                        }
                    }

                    // TODO: For a full screen app, I'm supposed to do this to prevent alt-tab
                    //       from messing things up.
                    //device.DeviceResizing += new
                    //    System.ComponentModel.CancelEventHandler(this.CancelResize);
                }
                log.InfoFormat("Device constructed with presentation parameters: {0}", presentParams.ToString());

                // update device in driver
                driver.Device = device;
                // Store references to buffers for convenience
                renderSurface = device.GetRenderTarget(0);
                renderZBuffer = device.DepthStencilSurface;
                // Ogre releases these here
                // release immediately so we don't hog them
                // mpRenderSurface->Release();
                // mpRenderZBuffer->Release();
            }
        }
Пример #15
0
        void FrameStarted(object source, FrameEventArgs e)
        {
            try {
                if (texture == null ||
                    !(texture is D3DTexture) ||
                    ((texture as D3DTexture).DXTexture) == null ||
                    ((texture as D3DTexture).DXTexture as D3D.Texture) == null)
                {
                    return;
                }
                D3D.Surface d3dsurface = ((texture as D3DTexture).DXTexture as D3D.Texture).GetSurfaceLevel(0);
                if (ps == PLAY_STATE.BUFFERING)
                {
                    if (browser == null)
                    {
                        browser = new Browser();
                        browser.SetObjectForScripting(scriptingObj);
                        browser.SetSize(VideoSize());
                        CreateTexture();
                        bool ans = browser.Open(path);
                        if (ans == false)
                        {
                            ps      = PLAY_STATE.STOPPED;
                            browser = null;
                        }
                    }

                    if (browser.Loaded())
                    {
                        Play();
                    }
                    else
                    {
                        Graphics g = d3dsurface.GetGraphics();
                        string   text;
                        int      pct = browser.LoadPercent();
                        if ((pct == 100) || (pct == 0))
                        {
                            text = string.Format("Loading ({0}%)", pct);
                        }
                        else
                        {
                            text = string.Format("Loading ({0:d2}%)", pct);
                        }
                        switch ((count++ / 10) % 3)
                        {
                        case 0:
                            text += ".";
                            break;

                        case 1:
                            text += "..";
                            break;

                        case 2:
                            text += "...";
                            break;
                        }
                        g.Clear(Color.Black);
                        g.DrawString(text, loadingFont, Brushes.White, loadingPoint);
                        d3dsurface.ReleaseGraphics();
                    }
                }
                if (ps == PLAY_STATE.RUNNING)
                {
                    Graphics g = d3dsurface.GetGraphics();
                    browser.RenderTo(g);
                    d3dsurface.ReleaseGraphics();
                }
            }
            catch (Exception exc) {
                log.WarnFormat("BrowserMovie.FrameStarted exception: {0}, stack trace {1}",
                               exc.Message, exc.StackTrace);
            }
        }
Пример #16
0
 public void UpdateSurface(Surface sourceSurface, Surface destinationSurface)
 {
     throw new NotImplementedException();
 }
Пример #17
0
 public void UpdateSurface(Surface sourceSurface, Rectangle sourceRect, Surface destinationSurface, Point destPoint)
 {
     throw new NotImplementedException();
 }
Пример #18
0
        /// <summary>
        /// Creates the texture as a render target.
        /// </summary>
        public Texture(Renderer renderer, int width, int height, bool alpha)
        {
            if (renderer == null)
                throw new ArgumentNullException("renderer",
                    "Unable to create texture without a valid renderer reference.");

            this.renderer = renderer;

            try
            {
                d3dTexture = new Microsoft.DirectX.Direct3D.Texture(renderer.Device,
                    width, height, 1, Usage.RenderTarget, alpha ? Format.A8R8G8B8 : Format.X8R8G8B8,
                    Pool.Default);

                d3dSurface = d3dTexture.GetSurfaceLevel(0);

                this.size = new Size(width, height);
                this.hasAlpha = alpha;

                loaded = true;

                renderer.AddGraphicsObject(this);
            }
            catch (Exception ex)
            {
                loaded = false;
                Log.Write("Failed to create texture as render target, will use empty texture!" +
                    " Error: " + ex.ToString());
            }
        }
Пример #19
0
 public void StretchRectangle(Surface sourceSurface, Rectangle sourceRectangle, Surface destSurface, Rectangle destRectangle, TextureFilter filter)
 {
     throw new NotImplementedException();
 }
        ///<summary>
        ///    Call this to associate a D3D surface with this pixel buffer
        ///</summary>
        public void Bind(D3D.Device device, D3D.Surface surface, bool update)
        {
            this.device = device;
            this.surface = surface;

            D3D.SurfaceDescription desc = surface.Description;
            width = desc.Width;
            height = desc.Height;
            depth = 1;
            format = D3DHelper.ConvertEnum(desc.Format);
            // Default
            rowPitch = width;
            slicePitch = height * width;
            sizeInBytes = PixelUtil.GetMemorySize(width, height, depth, format);

            if (((int)usage & (int)TextureUsage.RenderTarget) != 0)
                CreateRenderTextures(update);
        }
        public void RefreshTexture()
        {
            if (tileData != null && dirtyImage)
            {
                EnsureTextureIsDynamic(); // Unload texture & recreate if needed

                Texture texture = TextureManager.Instance.GetByName(textureName);
                if (texture == null)
                {
                    // We couldn't find the texture.  It might be that we're in
                    // the midst of swapping them at the DirectX level (this is
                    // only speculation)
                    return;
                }

                if (texture is D3DTexture)
                {
                    // Turns out that to get performance, not only did I have to go
                    // straight to DirectX, unsafe code is much faster as well.  What
                    // we're doing here is keeping a temporary surface around that we
                    // can lock and draw to at our leisure, then copying the surface
                    // over to the correct texture data when we're done.  To do this,
                    // the easiest way is to lock the desired rectangle on the temp
                    // surface, and get a graphics stream object back from it.  You
                    // might think you could then use byte arrays, or even ask for
                    // an Array of bytes back from LockRectangle, but not only was
                    // that slower, it also produced unpredictable results, possibly
                    // due to storing the array in row order vs. column order in the
                    // native vs. managed areas.
                    //
                    // The temporary surface is necessary because, well, I could
                    // never seem to acquire the lock on the real surface.  However,
                    // an offscreen plain surface (as used above) seems to lock fine.
                    //
                    // Next caveat: The pointer on the graphics stream points to the
                    // start of the row of the locked rectangle.  You'd be surprised
                    // how long it took me to figure that one out.  Further, it's
                    // important to use the pitch returned by LockRectangle to adjust
                    // your row array position, as the pitch may or may not be your
                    // surface width in bytes.  (Some drivers store extra data on the
                    // ends of the rows, it seems.)
                    Rectangle lockRect = new Rectangle();
                    lockRect.X      = dirtyArea.X;
                    lockRect.Y      = dirtyArea.Y;
                    lockRect.Width  = dirtyArea.Width;
                    lockRect.Height = dirtyArea.Height;

                    D3D.Texture       t = (texture as D3DTexture).DXTexture as D3D.Texture;
                    int               pitch;
                    int               bpp = PixelUtil.GetNumElemBytes(texture.Format);
                    D3D.Surface       dst = t.GetSurfaceLevel(0);
                    DX.GraphicsStream g   = dynamicSurface.LockRectangle(lockRect, D3D.LockFlags.NoSystemLock, out pitch);
                    unsafe
                    {
                        uint *dstArray = (uint *)g.InternalDataPointer;
                        pitch /= sizeof(uint);
                        for (int z = 0; z < lockRect.Height; z++)
                        {
                            for (int x = 0; x < lockRect.Width; x++)
                            {
                                uint data      = GetData(x + lockRect.X, z + lockRect.Y);
                                uint converted = ConvertPixel(data, INTERNAL_DATA_FORMAT, texture.Format);
                                dstArray[z * pitch + x] = converted;
                            }
                        }
                    }
                    dynamicSurface.UnlockRectangle();
                    D3D.SurfaceLoader.FromSurface(dst, dynamicSurface, D3D.Filter.None, 0);
                }
                else
                {
#if false
                    // following code is for blitting only the dirty rectangle
                    BasicBox destBox = new BasicBox(dirtyArea.X, dirtyArea.Y, dirtyArea.X + dirtyArea.Width,
                                                    dirtyArea.Y + dirtyArea.Height);
                    PixelBox srcPixel        = textureImage.GetPixelBox(0, 0);
                    BasicBox srcBox          = new BasicBox(0, 0, dirtyArea.Width, dirtyArea.Height);
                    PixelBox trimmedSrcPixel = srcPixel.GetSubVolume(srcBox);
                    buffer.BlitFromMemory(trimmedSrcPixel, destBox);
#endif
                }

                // Clean up dirty bit
                dirtyImage       = false;
                dirtyArea.X      = 0;
                dirtyArea.Y      = 0;
                dirtyArea.Width  = 0;
                dirtyArea.Height = 0;
            }
        }
        public void Load(bool forceDynamic)
        {
            if (available && (!loaded || forceDynamic))
            {
                if (forceDynamic && textureName.Equals("zero.png"))
                {
                    textureName = string.Format("{0}_x{1}y{2}.{3}", parent.BaseName, m_tileLocationX, m_loadTileZ,
                                                parent.MosaicDesc.FileExt);
                }

                // Attempt to load the texture.  If the texture
                // is already loaded, then this will just return the
                // already loaded texture, so no extra work will be done.

                Texture texture = TextureManager.Instance.GetByName(textureName);
                if (texture != null)
                {
                    if (forceDynamic)
                    {
                        if (texture.Usage == DYNAMIC_TEXTURE_USAGE)
                        {
                            loaded = true;
                            return;
                        }
                    }
                    texture.Unload();
                    texture = null;
                }

                if (dynamicSurface != null)
                {
                    dynamicSurface.Dispose();
                    dynamicSurface = null;
                }

                if (!forceDynamic)
                {
                    try
                    {
                        texture = TextureManager.Instance.Load(textureName);
                    } // ReSharper disable EmptyGeneralCatchClause
                    catch // ReSharper restore EmptyGeneralCatchClause
                    {
                        // Ignore
                    }
                }

                // If we failed to load the texture, manually create it
                if (texture == null)
                {
                    texture = TextureManager.Instance.CreateManual(textureName, TextureType.TwoD, parent.MosaicDesc.TileSizeSamples,
                                                                   parent.MosaicDesc.TileSizeSamples, 0, DEFAULT_IMAGE_FORMAT, DYNAMIC_TEXTURE_USAGE);
                    texture.Load();
                    if (texture is D3DTexture)
                    {
                        D3D.Texture t = (texture as D3DTexture).DXTexture as D3D.Texture;
                        if (t != null)
                        {
                            dynamicSurface = t.Device.CreateOffscreenPlainSurface(texture.Width, texture.Height,
                                                                                  D3DHelper.ConvertEnum(texture.Format), D3D.Pool.Default);
                        }
                    }
                }

                loaded = true;
            }
        }
Пример #23
0
        public override void Update()
        {
            D3D9RenderSystem rs = (D3D9RenderSystem)Root.Instance.RenderSystem;

            // access device through driver
            D3D.Device device = driver.Device;

            if (rs.DeviceLost)
            {
                log.Info("In D3DRenderWindow.Update, rs.DeviceLost is true");
                // Test the cooperative mode first
                int status;
                device.CheckCooperativeLevel(out status);
                if (status == (int)Microsoft.DirectX.Direct3D.ResultCode.DeviceLost)
                {
                    // device lost, and we can't reset
                    // can't do anything about it here, wait until we get
                    // D3DERR_DEVICENOTRESET; rendering calls will silently fail until
                    // then (except Present, but we ignore device lost there too)
                    // FIXME: Ogre doesn't do these two Dispose calls here.
#if NOT
                    // This code is what Ogre does for this clause, but since
                    // Ogre gets to immediately call release on the renderSurface
                    // and renderZBuffer, this assign of null will end up leaving
                    // the reference count at 0 for them, and will cause them to
                    // be freed.  For the Axiom code, I'm just going to leave them
                    // alone, and do the proper dispose calls in the devicenotreset
                    // clause.

                    renderSurface = null;
                    // need to release if swap chain
                    if (!isSwapChain)
                    {
                        renderZBuffer = null;
                    }
                    else
                    {
                        // Do I need to dispose of the ZBuffer here?
                        // SAFE_RELEASE (mpRenderZBuffer);
                        if (renderZBuffer != null)
                        {
                            renderZBuffer.Dispose();
                            renderZBuffer = null;
                        }
                    }
#endif
                    Thread.Sleep(50);
                    return;
                }
                else
                {
                    if (status != (int)Microsoft.DirectX.Direct3D.ResultCode.Success &&
                        status != (int)Microsoft.DirectX.Direct3D.ResultCode.DeviceNotReset)
                    {
                        // I've encountered some unexpected device state
                        // Ogre would just continue, but I want to make sure I notice this.
                        throw new Exception(string.Format("Unknown Device State: {0}", status));
                    }
                    // FIXME: Ogre doesn't do these two Dispose calls here.
                    if (renderSurface != null)
                    {
                        log.Info("Disposing of render surface");
                        renderSurface.Dispose();
                        renderSurface = null;
                    }
                    if (renderZBuffer != null)
                    {
                        log.Info("Disposing of render zbuffer");
                        renderZBuffer.Dispose();
                        renderZBuffer = null;
                    }

                    log.InfoFormat("In D3DRenderWindow.Update, calling rs.RestoreLostDevice(); status = {0}", status);
                    // device lost, and we can reset
                    rs.RestoreLostDevice();

                    // Still lost?
                    if (rs.DeviceLost)
                    {
                        // Wait a while
                        Thread.Sleep(50);
                        return;
                    }

                    if (!isSwapChain)
                    {
                        log.Info("In D3DRenderWindow.Update, re-querying buffers");
                        // re-qeuery buffers
                        renderSurface = device.GetRenderTarget(0);
                        renderZBuffer = device.DepthStencilSurface;
                        // release immediately so we don't hog them
                        // mpRenderSurface->Release();
                        // mpRenderZBuffer->Release();
                    }
                    else
                    {
                        log.Info("In D3DRenderWindow.Update, isSwapChain is true, changing viewport dimensions");
                        // Update dimensions incase changed
                        foreach (Axiom.Core.Viewport vp in viewportList)
                        {
                            vp.UpdateDimensions();
                        }
                        // Actual restoration of surfaces will happen in
                        // D3D9RenderSystem.RestoreLostDevice when it calls
                        // CreateD3DResources for each secondary window
                    }
                }
            }
            base.Update();
        }
Пример #24
0
        public void WindowMovedOrResized()
        {
            log.Info("D3DRenderWindow.WindowMovedOrResized called.");
            if (windowHandle == null)
            {
                return;
            }
            Form form = windowHandle.FindForm();

            if (form != null)
            {
                if (form.WindowState == FormWindowState.Minimized)
                {
                    return;
                }

                this.top  = form.DesktopLocation.Y;
                this.left = form.DesktopLocation.X;
            }

            if ((width == windowHandle.Size.Width) && (height == windowHandle.Size.Height))
            {
                return;
            }

            if (isSwapChain)
            {
                PresentParameters pp = new PresentParameters(presentParams);
                width  = windowHandle.Size.Width > 0 ? windowHandle.Size.Width : 1;
                height = windowHandle.Size.Height > 0 ? windowHandle.Size.Height : 1;
                if (presentParams.Windowed)
                {
                    pp.BackBufferWidth  = width;
                    pp.BackBufferHeight = height;
                }
                if (renderZBuffer != null)
                {
                    renderZBuffer.Dispose();
                    renderZBuffer = null;
                }
                if (swapChain != null)
                {
                    swapChain.Dispose();
                    swapChain = null;
                }
                if (renderSurface != null)
                {
                    renderSurface.Dispose();
                    renderSurface = null;
                }

                swapChain     = new SwapChain(driver.Device, pp);
                presentParams = pp;

                renderSurface = swapChain.GetBackBuffer(0, BackBufferType.Mono);
                renderZBuffer =
                    driver.Device.CreateDepthStencilSurface(presentParams.BackBufferWidth,
                                                            presentParams.BackBufferHeight,
                                                            presentParams.AutoDepthStencilFormat,
                                                            presentParams.MultiSample,
                                                            presentParams.MultiSampleQuality,
                                                            false);

                // TODO: Ogre releases here
                // renderSurface.Release();
            }
            else
            {
                // primary windows must reset the device
                width  = windowHandle.Size.Width > 0 ? windowHandle.Size.Width : 1;
                height = windowHandle.Size.Height > 0 ? windowHandle.Size.Height : 1;
                if (presentParams.Windowed)
                {
                    presentParams.BackBufferWidth  = width;
                    presentParams.BackBufferHeight = height;
                }
                D3D9RenderSystem renderSystem = (D3D9RenderSystem)Root.Instance.RenderSystem;
                renderSystem.NotifyDeviceLost();
            }
            // Notify viewports of resize
            foreach (Axiom.Core.Viewport viewport in viewportList)
            {
                viewport.UpdateDimensions();
            }
        }
Пример #25
0
 public void ColorFill(Surface surface, Rectangle rect, int color)
 {
     throw new NotImplementedException();
 }
Пример #26
0
 public void GetRenderTargetData(Surface renderTarget, Surface destSurface)
 {
     throw new NotImplementedException();
 }
Пример #27
0
        ///<summary>
        ///    @copydoc HardwarePixelBuffer.BlitToMemory
        ///</summary>
        public override void BlitToMemory(BasicBox srcBox, PixelBox dst)
        {
            // Decide on pixel format of temp surface
            PixelFormat tmpFormat = format;

            if (D3DHelper.ConvertEnum(dst.Format) == D3D.Format.Unknown)
            {
                tmpFormat = dst.Format;
            }
            if (surface != null)
            {
                Debug.Assert(srcBox.Depth == 1 && dst.Depth == 1);
                // Create temp texture
                D3D.Texture tmp =
                    new D3D.Texture(device, dst.Width, dst.Height,
                                    1, // 1 mip level ie topmost, generate no mipmaps
                                    0, D3DHelper.ConvertEnum(tmpFormat),
                                    Pool.Scratch);
                D3D.Surface subSurface = tmp.GetSurfaceLevel(0);
                // Copy texture to this temp surface
                Rectangle destRect, srcRect;
                srcRect  = ToD3DRectangle(srcBox);
                destRect = ToD3DRectangleExtent(dst);

                SurfaceLoader.FromSurface(subSurface, destRect, surface, srcRect, Filter.None, 0);

                // Lock temp surface and copy it to memory
                int            pitch; // Filled in by D3D
                GraphicsStream data = subSurface.LockRectangle(D3D.LockFlags.ReadOnly, out pitch);
                // Copy it
                PixelBox locked = new PixelBox(dst.Width, dst.Height, dst.Depth, tmpFormat);
                FromD3DLock(locked, pitch, data);
                PixelUtil.BulkPixelConversion(locked, dst);
                subSurface.UnlockRectangle();
                // Release temporary surface and texture
                subSurface.Dispose();
                tmp.Dispose();
            }
            else
            {
                // Create temp texture
                D3D.VolumeTexture tmp =
                    new D3D.VolumeTexture(device, dst.Width, dst.Height, dst.Depth,
                                          0, D3D.Usage.None,
                                          D3DHelper.ConvertEnum(tmpFormat),
                                          Pool.Scratch);
                D3D.Volume subVolume = tmp.GetVolumeLevel(0);
                // Volume
                D3D.Box ddestBox = ToD3DBoxExtent(dst);
                D3D.Box dsrcBox  = ToD3DBox(srcBox);

                VolumeLoader.FromVolume(subVolume, ddestBox, volume, dsrcBox, Filter.None, 0);
                // Lock temp surface and copy it to memory
                D3D.LockedBox  lbox;                // Filled in by D3D
                GraphicsStream data = subVolume.LockBox(LockFlags.ReadOnly, out lbox);
                // Copy it
                PixelBox locked = new PixelBox(dst.Width, dst.Height, dst.Depth, tmpFormat);
                FromD3DLock(locked, lbox, data);
                PixelUtil.BulkPixelConversion(locked, dst);
                subVolume.UnlockBox();
                // Release temporary surface and texture
                subVolume.Dispose();
                tmp.Dispose();
            }
        }
Пример #28
0
 public void GetFrontBufferData(int swapChain, Surface buffer)
 {
     throw new NotImplementedException();
 }
Пример #29
0
 public void SetRenderTarget(int renderTargetIndex, Surface renderTarget)
 {
     throw new NotImplementedException();
 }
Пример #30
0
        public virtual void Dispose()
        {
            if (d3dTexture != null)
                d3dTexture.Dispose();
            d3dTexture = null;

            if (d3dSurface != null)
                d3dSurface.Dispose();
            d3dSurface = null;

            loaded = false;
        }
        /// <summary>
        /// Specifies the custom attribute by converting this to a string and passing to GetCustomAttribute()
        /// </summary>
        // public enum CustomAttribute { D3DDEVICE, D3DZBUFFER, D3DBACKBUFFER }
        public void CreateD3DResources()
        {
            // access device via driver
            Device device = driver.Device;

            if (isSwapChain && device == null) {
                throw new Exception("Secondary window has not been given the device from the primary!");
            }

            DeviceType devType = DeviceType.Hardware;

            presentParams = new PresentParameters();
            presentParams.Windowed = !isFullScreen;
            presentParams.SwapEffect = SwapEffect.Discard;
            // triple buffer if VSync is on
            presentParams.BackBufferCount = isVSync ? 2 : 1;
            presentParams.EnableAutoDepthStencil = isDepthBuffered;
            presentParams.DeviceWindow = windowHandle;
            presentParams.BackBufferWidth = width;
            presentParams.BackBufferHeight = height;
            presentParams.FullScreenRefreshRateInHz = isFullScreen ? displayFrequency : 0;

            if (isVSync) {
                presentParams.PresentationInterval = PresentInterval.One;
            } else {
                // NB not using vsync in windowed mode in D3D9 can cause jerking at low
                // frame rates no matter what buffering modes are used (odd - perhaps a
                // timer issue in D3D9 since GL doesn't suffer from this)
                // low is < 200fps in this context
                if (!isFullScreen)
                    log.Debug("Disabling VSync in windowed mode can cause timing issues at lower " +
                              "frame rates, turn VSync on if you observe this problem.");
                presentParams.PresentationInterval = PresentInterval.Immediate;
            }

            presentParams.BackBufferFormat = Format.R5G6B5;
            if (colorDepth > 16)
                presentParams.BackBufferFormat = Format.X8R8G8B8;

            if (colorDepth > 16) {
                // Try to create a 32-bit depth, 8-bit stencil
                if (!D3D.Manager.CheckDeviceFormat(driver.AdapterNumber, devType,
                                                   presentParams.BackBufferFormat,
                                                   Usage.DepthStencil,
                                                   ResourceType.Surface, DepthFormat.D24S8)) {
                    // Bugger, no 8-bit hardware stencil, just try 32-bit zbuffer
                    if (!D3D.Manager.CheckDeviceFormat(driver.AdapterNumber, devType,
                                                      presentParams.BackBufferFormat,
                                                      Usage.DepthStencil,
                                                      ResourceType.Surface, DepthFormat.D32)) {
                        // Jeez, what a naff card. Fall back on 16-bit depth buffering
                        presentParams.AutoDepthStencilFormat = DepthFormat.D16;
                    } else
                        presentParams.AutoDepthStencilFormat = DepthFormat.D32;
                } else {
                    // Woohoo!
                    if (D3D.Manager.CheckDepthStencilMatch(driver.AdapterNumber, devType,
                                                           presentParams.BackBufferFormat,
                                                           presentParams.BackBufferFormat,
                                                           DepthFormat.D24S8)) {
                        presentParams.AutoDepthStencilFormat = DepthFormat.D24S8;
                    } else
                        presentParams.AutoDepthStencilFormat = DepthFormat.D24X8;
                }
            } else {
                // 16-bit depth, software stencil
                presentParams.AutoDepthStencilFormat = DepthFormat.D16;
            }

            presentParams.MultiSample = fsaaType;
            presentParams.MultiSampleQuality = fsaaQuality;

            if (isSwapChain) {
                swapChain = new SwapChain(device, presentParams);
                if (swapChain == null) {
               		    // Try a second time, may fail the first time due to back buffer count,
                    // which will be corrected by the runtime
                    swapChain = new SwapChain(device, presentParams);
                }
                // Store references to buffers for convenience
                renderSurface = swapChain.GetBackBuffer(0, BackBufferType.Mono);
             			// Additional swap chains need their own depth buffer
                // to support resizing them
                if (isDepthBuffered) {
                    renderZBuffer =
                        device.CreateDepthStencilSurface(width, height,
                                                         presentParams.AutoDepthStencilFormat,
                                                         presentParams.MultiSample,
                                                         presentParams.MultiSampleQuality,
                                                         false);
                } else {
                    renderZBuffer = null;
                }
                // Ogre releases the mpRenderSurface here (but not the mpRenderZBuffer)
                // release immediately so we don't hog them
                // mpRenderSurface->Release();
                // We'll need the depth buffer for rendering the swap chain
                // //mpRenderZBuffer->Release();
            } else {
                if (device == null) {
            #if !USE_D3D_EVENTS
                    // Turn off default event handlers, since Managed DirectX seems confused.
                    Device.IsUsingEventHandlers = false;
            #endif

                    // We haven't created the device yet, this must be the first time

                    // Do we want to preserve the FPU mode? Might be useful for scientific apps
                    CreateFlags extraFlags = 0;
                    if (multiThreaded) {
                        extraFlags |= CreateFlags.MultiThreaded;
                    }
                    // TODO: query and preserve the fpu mode

                    // Set default settings (use the one Ogre discovered as a default)
                    int adapterToUse = driver.AdapterNumber;
                    if (useNVPerfHUD) {
                        // Look for 'NVIDIA NVPerfHUD' adapter
                        // If it is present, override default settings
                        foreach (AdapterInformation identifier in D3D.Manager.Adapters) {
                            log.Info("Device found: " + identifier.Information.Description);
                            if (identifier.Information.Description.Contains("PerfHUD")) {
                                log.Info("Attempting to use PerfHUD");
                                adapterToUse = identifier.Adapter;
                                devType = DeviceType.Reference;
                                break;
                            }
                        }
                    }

                    try
                    {
                        device = new D3D.Device(adapterToUse, devType, windowHandle,
                                                CreateFlags.HardwareVertexProcessing | extraFlags,
                                                presentParams);
                    }
                    catch (Exception) {
                        log.Info("First device creation failed");
                        try
                        {
                            // Try a second time, may fail the first time due to back buffer count,
                            // which will be corrected down to 1 by the runtime
                            device = new D3D.Device(adapterToUse, devType, windowHandle,
                                                    CreateFlags.HardwareVertexProcessing | extraFlags,
                                                    presentParams);
                        }
                        catch (Exception)
                        {
                            try
                            {
                                // Looks like we can't use HardwareVertexProcessing, so try Mixed
                                device = new D3D.Device(adapterToUse, devType, windowHandle,
                                                        CreateFlags.MixedVertexProcessing | extraFlags,
                                                        presentParams);
                            }
                            catch (Exception)
                            {
                                // Ok, one last try. Try software.  If this fails, just throw up.
                                device = new D3D.Device(adapterToUse, devType, windowHandle,
                                                        CreateFlags.SoftwareVertexProcessing | extraFlags,
                                                        presentParams);
                            }
                        }
                    }

                    // TODO: For a full screen app, I'm supposed to do this to prevent alt-tab
                    //       from messing things up.
                    //device.DeviceResizing += new
                    //    System.ComponentModel.CancelEventHandler(this.CancelResize);

                }
                log.InfoFormat("Device constructed with presentation parameters: {0}", presentParams.ToString());

                // update device in driver
                driver.Device = device;
                // Store references to buffers for convenience
                renderSurface = device.GetRenderTarget(0);
                renderZBuffer = device.DepthStencilSurface;
                // Ogre releases these here
                // release immediately so we don't hog them
                // mpRenderSurface->Release();
                // mpRenderZBuffer->Release();
            }
        }
Пример #32
0
        /// <summary>
        /// Saves the current rendering to a screenshot file.
        /// </summary>
        /// <param name="filename">The name of the file to create or overwrite.</param>
        /// <param name="fileFormat">The image format of the image to create.</param>
        public void TakeScreenshot(string filename, D3D.ImageFileFormat fileFormat)
        {
            D3D.Surface buffer = _viewport.Device.GetBackBuffer(0, 0, D3D.BackBufferType.Mono);

            D3D.SurfaceLoader.Save(filename, fileFormat, buffer);
        }
        public void DestroyD3DResources()
        {
            // FIXME: Ogre doesn't do this Dispose call here (just sets to null).
            if (renderSurface != null) {
                renderSurface.Dispose();
                renderSurface = null;
            }
            // renderSurface = null;

            if (isSwapChain) {
                if (renderZBuffer != null) {
                    renderZBuffer.Dispose();
                    renderZBuffer = null;
                }
                if (swapChain != null) {
                    swapChain.Dispose();
                    swapChain = null;
                }
            } else {
                // FIXME: Ogre doesn't do this Dispose call here (just sets to null).
                if (renderZBuffer != null) {
                    renderZBuffer.Dispose();
                    renderZBuffer = null;
                }
                // renderZBuffer = null;
            }
        }
Пример #34
0
        /// <summary>
        /// Initializes all the Textures based on the configuration settings
        /// </summary>
        private void InitDeviceMem()
        {
            // generic quad vertex buffer
            try
            {
                int color = Color.White.ToArgb();
                this.GenericQuad = new VertexBuffer(typeof(CustomVertex.PositionColoredTextured), 4, display, Usage.Dynamic, CustomVertex.TransformedColoredTextured.Format, Pool.Default);
                Microsoft.DirectX.GraphicsStream       stm   = GenericQuad.Lock(0, 0, 0);
                CustomVertex.PositionColoredTextured[] verts = (CustomVertex.PositionColoredTextured[])GenericQuad.Lock(0, LockFlags.None);
                // Bottom left
                verts[0] = new CustomVertex.PositionColoredTextured(
                    new Vector3(
                        -0.5f,
                        0.5f,
                        0),
                    color,
                    0.0f,
                    1.0f);

                // Top left
                verts[1] = new CustomVertex.PositionColoredTextured(
                    new Vector3(
                        -0.5f,
                        -0.5f,
                        0),
                    color,
                    0.0f,
                    0.0f);

                // Bottom right
                verts[2] = new CustomVertex.PositionColoredTextured(
                    new Vector3(
                        0.5f,
                        0.5f,
                        0),
                    color,
                    1.0f,
                    1.0f);

                // Top right
                verts[3] = new CustomVertex.PositionColoredTextured(
                    new Vector3(
                        0.5f,
                        -0.5f,
                        0),
                    color,
                    1.0f,
                    0.0f);
                stm.Write(verts);
                GenericQuad.Unlock();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message + "\n" + ex.StackTrace);
                try
                {
                    GenericQuad.Unlock();
                }
                catch (Exception) {}
            }

            // font objects
            fntOut  = new Microsoft.DirectX.Direct3D.Font(display, new System.Drawing.Font(Global.Configuration.Fonts.LabelFont, Global.Configuration.Fonts.LabelSize, Global.Configuration.Fonts.LabelStyle));
            descOut = new Microsoft.DirectX.Direct3D.Font(display, new System.Drawing.Font(Global.Configuration.Fonts.DescriptionFont, Global.Configuration.Fonts.DescriptionSize, Global.Configuration.Fonts.DescriptionStyle));
#if DEBUG
            dbo = new Microsoft.DirectX.Direct3D.Font(display, new System.Drawing.Font("Tahoma", 10));
#endif

            // init Sprite painter
            SpritePainter = new Sprite(display);

            // get a pointer to the back buffer
            back = display.GetBackBuffer(0, 0, BackBufferType.Mono);

            // init composite texture
            InitCompositeTexture();

            // load bg only if is not using transparency
            if (Global.Configuration.Appearance.Transparency != Orbit.Configuration.TransparencyMode.Real)
            {
                // load the proper background provider
                if (Global.Configuration.Images.UseWindowsWallpaper)
                {
                    // init the wallpaper sync background provider
                    BGProvider = new WindowsBackgroundProvider(display, SpritePainter);
                    BGProvider.BackgroundColor = Global.Configuration.Images.BackgroundColor;
                }
                else
                {
                    // init the background provider
                    BGProvider = new BackgroundProvider(display, SpritePainter);
                    // assing bg image
                    if (Global.Configuration.Images.BackgroundImagePath != "")
                    {
                        BGProvider.BackgroundPath = Global.Configuration.Images.BackgroundImagePath;
                        // pass on the backgorund size
                        ImageInformation ii = Microsoft.DirectX.Direct3D.TextureLoader.ImageInformationFromFile(Global.Configuration.Images.BackgroundImagePath);
                        BGProvider.BackgroundSize = new Size(ii.Width, ii.Height);
                    }
                    // pass the background color
                    BGProvider.BackgroundColor = Color.FromArgb(0xFF, Global.Configuration.Images.BackgroundColor);
                }
            }

            // Load Icon Background
            if (Global.Configuration.Images.IconBackgroundImagePath != "")
            {
                SetIconBg(Global.Configuration.Images.IconBackgroundImagePath);
            }

            // Load Selected Icon overlay
            if (Global.Configuration.Images.IconSelectedImagePath != "")
            {
                SetIconSelected(Global.Configuration.Images.IconSelectedImagePath);
            }

            // load the scroll up image
            if (Global.Configuration.Images.ScrollUpImagePath != "")
            {
                SetScrollUp(Global.Configuration.Images.ScrollUpImagePath);
            }

            // load the scroll down image
            if (Global.Configuration.Images.ScrollDownImagePath != "")
            {
                SetScrollDown(Global.Configuration.Images.ScrollDownImagePath);
            }
        }
        public override void Update()
        {
            D3D9RenderSystem rs = (D3D9RenderSystem)Root.Instance.RenderSystem;

            // access device through driver
            D3D.Device device = driver.Device;

            if (rs.DeviceLost)
            {
                log.Info("In D3DRenderWindow.Update, rs.DeviceLost is true");
                // Test the cooperative mode first
                int status;
                device.CheckCooperativeLevel(out status);
                if (status == (int)Microsoft.DirectX.Direct3D.ResultCode.DeviceLost) {
                    // device lost, and we can't reset
                    // can't do anything about it here, wait until we get
                    // D3DERR_DEVICENOTRESET; rendering calls will silently fail until
                    // then (except Present, but we ignore device lost there too)
                    // FIXME: Ogre doesn't do these two Dispose calls here.
            #if NOT
                    // This code is what Ogre does for this clause, but since
                    // Ogre gets to immediately call release on the renderSurface
                    // and renderZBuffer, this assign of null will end up leaving
                    // the reference count at 0 for them, and will cause them to
                    // be freed.  For the Axiom code, I'm just going to leave them
                    // alone, and do the proper dispose calls in the devicenotreset
                    // clause.

                    renderSurface = null;
                    // need to release if swap chain
                    if (!isSwapChain) {
                        renderZBuffer = null;
                    } else {
                        // Do I need to dispose of the ZBuffer here?
                        // SAFE_RELEASE (mpRenderZBuffer);
                        if (renderZBuffer != null) {
                            renderZBuffer.Dispose();
                            renderZBuffer = null;
                        }
                    }
            #endif
                    Thread.Sleep(50);
                    return;
                } else {
                    if (status != (int)Microsoft.DirectX.Direct3D.ResultCode.Success &&
                        status != (int)Microsoft.DirectX.Direct3D.ResultCode.DeviceNotReset) {
                        // I've encountered some unexpected device state
                        // Ogre would just continue, but I want to make sure I notice this.
                        throw new Exception(string.Format("Unknown Device State: {0}", status));
                    }
                    // FIXME: Ogre doesn't do these two Dispose calls here.
                    if (renderSurface != null) {
                        log.Info("Disposing of render surface");
                        renderSurface.Dispose();
                        renderSurface = null;
                    }
                    if (renderZBuffer != null) {
                        log.Info("Disposing of render zbuffer");
                        renderZBuffer.Dispose();
                        renderZBuffer = null;
                    }

                    log.InfoFormat("In D3DRenderWindow.Update, calling rs.RestoreLostDevice(); status = {0}", status);
                    // device lost, and we can reset
                    rs.RestoreLostDevice();

                    // Still lost?
                    if (rs.DeviceLost) {
                        // Wait a while
                        Thread.Sleep(50);
                        return;
                    }

                    if (!isSwapChain) {
                        log.Info("In D3DRenderWindow.Update, re-querying buffers");
                        // re-qeuery buffers
                        renderSurface = device.GetRenderTarget(0);
                        renderZBuffer = device.DepthStencilSurface;
                        // release immediately so we don't hog them
                        // mpRenderSurface->Release();
                        // mpRenderZBuffer->Release();
                    } else {
                        log.Info("In D3DRenderWindow.Update, isSwapChain is true, changing viewport dimensions");
                        // Update dimensions incase changed
                        foreach (Axiom.Core.Viewport vp in viewportList)
                            vp.UpdateDimensions();
                        // Actual restoration of surfaces will happen in
                        // D3D9RenderSystem.RestoreLostDevice when it calls
                        // CreateD3DResources for each secondary window
                    }
                }
            }
            base.Update();
        }
Пример #36
0
 public void SetCursorProperties(int hotSpotX, int hotSpotY, Surface cursorBitmap)
 {
     throw new NotImplementedException();
 }
        public void WindowMovedOrResized()
        {
            log.Info("D3DRenderWindow.WindowMovedOrResized called.");
            if (windowHandle == null)
                return;
            Form form = windowHandle.FindForm();
            if (form != null) {
                if (form.WindowState == FormWindowState.Minimized)
                    return;

                this.top = form.DesktopLocation.Y;
                this.left = form.DesktopLocation.X;
            }

            if ((width == windowHandle.Size.Width) && (height == windowHandle.Size.Height))
                return;

            if (isSwapChain) {
                PresentParameters pp = new PresentParameters(presentParams);
                width = windowHandle.Size.Width > 0 ? windowHandle.Size.Width : 1;
                height = windowHandle.Size.Height > 0 ? windowHandle.Size.Height : 1;
                if (presentParams.Windowed)
                {
                    pp.BackBufferWidth = width;
                    pp.BackBufferHeight = height;
                }
                if (renderZBuffer != null) {
                    renderZBuffer.Dispose();
                    renderZBuffer = null;
                }
                if (swapChain != null) {
                    swapChain.Dispose();
                    swapChain = null;
                }
                if (renderSurface != null) {
                    renderSurface.Dispose();
                    renderSurface = null;
                }

                swapChain =  new SwapChain(driver.Device, pp);
                presentParams = pp;

                renderSurface = swapChain.GetBackBuffer(0, BackBufferType.Mono);
                renderZBuffer =
                    driver.Device.CreateDepthStencilSurface(presentParams.BackBufferWidth,
                                                            presentParams.BackBufferHeight,
                                                            presentParams.AutoDepthStencilFormat,
                                                            presentParams.MultiSample,
                                                            presentParams.MultiSampleQuality,
                                                            false);

                // TODO: Ogre releases here
                // renderSurface.Release();
            } else {
                // primary windows must reset the device
                width = windowHandle.Size.Width > 0 ? windowHandle.Size.Width : 1;
                height = windowHandle.Size.Height > 0 ? windowHandle.Size.Height : 1;
                if (presentParams.Windowed)
                {
                    presentParams.BackBufferWidth = width;
                    presentParams.BackBufferHeight = height;
                }
                D3D9RenderSystem renderSystem = (D3D9RenderSystem)Root.Instance.RenderSystem;
                renderSystem.NotifyDeviceLost();
            }
               		// Notify viewports of resize
            foreach (Axiom.Core.Viewport viewport in viewportList)
                viewport.UpdateDimensions();
        }
 public D3DHardwarePixelBuffer(BufferUsage usage)
     : base(0, 0, 0, Axiom.Media.PixelFormat.Unknown, usage, false, false)
 {
     device = null;
     surface = null;
     volume = null;
     tempSurface = null;
     tempVolume = null;
     doMipmapGen = false;
     HWMipmaps = false;
     mipTex = null;
     sliceTRT = new List<RenderTexture>();
 }
Пример #39
0
 /// <summary>
 /// Saves a copy of the render target so that it can be restored later.
 /// </summary>
 public void SaveRenderTarget()
 {
     savedRenderTarget = device.GetRenderTarget( 0 );
 }