예제 #1
0
        public PlaneScene(VMR9Util util)
        {
            //	Log.Info("PlaneScene: ctor()");

            _textureAddress = 0;
            _vmr9Util       = util;

            // Number of vertex buffers must be same as numer of segments in non-linear stretch
            _vertexBuffers = new VertexBuffer[nlsSourcePartitioning.Length];
            for (int i = 0; i < _vertexBuffers.Length; i++)
            {
                _vertexBuffers[i] = new VertexBuffer(typeof(CustomVertex.TransformedColoredTextured),
                                                     4,
                                                     GUIGraphicsContext.DX9Device,
                                                     0,
                                                     CustomVertex.TransformedColoredTextured.Format,
                                                     GUIGraphicsContext.GetTexturePoolType());
            }

            _blackImage = new GUIImage(0);
            _blackImage.SetFileName("black.png");
            _blackImage.AllocResources();

            _cropSettings = new CropSettings();
        }
예제 #2
0
 /// <summary>
 /// This method converts a GDI image to a DirectX Textures
 /// </summary>
 /// <param name="theImage">GDI Image</param>
 /// <param name="iWidth">width of returned texture</param>
 /// <param name="iHeight">height of returned texture</param>
 /// <returns>Texture with image or null if image could not be loaded</returns>
 public static Texture ConvertImageToTexture(Bitmap theImage, out int iWidth, out int iHeight)
 {
     iWidth  = 0;
     iHeight = 0;
     if (theImage == null)
     {
         return(null);
     }
     // Texture texture=null;
     try
     {
         Texture texture = null;
         using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
         {
             ImageInformation info2 = new ImageInformation();
             theImage.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
             stream.Flush();
             stream.Seek(0, System.IO.SeekOrigin.Begin);
             texture = TextureLoader.FromStream(
                 GUIGraphicsContext.DX9Device,
                 stream,
                 0, 0, //width/height
                 1,    //mipslevels
                 0,    //Usage.Dynamic,
                 Format.X8R8G8B8,
                 GUIGraphicsContext.GetTexturePoolType(),
                 Filter.None,
                 Filter.None,
                 (int)0,
                 ref info2);
             stream.Close();
             iWidth  = info2.Width;
             iHeight = info2.Height;
         }
         return(texture);
     }
     catch (Exception ex)
     {
         Log.Info("Picture.ConvertImageToTexture( {0}x{1} ) exception err:{2} stack:{3}",
                  iWidth, iHeight,
                  ex.Message, ex.StackTrace);
     }
     return(null);
 }
        private void CreateVertexBuffer(int wx, int wy, int wwidth, int wheight)
        {
            if (_vertexBuffer == null)
            {
                Usage usage = Usage.None;
                if (OSInfo.OSInfo.VistaOrLater())
                {
                    usage = Usage.Dynamic | Usage.WriteOnly;
                }
                _vertexBuffer = new VertexBuffer(typeof(CustomVertex.TransformedTextured),
                                                 4, GUIGraphicsContext.DX9Device,
                                                 usage,
                                                 CustomVertex.TransformedTextured.Format,
                                                 GUIGraphicsContext.GetTexturePoolType());
                _wx = _wy = _wwidth = _wheight = 0;
            }

            if (_wx != wx || _wy != wy || _wwidth != wwidth || _wheight != wheight)
            {
                CustomVertex.TransformedTextured[] verts = (CustomVertex.TransformedTextured[])_vertexBuffer.Lock(0, 0);

                // upper left
                verts[0] = new CustomVertex.TransformedTextured(wx, wy, 0, 1, 0, 0);

                // upper right
                verts[1] = new CustomVertex.TransformedTextured(wx + wwidth, wy, 0, 1, 1, 0);

                // lower left
                verts[2] = new CustomVertex.TransformedTextured(wx, wy + wheight, 0, 1, 0, 1);

                // lower right
                verts[3] = new CustomVertex.TransformedTextured(wx + wwidth, wy + wheight, 0, 1, 1, 1);

                _vertexBuffer.SetData(verts, 0, LockFlags.None);
                _vertexBuffer.Unlock();

                // remember what the vertexBuffer is set to
                _wy      = wy;
                _wx      = wx;
                _wheight = wheight;
                _wwidth  = wwidth;
            }
        }
예제 #4
0
        /// <summary>
        /// Creates a vertex buffer for a transformed textured quad matching
        /// the given rectangle and stores it in vertexBuffer
        /// </summary>
        /// <param name="wx"></param>
        /// <param name="wy"></param>
        /// <param name="wwidth"></param>
        /// <param name="wheight"></param>
        private void CreateVertexBuffer(int wx, int wy, int wwidth, int wheight)
        {
            if (_vertexBuffer == null)
            {
                Log.Debug("Subtitle: Creating vertex buffer");
                _vertexBuffer = new VertexBuffer(typeof(CustomVertex.TransformedTextured),
                                                 4, GUIGraphicsContext.DX9Device,
                                                 Usage.Dynamic | Usage.WriteOnly,
                                                 CustomVertex.TransformedTextured.Format,
                                                 GUIGraphicsContext.GetTexturePoolType());
                _wx = _wy = _wwidth = _wheight = 0;
            }

            if (_wx != wx || _wy != wy || _wwidth != wwidth || _wheight != wheight)
            {
                Log.Debug("Subtitle: Setting vertices");
                CustomVertex.TransformedTextured[] verts = (CustomVertex.TransformedTextured[])_vertexBuffer.Lock(0, 0);

                // upper left
                verts[0] = new CustomVertex.TransformedTextured(wx, wy, 0, 1, 0, 0);

                // upper right
                verts[1] = new CustomVertex.TransformedTextured(wx + wwidth, wy, 0, 1, 1, 0);

                // lower left
                verts[2] = new CustomVertex.TransformedTextured(wx, wy + wheight, 0, 1, 0, 1);

                // lower right
                verts[3] = new CustomVertex.TransformedTextured(wx + wwidth, wy + wheight, 0, 1, 1, 1);

                _vertexBuffer.SetData(verts, 0, LockFlags.None);

                // remember what the vertexBuffer is set to
                _wy      = wy;
                _wx      = wx;
                _wheight = wheight;
                _wwidth  = wwidth;
            }
        }
예제 #5
0
        private void LoadPackedGraphics(int index)
        {
            //	return ;
            PackedTexture bigOne    = _packedTextures[index];
            const Format  useFormat = Format.A8R8G8B8;

            //if (IsCompressedTextureFormatOk(Format.Dxt5))
            //{
            //    Log.Debug("TexturePacker: Using DXT5 texture format");
            //    useFormat = Format.Dxt5;
            //}
            if (bigOne.texture == null)
            {
                bigOne.textureNo = -1;

                string fileName = String.Format(@"{0}\packedgfx2{1}.png", GUIGraphicsContext.SkinCacheFolder, index);

                var     info2 = new ImageInformation();
                Texture tex   = TextureLoader.FromFile(GUIGraphicsContext.DX9Device,
                                                       fileName,
                                                       0, 0, //width/height
                                                       1,    //mipslevels
                                                       0,    //Usage.Dynamic,
                                                       useFormat,
                                                       GUIGraphicsContext.GetTexturePoolType(),
                                                       Filter.None,
                                                       Filter.None,
                                                       0,
                                                       ref info2);
                bigOne.texture            = tex;
                bigOne.texture.Disposing -= TextureDisposing;
                bigOne.texture.Disposing += TextureDisposing;

                Log.Info("TexturePacker: Loaded {0} texture:{1}x{2} miplevels:{3}", fileName, info2.Width, info2.Height,
                         tex.LevelCount);
            }
        }
예제 #6
0
        private static Texture LoadGraphic(string fileName, long lColorKey, int iMaxWidth, int iMaxHeight, out int width,
                                           out int height)
        {
            width  = 0;
            height = 0;
            Image   imgSrc  = null;
            Texture texture = null;

            try
            {
#if DO_RESAMPLE
                imgSrc = Image.FromFile(fileName);
                if (imgSrc == null)
                {
                    return(null);
                }
                //Direct3D prefers textures which height/width are a power of 2
                //doing this will increases performance
                //So the following core resamples all textures to
                //make sure all are 2x2, 4x4, 8x8, 16x16, 32x32, 64x64, 128x128, 256x256, 512x512
                int w = -1, h = -1;
                if (imgSrc.Width > 2 && imgSrc.Width < 4)
                {
                    w = 2;
                }
                if (imgSrc.Width > 4 && imgSrc.Width < 8)
                {
                    w = 4;
                }
                if (imgSrc.Width > 8 && imgSrc.Width < 16)
                {
                    w = 8;
                }
                if (imgSrc.Width > 16 && imgSrc.Width < 32)
                {
                    w = 16;
                }
                if (imgSrc.Width > 32 && imgSrc.Width < 64)
                {
                    w = 32;
                }
                if (imgSrc.Width > 64 && imgSrc.Width < 128)
                {
                    w = 64;
                }
                if (imgSrc.Width > 128 && imgSrc.Width < 256)
                {
                    w = 128;
                }
                if (imgSrc.Width > 256 && imgSrc.Width < 512)
                {
                    w = 256;
                }
                if (imgSrc.Width > 512 && imgSrc.Width < 1024)
                {
                    w = 512;
                }


                if (imgSrc.Height > 2 && imgSrc.Height < 4)
                {
                    h = 2;
                }
                if (imgSrc.Height > 4 && imgSrc.Height < 8)
                {
                    h = 4;
                }
                if (imgSrc.Height > 8 && imgSrc.Height < 16)
                {
                    h = 8;
                }
                if (imgSrc.Height > 16 && imgSrc.Height < 32)
                {
                    h = 16;
                }
                if (imgSrc.Height > 32 && imgSrc.Height < 64)
                {
                    h = 32;
                }
                if (imgSrc.Height > 64 && imgSrc.Height < 128)
                {
                    h = 64;
                }
                if (imgSrc.Height > 128 && imgSrc.Height < 256)
                {
                    h = 128;
                }
                if (imgSrc.Height > 256 && imgSrc.Height < 512)
                {
                    h = 256;
                }
                if (imgSrc.Height > 512 && imgSrc.Height < 1024)
                {
                    h = 512;
                }
                if (w > 0 || h > 0)
                {
                    if (h > w)
                    {
                        w = h;
                    }
                    Log.Info("TextureManager: resample {0}x{1} -> {2}x{3} {4}",
                             imgSrc.Width, imgSrc.Height, w, w, fileName);

                    Image imgResampled = Resample(imgSrc, w, h);
                    imgSrc.SafeDispose();
                    imgSrc       = imgResampled;
                    imgResampled = null;
                }
#endif

                Format fmt = Format.A8R8G8B8;

                ImageInformation info2 = new ImageInformation();

                texture = TextureLoader.FromFile(GUIGraphicsContext.DX9Device,
                                                 fileName,
                                                 0, 0, //width/height
                                                 1,    //mipslevels
                                                 0,    //Usage.Dynamic,
                                                 fmt,
                                                 GUIGraphicsContext.GetTexturePoolType(),
                                                 Filter.None,
                                                 Filter.None,
                                                 (int)lColorKey,
                                                 ref info2);
                width  = info2.Width;
                height = info2.Height;
            }
            catch (InvalidDataException e1) // weird : should have been FileNotFoundException when file is missing ??
            {
                //we need to catch this on higer level.
                throw e1;
            }
            catch (Exception)
            {
                Log.Error("TextureManager: LoadGraphic - invalid thumb({0})", fileName);
                Format fmt      = Format.A8R8G8B8;
                string fallback = GUIGraphicsContext.GetThemedSkinFile(@"\media\" + "black.png");

                ImageInformation info2 = new ImageInformation();
                texture = TextureLoader.FromFile(GUIGraphicsContext.DX9Device,
                                                 fallback,
                                                 0, 0, //width/height
                                                 1,    //mipslevels
                                                 0,    //Usage.Dynamic,
                                                 fmt,
                                                 GUIGraphicsContext.GetTexturePoolType(),
                                                 Filter.None,
                                                 Filter.None,
                                                 (int)lColorKey,
                                                 ref info2);
                width  = info2.Width;
                height = info2.Height;
            }
            finally
            {
                if (imgSrc != null)
                {
                    imgSrc.SafeDispose();
                }
            }
            return(texture);
        }
예제 #7
0
        public static int LoadFromMemory(Image memoryImage, string name, long lColorKey, int iMaxWidth, int iMaxHeight)
        {
            Log.Debug("TextureManager: load from memory: {0}", name);
            string cacheName = name;
            string cacheKey  = name.ToLowerInvariant();

            CachedTexture cached;

            if (_cacheTextures.TryGetValue(cacheKey, out cached))
            {
                return(cached.Frames);
            }

            if (memoryImage == null)
            {
                return(0);
            }
            if (memoryImage.FrameDimensionsList == null)
            {
                return(0);
            }
            if (memoryImage.FrameDimensionsList.Length == 0)
            {
                return(0);
            }

            try
            {
                CachedTexture newCache = new CachedTexture();

                newCache.Name = cacheName;
                FrameDimension oDimension = new FrameDimension(memoryImage.FrameDimensionsList[0]);
                newCache.Frames = memoryImage.GetFrameCount(oDimension);
                if (newCache.Frames != 1)
                {
                    return(0);
                }
                //load gif into texture
                using (MemoryStream stream = new MemoryStream())
                {
                    memoryImage.Save(stream, ImageFormat.Png);
                    ImageInformation info2 = new ImageInformation();
                    stream.Flush();
                    stream.Seek(0, SeekOrigin.Begin);
                    Texture texture = TextureLoader.FromStream(
                        GUIGraphicsContext.DX9Device,
                        stream,
                        0, 0, //width/height
                        1,    //mipslevels
                        0,    //Usage.Dynamic,
                        Format.A8R8G8B8,
                        GUIGraphicsContext.GetTexturePoolType(),
                        Filter.None,
                        Filter.None,
                        (int)lColorKey,
                        ref info2);
                    newCache.Width   = info2.Width;
                    newCache.Height  = info2.Height;
                    newCache.texture = new CachedTexture.Frame(cacheName, texture, 0);
                }
                memoryImage.SafeDispose();
                memoryImage        = null;
                newCache.Disposed += new EventHandler(cachedTexture_Disposed);

                _cacheTextures[cacheKey] = newCache;

                Log.Debug("TextureManager: added: memoryImage  " + " total count: " + _cacheTextures.Count + ", mem left (MB): " +
                          ((uint)GUIGraphicsContext.DX9Device.AvailableTextureMemory / 1048576));
                return(newCache.Frames);
            }
            catch (Exception ex)
            {
                Log.Error("TextureManager: exception loading texture memoryImage");
                Log.Error(ex);
            }
            return(0);
        }
예제 #8
0
        public static int Load(string fileNameOrg, long lColorKey, int iMaxWidth, int iMaxHeight, bool persistent)
        {
            string fileName = GetFileName(fileNameOrg);
            string cacheKey = fileName.ToLowerInvariant();

            if (String.IsNullOrEmpty(fileName))
            {
                return(0);
            }

            CachedTexture cached;

            if (_cacheTextures.TryGetValue(cacheKey, out cached))
            {
                return(cached.Frames);
            }

            string extension = Path.GetExtension(fileName).ToLowerInvariant();

            if (extension == ".gif")
            {
                Image theImage = null;
                try
                {
                    try
                    {
                        theImage = ImageFast.FromFile(fileName);
                    }
                    catch (FileNotFoundException)
                    {
                        Log.Warn("TextureManager: texture: {0} does not exist", fileName);
                        return(0);
                    }
                    catch (Exception)
                    {
                        Log.Warn("TextureManager: Fast loading texture {0} failed using safer fallback", fileName);
                        theImage = Image.FromFile(fileName);
                    }
                    if (theImage != null)
                    {
                        CachedTexture newCache = new CachedTexture();

                        newCache.Name = fileName;
                        FrameDimension oDimension = new FrameDimension(theImage.FrameDimensionsList[0]);
                        newCache.Frames = theImage.GetFrameCount(oDimension);
                        int[] frameDelay = new int[newCache.Frames];
                        for (int num2 = 0; (num2 < newCache.Frames); ++num2)
                        {
                            frameDelay[num2] = 0;
                        }

                        // Getting Frame duration of an animated Gif image
                        try
                        {
                            int          num1  = 20736;
                            PropertyItem item1 = theImage.GetPropertyItem(num1);
                            if (item1 != null)
                            {
                                byte[] buffer1 = item1.Value;
                                for (int num2 = 0; (num2 < newCache.Frames); ++num2)
                                {
                                    frameDelay[num2] = (((buffer1[(num2 * 4)] + (256 * buffer1[((num2 * 4) + 1)])) +
                                                         (65536 * buffer1[((num2 * 4) + 2)])) + (16777216 * buffer1[((num2 * 4) + 3)]));
                                }
                            }
                        }
                        catch (Exception) { }

                        for (int i = 0; i < newCache.Frames; ++i)
                        {
                            theImage.SelectActiveFrame(oDimension, i);

                            //load gif into texture
                            using (MemoryStream stream = new MemoryStream())
                            {
                                theImage.Save(stream, ImageFormat.Png);
                                ImageInformation info2 = new ImageInformation();
                                stream.Flush();
                                stream.Seek(0, SeekOrigin.Begin);
                                Texture texture = TextureLoader.FromStream(
                                    GUIGraphicsContext.DX9Device,
                                    stream,
                                    0, 0, //width/height
                                    1,    //mipslevels
                                    0,    //Usage.Dynamic,
                                    Format.A8R8G8B8,
                                    GUIGraphicsContext.GetTexturePoolType(),
                                    Filter.None,
                                    Filter.None,
                                    (int)lColorKey,
                                    ref info2);
                                newCache.Width  = info2.Width;
                                newCache.Height = info2.Height;
                                newCache[i]     = new CachedTexture.Frame(fileName, texture, (frameDelay[i] / 5) * 50);
                            }
                        }

                        theImage.SafeDispose();
                        theImage           = null;
                        newCache.Disposed += new EventHandler(cachedTexture_Disposed);
                        if (persistent && !_persistentTextures.ContainsKey(cacheKey))
                        {
                            _persistentTextures[cacheKey] = true;
                        }

                        _cacheTextures[cacheKey] = newCache;

                        //Log.Info("  TextureManager:added:" + fileName + " total:" + _cache.Count + " mem left:" + GUIGraphicsContext.DX9Device.AvailableTextureMemory.ToString());
                        return(newCache.Frames);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("TextureManager: exception loading texture {0} - {1}", fileName, ex.Message);
                }
                return(0);
            }

            try
            {
                int width, height;

                if (MediaPortal.Util.Utils.FileExistsInCache(fileName))
                {
                    Texture dxtexture = LoadGraphic(fileName, lColorKey, iMaxWidth, iMaxHeight, out width, out height);
                    if (dxtexture != null)
                    {
                        CachedTexture newCache = new CachedTexture();
                        newCache.Name    = fileName;
                        newCache.Frames  = 1;
                        newCache.Width   = width;
                        newCache.Height  = height;
                        newCache.texture = new CachedTexture.Frame(fileName, dxtexture, 0);
                        //Log.Info("  texturemanager:added:" + fileName + " total:" + _cache.Count + " mem left:" + GUIGraphicsContext.DX9Device.AvailableTextureMemory.ToString());
                        newCache.Disposed += new EventHandler(cachedTexture_Disposed);
                        if (persistent && !_persistentTextures.ContainsKey(cacheKey))
                        {
                            _persistentTextures[cacheKey] = true;
                        }

                        _cacheTextures[cacheKey] = newCache;
                        return(1);
                    }
                }
            }
            catch (Exception)
            {
                return(0);
            }
            return(0);
        }
예제 #9
0
        /// <summary>
        /// Callback from subtitle filter, alerting us that a new subtitle is available
        /// It receives the new subtitle as the argument sub, which data is only valid
        /// for the duration of OnSubtitle.
        /// </summary>
        /// <returns></returns>
        public int OnSubtitle(ref NATIVE_SUBTITLE sub)
        {
            if (!_useBitmap || !_renderSubtitles)
            {
                return(0);
                // TODO: Might be good to let this cache and then check in Render method because bitmap subs arrive a while before display
            }
            Log.Debug("OnSubtitle - stream position " + _player.StreamPosition);
            lock (_alert)
            {
                try
                {
                    Log.Debug("SubtitleRenderer:  Bitmap: bpp=" + sub.bmBitsPixel + " planes " + sub.bmPlanes + " dim = " +
                              sub.bmWidth + " x " + sub.bmHeight + " stride : " + sub.bmWidthBytes);
                    Log.Debug("SubtitleRenderer: to = " + sub.timeOut + " ts=" + sub.timeStamp + " fsl=" + sub.firstScanLine +
                              " h pos=" + sub.horizontalPosition + " (startPos = " + _startPos + ")");

                    Subtitle subtitle = new Subtitle();
                    subtitle.subBitmap          = new Bitmap(sub.bmWidth, sub.bmHeight, PixelFormat.Format32bppArgb);
                    subtitle.timeOut            = sub.timeOut;
                    subtitle.presentTime        = ((double)sub.timeStamp / 1000.0f) + _startPos; // compute present time in SECONDS
                    subtitle.height             = (uint)sub.bmHeight;
                    subtitle.width              = (uint)sub.bmWidth;
                    subtitle.screenHeight       = (uint)sub.screenHeight;
                    subtitle.screenWidth        = (uint)sub.screenWidth;
                    subtitle.firstScanLine      = sub.firstScanLine;
                    subtitle.horizontalPosition = sub.horizontalPosition;
                    subtitle.id = _subCounter++;
                    //Log.Debug("Received Subtitle : " + subtitle.ToString());

                    Texture texture = null;
                    try
                    {
                        // allocate new texture
                        texture = new Texture(GUIGraphicsContext.DX9Device, (int)subtitle.width, (int)subtitle.height, 1,
                                              Usage.Dynamic,
                                              Format.A8R8G8B8, GUIGraphicsContext.GetTexturePoolType());

                        if (texture == null)
                        {
                            Log.Debug("OnSubtitle: Failed to create new texture!");
                            return(0);
                        }

                        int pitch;
                        using (GraphicsStream a = texture.LockRectangle(0, LockFlags.Discard, out pitch))
                        {
                            // Quick copy of content
                            unsafe
                            {
                                byte *to   = (byte *)a.InternalDataPointer;
                                byte *from = (byte *)sub.bmBits;
                                for (int y = 0; y < sub.bmHeight; ++y)
                                {
                                    for (int x = 0; x < sub.bmWidth * 4; ++x)
                                    {
                                        to[pitch * y + x] = from[y * sub.bmWidthBytes + x];
                                    }
                                }
                            }
                            a.Close();
                        }

                        texture.UnlockRectangle(0);
                        subtitle.texture = texture;
                    }
                    catch (Exception)
                    {
                        Log.Debug("OnSubtitle: Failed to copy bitmap data!");
                        return(0);
                    }

                    AddSubtitle(subtitle);
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
            }
            return(0);
        }
예제 #10
0
        /// <summary>
        /// render the image contained in texture onscreen
        /// </summary>
        /// <param name="texture">Directx texture containing the image</param>
        /// <param name="x">x (left) coordinate</param>
        /// <param name="y">y (top) coordinate</param>
        /// <param name="nw">width </param>
        /// <param name="nh">height</param>
        /// <param name="iTextureWidth">width in texture</param>
        /// <param name="iTextureHeight">height in texture</param>
        /// <param name="iTextureLeft">x (left) offset in texture</param>
        /// <param name="iTextureTop">y (top) offset in texture</param>
        /// <param name="lColorDiffuse">diffuse color</param>
        //public static void RenderImage(ref Texture texture, float x, float y, float nw, float nh, float iTextureWidth, float iTextureHeight, float iTextureLeft, float iTextureTop, long lColorDiffuse)
        public static void RenderImage(Texture texture, float x, float y, float nw, float nh, float iTextureWidth,
                                       float iTextureHeight, float iTextureLeft, float iTextureTop, long lColorDiffuse)
        {
            if (texture == null)
            {
                return;
            }
            if (texture.Disposed)
            {
                return;
            }
            if (GUIGraphicsContext.DX9Device == null)
            {
                return;
            }
            if (GUIGraphicsContext.DX9Device.Disposed)
            {
                return;
            }

            if (x < 0 || y < 0)
            {
                return;
            }
            if (nw < 0 || nh < 0)
            {
                return;
            }
            if (iTextureWidth < 0 || iTextureHeight < 0)
            {
                return;
            }
            if (iTextureLeft < 0 || iTextureTop < 0)
            {
                return;
            }

            VertexBuffer m_vbBuffer = null;

            try
            {
                m_vbBuffer = new VertexBuffer(typeof(CustomVertex.TransformedColoredTextured),
                                              4, GUIGraphicsContext.DX9Device,
                                              0, CustomVertex.TransformedColoredTextured.Format,
                                              GUIGraphicsContext.GetTexturePoolType());

                Direct3D.SurfaceDescription desc;
                desc = texture.GetLevelDescription(0);

                float uoffs = ((float)iTextureLeft) / ((float)desc.Width);
                float voffs = ((float)iTextureTop) / ((float)desc.Height);
                float umax  = ((float)iTextureWidth) / ((float)desc.Width);
                float vmax  = ((float)iTextureHeight) / ((float)desc.Height);

                if (uoffs < 0 || uoffs > 1)
                {
                    return;
                }
                if (voffs < 0 || voffs > 1)
                {
                    return;
                }
                if (umax < 0 || umax > 1)
                {
                    return;
                }
                if (vmax < 0 || vmax > 1)
                {
                    return;
                }
                if (umax + uoffs < 0 || umax + uoffs > 1)
                {
                    return;
                }
                if (vmax + voffs < 0 || vmax + voffs > 1)
                {
                    return;
                }
                if (x < 0)
                {
                    x = 0;
                }
                if (x > GUIGraphicsContext.Width)
                {
                    x = GUIGraphicsContext.Width;
                }
                if (y < 0)
                {
                    y = 0;
                }
                if (y > GUIGraphicsContext.Height)
                {
                    y = GUIGraphicsContext.Height;
                }
                if (nw < 0)
                {
                    nw = 0;
                }
                if (nh < 0)
                {
                    nh = 0;
                }
                if (x + nw > GUIGraphicsContext.Width)
                {
                    nw = GUIGraphicsContext.Width - x;
                }
                if (y + nh > GUIGraphicsContext.Height)
                {
                    nh = GUIGraphicsContext.Height - y;
                }

                CustomVertex.TransformedColoredTextured[] verts =
                    (CustomVertex.TransformedColoredTextured[])m_vbBuffer.Lock(0, 0);
                // Lock the buffer (which will return our structs)
                verts[0].X     = x - 0.5f;
                verts[0].Y     = y + nh - 0.5f;
                verts[0].Z     = 0.0f;
                verts[0].Rhw   = 1.0f;
                verts[0].Color = (int)lColorDiffuse;
                verts[0].Tu    = uoffs;
                verts[0].Tv    = voffs + vmax;

                verts[1].X     = x - 0.5f;
                verts[1].Y     = y - 0.5f;
                verts[1].Z     = 0.0f;
                verts[1].Rhw   = 1.0f;
                verts[1].Color = (int)lColorDiffuse;
                verts[1].Tu    = uoffs;
                verts[1].Tv    = voffs;

                verts[2].X     = x + nw - 0.5f;
                verts[2].Y     = y + nh - 0.5f;
                verts[2].Z     = 0.0f;
                verts[2].Rhw   = 1.0f;
                verts[2].Color = (int)lColorDiffuse;
                verts[2].Tu    = uoffs + umax;
                verts[2].Tv    = voffs + vmax;

                verts[3].X     = x + nw - 0.5f;
                verts[3].Y     = y - 0.5f;
                verts[3].Z     = 0.0f;
                verts[3].Rhw   = 1.0f;
                verts[3].Color = (int)lColorDiffuse;
                verts[3].Tu    = uoffs + umax;
                verts[3].Tv    = voffs;


                m_vbBuffer.Unlock();

                GUIGraphicsContext.DX9Device.SetTexture(0, texture);

                DXNative.FontEngineSetTextureStageState(0, (int)D3DTEXTURESTAGESTATETYPE.D3DTSS_COLOROP, (int)D3DTEXTUREOP.D3DTOP_MODULATE);
                DXNative.FontEngineSetTextureStageState(0, (int)D3DTEXTURESTAGESTATETYPE.D3DTSS_COLORARG1, (int)D3DTA.D3DTA_TEXTURE);
                DXNative.FontEngineSetTextureStageState(0, (int)D3DTEXTURESTAGESTATETYPE.D3DTSS_COLORARG2, (int)D3DTA.D3DTA_DIFFUSE);
                DXNative.FontEngineSetTextureStageState(0, (int)D3DTEXTURESTAGESTATETYPE.D3DTSS_ALPHAOP, (int)D3DTEXTUREOP.D3DTOP_MODULATE);
                DXNative.FontEngineSetTextureStageState(0, (int)D3DTEXTURESTAGESTATETYPE.D3DTSS_ALPHAARG1, (int)D3DTA.D3DTA_TEXTURE);
                DXNative.FontEngineSetTextureStageState(0, (int)D3DTEXTURESTAGESTATETYPE.D3DTSS_ALPHAARG2, (int)D3DTA.D3DTA_DIFFUSE);


                DXNative.FontEngineSetTextureStageState(0, (int)D3DTEXTURESTAGESTATETYPE.D3DTSS_COLOROP, (int)D3DTEXTUREOP.D3DTOP_MODULATE);
                DXNative.FontEngineSetTextureStageState(0, (int)D3DTEXTURESTAGESTATETYPE.D3DTSS_COLORARG1, (int)D3DTA.D3DTA_TEXTURE);
                DXNative.FontEngineSetTextureStageState(0, (int)D3DTEXTURESTAGESTATETYPE.D3DTSS_COLORARG2, (int)D3DTA.D3DTA_DIFFUSE);

                DXNative.FontEngineSetTextureStageState(0, (int)D3DTEXTURESTAGESTATETYPE.D3DTSS_ALPHAOP, (int)D3DTEXTUREOP.D3DTOP_MODULATE);

                DXNative.FontEngineSetTextureStageState(0, (int)D3DTEXTURESTAGESTATETYPE.D3DTSS_ALPHAARG1, (int)D3DTA.D3DTA_TEXTURE);
                DXNative.FontEngineSetTextureStageState(0, (int)D3DTEXTURESTAGESTATETYPE.D3DTSS_ALPHAARG2, (int)D3DTA.D3DTA_DIFFUSE);

                DXNative.FontEngineSetTextureStageState(1, (int)D3DTEXTURESTAGESTATETYPE.D3DTSS_COLOROP, (int)D3DTEXTUREOP.D3DTOP_DISABLE);
                DXNative.FontEngineSetTextureStageState(1, (int)D3DTEXTURESTAGESTATETYPE.D3DTSS_ALPHAOP, (int)D3DTEXTUREOP.D3DTOP_DISABLE);

                int   g_nAnisotropy    = GUIGraphicsContext.DX9Device.DeviceCaps.MaxAnisotropy;
                float g_fMipMapLodBias = 0.0f;

                DXNative.FontEngineSetSamplerState(0, (int)D3DSAMPLERSTATETYPE.D3DSAMP_MINFILTER, (uint)D3DTEXTUREFILTERTYPE.D3DTEXF_LINEAR);
                DXNative.FontEngineSetSamplerState(0, (int)D3DSAMPLERSTATETYPE.D3DSAMP_MAGFILTER, (uint)D3DTEXTUREFILTERTYPE.D3DTEXF_LINEAR);
                DXNative.FontEngineSetSamplerState(0, (int)D3DSAMPLERSTATETYPE.D3DSAMP_MIPFILTER, (uint)D3DTEXTUREFILTERTYPE.D3DTEXF_LINEAR);
                DXNative.FontEngineSetSamplerState(0, (int)D3DSAMPLERSTATETYPE.D3DSAMP_MAXANISOTROPY, (uint)g_nAnisotropy);
                DXNative.FontEngineSetSamplerState(0, (int)D3DSAMPLERSTATETYPE.D3DSAMP_MIPMAPLODBIAS, (uint)g_fMipMapLodBias);

                DXNative.FontEngineSetSamplerState(1, (int)D3DSAMPLERSTATETYPE.D3DSAMP_MINFILTER, (int)D3DTEXTUREFILTERTYPE.D3DTEXF_LINEAR);
                DXNative.FontEngineSetSamplerState(1, (int)D3DSAMPLERSTATETYPE.D3DSAMP_MAGFILTER, (int)D3DTEXTUREFILTERTYPE.D3DTEXF_LINEAR);
                DXNative.FontEngineSetSamplerState(1, (int)D3DSAMPLERSTATETYPE.D3DSAMP_MIPFILTER, (int)D3DTEXTUREFILTERTYPE.D3DTEXF_LINEAR);
                DXNative.FontEngineSetSamplerState(1, (int)D3DSAMPLERSTATETYPE.D3DSAMP_MAXANISOTROPY, (uint)g_nAnisotropy);
                DXNative.FontEngineSetSamplerState(1, (int)D3DSAMPLERSTATETYPE.D3DSAMP_MIPMAPLODBIAS, (uint)g_fMipMapLodBias);

                // Render the image
                GUIGraphicsContext.DX9Device.SetStreamSource(0, m_vbBuffer, 0);
                GUIGraphicsContext.DX9Device.VertexFormat = CustomVertex.TransformedColoredTextured.Format;
                GUIGraphicsContext.DX9Device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);

                // unset the texture and palette or the texture caching crashes because the runtime still has a reference
                GUIGraphicsContext.DX9Device.SetTexture(0, null);
            }
            finally
            {
                if (m_vbBuffer != null)
                {
                    m_vbBuffer.SafeDispose();
                }
            }
        }
        private static void DrawTextUsingTexture(FontManagerDrawText draw, int fontSize)
        {
            bool textureCached  = false;
            int  cacheSlot      = 0;
            var  drawingTexture = new FontTexture();

            foreach (FontTexture cachedTexture in ListFontTextures)
            {
                if (cachedTexture.text == draw.Text && cachedTexture.size == fontSize)
                {
                    textureCached  = true;
                    drawingTexture = cachedTexture;
                    break;
                }
                cacheSlot++;
            }

            var size = new Size(0, 0);

            if (textureCached)
            {
                //keep commonly used textures at the top of the pile
                ListFontTextures.RemoveAt(cacheSlot);
                ListFontTextures.Add(drawingTexture);
            }
            else // texture needs to be cached
            {
                Texture texture = null;
                float   textwidth = 0, textheight = 0;

                MeasureText(draw.Text, ref textwidth, ref textheight, fontSize);
                size.Width  = (int)textwidth;
                size.Height = (int)textheight;

                try
                {
                    // The MemoryStream must be kept open for the lifetime of the bitmap
                    using (var imageStream = new MemoryStream())
                    {
                        using (var bitmap = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppArgb))
                        {
                            using (Graphics g = Graphics.FromImage(bitmap))
                            {
                                g.SmoothingMode     = SmoothingMode.AntiAlias;
                                g.TextRenderingHint = TextRenderingHint.AntiAlias;
                                g.TextContrast      = 0;
                                g.DrawString(draw.Text, CachedSystemFont(fontSize), Brushes.White, new Point(0, 0),
                                             StringFormat.GenericTypographic);

                                bitmap.Save(imageStream, ImageFormat.Bmp);

                                imageStream.Position = 0;
                                var format = Format.Dxt3;
                                if (GUIGraphicsContext.GetTexturePoolType() == Pool.Default)
                                {
                                    format = Format.Unknown;
                                }

                                var info = new ImageInformation();
                                try
                                {
                                    texture = TextureLoader.FromStream(GUIGraphicsContext.DX9Device,
                                                                       imageStream, (int)imageStream.Length,
                                                                       0, 0,
                                                                       1,
                                                                       0,
                                                                       format,
                                                                       GUIGraphicsContext.GetTexturePoolType(),
                                                                       Filter.None,
                                                                       Filter.None,
                                                                       0,
                                                                       ref info);
                                }
                                catch (OutOfVideoMemoryException oovme)
                                {
                                    Log.Error("GUIFontManager: OutOfVideoMemory in DrawTextUsingTexture - {0}", oovme.Message);
                                }
                                catch (OutOfMemoryException oome)
                                {
                                    Log.Error("GUIFontManager: OutOfMemory in DrawTextUsingTexture - {0}", oome.Message);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("GUIFontManager: Error in DrawTextUsingTexture - {0}", ex.Message);
                }

                MeasureText(draw.Text, ref textwidth, ref textheight, fontSize);
                size.Width  = (int)textwidth;
                size.Height = (int)textheight;

                var newTexture = new FontTexture {
                    text = draw.Text, texture = texture, size = fontSize
                };

                if (ListFontTextures.Count >= MaxCachedTextures)
                {
                    //need to clear this and not rely on the finalizer
                    FontTexture disposableFont = ListFontTextures[0];
                    ListFontTextures.RemoveAt(0);
                    disposableFont.Dispose();
                }
                ListFontTextures.Add(newTexture);
                drawingTexture = newTexture;
            }

            _sprite.Draw(drawingTexture.texture, new Rectangle(0, 0, size.Width, size.Height),
                         Vector3.Empty,
                         new Vector3((int)draw.Xpos, (int)draw.Ypos, 0), draw.Color);
        }
예제 #12
0
        /// <summary>
        /// render the image contained in texture onscreen
        /// </summary>
        /// <param name="texture">Directx texture containing the image</param>
        /// <param name="x">x (left) coordinate</param>
        /// <param name="y">y (top) coordinate</param>
        /// <param name="nw">width </param>
        /// <param name="nh">height</param>
        /// <param name="iTextureWidth">width in texture</param>
        /// <param name="iTextureHeight">height in texture</param>
        /// <param name="iTextureLeft">x (left) offset in texture</param>
        /// <param name="iTextureTop">y (top) offset in texture</param>
        /// <param name="lColorDiffuse">diffuse color</param>
        //public static void RenderImage(ref Texture texture, float x, float y, float nw, float nh, float iTextureWidth, float iTextureHeight, float iTextureLeft, float iTextureTop, long lColorDiffuse)
        public static void RenderImage(Texture texture, float x, float y, float nw, float nh, float iTextureWidth,
                                       float iTextureHeight, float iTextureLeft, float iTextureTop, long lColorDiffuse)
        {
            if (texture == null)
            {
                return;
            }
            if (texture.Disposed)
            {
                return;
            }
            if (GUIGraphicsContext.DX9Device == null)
            {
                return;
            }
            if (GUIGraphicsContext.DX9Device.Disposed)
            {
                return;
            }

            if (x < 0 || y < 0)
            {
                return;
            }
            if (nw < 0 || nh < 0)
            {
                return;
            }
            if (iTextureWidth < 0 || iTextureHeight < 0)
            {
                return;
            }
            if (iTextureLeft < 0 || iTextureTop < 0)
            {
                return;
            }

            VertexBuffer m_vbBuffer = null;

            try
            {
                m_vbBuffer = new VertexBuffer(typeof(CustomVertex.TransformedColoredTextured),
                                              4, GUIGraphicsContext.DX9Device,
                                              0, CustomVertex.TransformedColoredTextured.Format,
                                              GUIGraphicsContext.GetTexturePoolType());

                Direct3D.SurfaceDescription desc;
                desc = texture.GetLevelDescription(0);

                float uoffs = ((float)iTextureLeft) / ((float)desc.Width);
                float voffs = ((float)iTextureTop) / ((float)desc.Height);
                float umax  = ((float)iTextureWidth) / ((float)desc.Width);
                float vmax  = ((float)iTextureHeight) / ((float)desc.Height);

                if (uoffs < 0 || uoffs > 1)
                {
                    return;
                }
                if (voffs < 0 || voffs > 1)
                {
                    return;
                }
                if (umax < 0 || umax > 1)
                {
                    return;
                }
                if (vmax < 0 || vmax > 1)
                {
                    return;
                }
                if (umax + uoffs < 0 || umax + uoffs > 1)
                {
                    return;
                }
                if (vmax + voffs < 0 || vmax + voffs > 1)
                {
                    return;
                }
                if (x < 0)
                {
                    x = 0;
                }
                if (x > GUIGraphicsContext.Width)
                {
                    x = GUIGraphicsContext.Width;
                }
                if (y < 0)
                {
                    y = 0;
                }
                if (y > GUIGraphicsContext.Height)
                {
                    y = GUIGraphicsContext.Height;
                }
                if (nw < 0)
                {
                    nw = 0;
                }
                if (nh < 0)
                {
                    nh = 0;
                }
                if (x + nw > GUIGraphicsContext.Width)
                {
                    nw = GUIGraphicsContext.Width - x;
                }
                if (y + nh > GUIGraphicsContext.Height)
                {
                    nh = GUIGraphicsContext.Height - y;
                }

                CustomVertex.TransformedColoredTextured[] verts =
                    (CustomVertex.TransformedColoredTextured[])m_vbBuffer.Lock(0, 0);
                // Lock the buffer (which will return our structs)
                verts[0].X     = x - 0.5f;
                verts[0].Y     = y + nh - 0.5f;
                verts[0].Z     = 0.0f;
                verts[0].Rhw   = 1.0f;
                verts[0].Color = (int)lColorDiffuse;
                verts[0].Tu    = uoffs;
                verts[0].Tv    = voffs + vmax;

                verts[1].X     = x - 0.5f;
                verts[1].Y     = y - 0.5f;
                verts[1].Z     = 0.0f;
                verts[1].Rhw   = 1.0f;
                verts[1].Color = (int)lColorDiffuse;
                verts[1].Tu    = uoffs;
                verts[1].Tv    = voffs;

                verts[2].X     = x + nw - 0.5f;
                verts[2].Y     = y + nh - 0.5f;
                verts[2].Z     = 0.0f;
                verts[2].Rhw   = 1.0f;
                verts[2].Color = (int)lColorDiffuse;
                verts[2].Tu    = uoffs + umax;
                verts[2].Tv    = voffs + vmax;

                verts[3].X     = x + nw - 0.5f;
                verts[3].Y     = y - 0.5f;
                verts[3].Z     = 0.0f;
                verts[3].Rhw   = 1.0f;
                verts[3].Color = (int)lColorDiffuse;
                verts[3].Tu    = uoffs + umax;
                verts[3].Tv    = voffs;


                m_vbBuffer.Unlock();

                GUIGraphicsContext.DX9Device.SetTexture(0, texture);

                GUIGraphicsContext.DX9Device.TextureState[0].ColorOperation = Direct3D.TextureOperation.Modulate;
                GUIGraphicsContext.DX9Device.TextureState[0].ColorArgument1 = Direct3D.TextureArgument.TextureColor;
                GUIGraphicsContext.DX9Device.TextureState[0].ColorArgument2 = Direct3D.TextureArgument.Diffuse;

                GUIGraphicsContext.DX9Device.TextureState[0].AlphaOperation = Direct3D.TextureOperation.Modulate;

                GUIGraphicsContext.DX9Device.TextureState[0].AlphaArgument1 = Direct3D.TextureArgument.TextureColor;
                GUIGraphicsContext.DX9Device.TextureState[0].AlphaArgument2 = Direct3D.TextureArgument.Diffuse;
                GUIGraphicsContext.DX9Device.TextureState[1].ColorOperation = Direct3D.TextureOperation.Disable;
                GUIGraphicsContext.DX9Device.TextureState[1].AlphaOperation = Direct3D.TextureOperation.Disable;

                int   g_nAnisotropy    = GUIGraphicsContext.DX9Device.DeviceCaps.MaxAnisotropy;
                float g_fMipMapLodBias = 0.0f;
                GUIGraphicsContext.DX9Device.SamplerState[0].MinFilter               = TextureFilter.Linear;
                GUIGraphicsContext.DX9Device.SamplerState[0].MagFilter               = TextureFilter.Linear;
                GUIGraphicsContext.DX9Device.SamplerState[0].MipFilter               = TextureFilter.Linear;
                GUIGraphicsContext.DX9Device.SamplerState[0].MaxAnisotropy           = g_nAnisotropy;
                GUIGraphicsContext.DX9Device.SamplerState[0].MipMapLevelOfDetailBias = g_fMipMapLodBias;

                GUIGraphicsContext.DX9Device.SamplerState[1].MinFilter               = TextureFilter.Linear;
                GUIGraphicsContext.DX9Device.SamplerState[1].MagFilter               = TextureFilter.Linear;
                GUIGraphicsContext.DX9Device.SamplerState[1].MipFilter               = TextureFilter.Linear;
                GUIGraphicsContext.DX9Device.SamplerState[1].MaxAnisotropy           = g_nAnisotropy;
                GUIGraphicsContext.DX9Device.SamplerState[1].MipMapLevelOfDetailBias = g_fMipMapLodBias;

                // Render the image
                GUIGraphicsContext.DX9Device.SetStreamSource(0, m_vbBuffer, 0);
                GUIGraphicsContext.DX9Device.VertexFormat = CustomVertex.TransformedColoredTextured.Format;
                GUIGraphicsContext.DX9Device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);

                // unset the texture and palette or the texture caching crashes because the runtime still has a reference
                GUIGraphicsContext.DX9Device.SetTexture(0, null);
            }
            finally
            {
                if (m_vbBuffer != null)
                {
                    m_vbBuffer.SafeDispose();
                }
            }
        }