Example #1
0
        internal void BitmapData(ref BitmapResource pResource, int pResolution)
        {
            if (!_updateBitmap)
            {
                return;
            }

            var memory = new byte[pResolution * pResolution * 4];
            var step   = (int)Math.Floor((double)Size / pResolution);

            for (int x = 0; x < pResolution; x++)
            {
                for (int y = 0; y < pResolution; y++)
                {
                    var i     = (pResolution * 4 * y + x * 4);
                    var color = GetBrush(x * step, y * step).Color;
                    memory[i]     = color.B;
                    memory[i + 1] = color.G;
                    memory[i + 2] = color.R;
                    memory[i + 3] = color.A;
                }
            }

            if (pResource != null)
            {
                pResource.Dispose();
            }
            pResource     = ((DirectXGraphicSystem)Game.Graphics).FromByte(memory, pResolution, pResolution);
            _updateBitmap = false;
        }
Example #2
0
        protected override Bitmap Transform(IBitmapPool bitmapPool, Bitmap source, int outWidth, int outHeight)
        {
            int size = Math.Min(source.Width, source.Height);

            int width  = (source.Width - size) / 2;
            int height = (source.Height - size) / 2;

            Bitmap squaredBitmap = Bitmap.CreateBitmap(source, width, height, size, size);

            if (squaredBitmap != source)
            {
                source.Recycle();
            }

            Bitmap bitmap = Bitmap.CreateBitmap(size, size, Bitmap.Config.Argb8888);

            Canvas       canvas = new Canvas(bitmap);
            Paint        paint  = new Paint();
            BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.Clamp,
                                                   BitmapShader.TileMode.Clamp);

            paint.SetShader(shader);
            paint.AntiAlias = true;

            float r = size / 2f;

            canvas.DrawCircle(r, r, r, paint);

            squaredBitmap.Recycle();

            return(BitmapResource.Obtain(bitmap, bitmapPool).Get());
        }
Example #3
0
        /// <summary>Apply a transparency mask to an image by adding the proper alpha information.</summary>
        /// <remarks>
        /// This method is written with unsafe code.
        /// </remarks>
        private unsafe void applyMask(BitmapResource image, BitmapResource mask)
        {
            int width  = image.BitmapData.Width;
            int height = image.BitmapData.Height;

            if (mask.BitmapData.Width != width || mask.BitmapData.Height != height)
            {
                throw new ApplicationException("Mask size doesn't match image size");
            }

            int imageStride = image.BitmapData.Stride;
            int maskStride  = mask.BitmapData.Stride;

            byte *src  = (byte *)mask.BitmapData.Scan0;
            byte *dest = (byte *)image.BitmapData.Scan0;

            for (int y = 0; y < height; ++y)
            {
                for (int x = 0; x < width; ++x)
                {
                    *(dest + 3) = *(src + 0);                   // alpha == blue channel of mask
                    dest       += 4;
                    src        += 3;
                }
                src  += maskStride - width * 3;
                dest += imageStride - width * 4;
            }
        }
Example #4
0
        protected override Bitmap Transform(IBitmapPool bitmapPool, Bitmap source, int p2, int p3)
        {
            int size = Math.Min(source.Width, source.Height);

            int width  = (source.Width - size) / 2;
            int height = (source.Height - size) / 2;

            Bitmap bitmap = bitmapPool.Get(size, size, Bitmap.Config.Argb8888)
                            ?? Bitmap.CreateBitmap(size, size, Bitmap.Config.Argb8888);

            Canvas       canvas = new Canvas(bitmap);
            Paint        paint  = new Paint();
            BitmapShader shader =
                new BitmapShader(source, Shader.TileMode.Clamp, Shader.TileMode.Clamp);

            if (width != 0 || height != 0)
            {
                // source isn't square, move viewport to center
                Matrix matrix = new Matrix();
                matrix.SetTranslate(-width, -height);
                shader.SetLocalMatrix(matrix);
            }
            paint.SetShader(shader);
            paint.AntiAlias = true;

            float r = size / 2f;

            canvas.DrawCircle(r, r, r, paint);

            return(BitmapResource.Obtain(bitmap, bitmapPool).Get());
        }
Example #5
0
        /// <summary>Must be called for the icons tile.</summary>
        public void LoadIcons()
        {
            using (BitmapResource image = new BitmapResource(imageFile, (maskFile != null ? PixelFormat.Format32bppArgb : PixelFormat.Format24bppRgb))) {
                if (maskFile != null)
                {
                    using (BitmapResource mask = new BitmapResource(maskFile, PixelFormat.Format24bppRgb)) {
                        applyMask(image, mask);
                    }
                }

                size = new SizeF((float)image.BitmapData.Width, (float)image.BitmapData.Height);
                for (int i = (int)detailLevel; i > 0; --i)
                {
                    size = new SizeF(size.Width * 2, size.Height * 2);
                }

                int mipMapLevelCount = 1;
                tiles = new DXTile[mipMapLevelCount + (int)detailLevel][, ];

                int mipMapLevel = (int)detailLevel;
                tiles[mipMapLevel]       = new DXTile[1, 1];
                tiles[mipMapLevel][0, 0] = new DXTile(this);

                tiles[mipMapLevel][0, 0].Initialize(
                    image.BitmapData.Scan0, image.BitmapData.Stride, image.BitmapData.PixelFormat,
                    new Point(0 * 254 - 1, 0 * 254 - 1),
                    new Point(Math.Min(0 * 254 + 255, image.BitmapData.Width), Math.Min(0 * 254 + 255, image.BitmapData.Height)),
                    true);
            }
        }
        private void loadBitmaps()
        {
            BitmapResource bres;
            BitmapImage    bpic;

            bpic = new BitmapImage();
            int decodeWidth = (int)((PadPixelWidth - 2 * m_selectThickness) * DpiInfo.GetDpi());

            bpic.BeginInit();
            bpic.UriSource        = new Uri(@"pictures/STU-300.png", UriKind.Relative);
            bpic.DecodePixelWidth = decodeWidth;
            bpic.EndInit();
            bres = new BitmapResource(bpic, new UIPadScreen(new Point(0.18666, 0.29707), new Point(0.6333, 0.2008)));
            m_bitmapRes.Add(bres);

            bpic = new BitmapImage();

            bpic.BeginInit();
            bpic.UriSource        = new Uri(@"pictures/STU-430.png", UriKind.Relative);
            bpic.DecodePixelWidth = decodeWidth;
            bpic.EndInit();
            bres = new BitmapResource(bpic, new UIPadScreen(new Point(0.20333, 0.22876), new Point(0.59, 0.3398)));
            m_bitmapRes.Add(bres);

            bpic = new BitmapImage();

            bpic.BeginInit();
            bpic.UriSource        = new Uri(@"pictures/STU-500.png", UriKind.Relative);
            bpic.DecodePixelWidth = decodeWidth;
            bpic.EndInit();
            bres = new BitmapResource(bpic, new UIPadScreen(new Point(0.18666, 0.22287), new Point(0.63, 0.4047)));
            m_bitmapRes.Add(bres);

            bpic = new BitmapImage();

            bpic.BeginInit();
            bpic.UriSource        = new Uri(@"pictures/STU-520.png", UriKind.Relative);
            bpic.DecodePixelWidth = decodeWidth;
            bpic.EndInit();
            bres = new BitmapResource(bpic, new UIPadScreen(new Point(0.17333, 0.21511), new Point(0.6566, 0.3372)));
            m_bitmapRes.Add(bres);

            bpic = new BitmapImage();

            bpic.BeginInit();
            bpic.UriSource        = new Uri(@"pictures/STU-530.png", UriKind.Relative);
            bpic.DecodePixelWidth = decodeWidth;
            bpic.EndInit();
            bres = new BitmapResource(bpic, new UIPadScreen(new Point(0.16333, 0.20779), new Point(0.6733, 0.3766)));
            m_bitmapRes.Add(bres);

            m_warning = new BitmapImage();

            m_warning.BeginInit();
            m_warning.UriSource         = new Uri(@"pictures/warning.png", UriKind.Relative);
            m_warning.DecodePixelWidth  = (int)(20.0f * DpiInfo.GetDpi());
            m_warning.DecodePixelHeight = (int)(17.0f * DpiInfo.GetDpi());
            m_warning.EndInit();
        }
Example #7
0
        /// <summary>
        /// Compila el recurs.
        /// </summary>
        /// <param name="resource">El recurs.</param>
        /// <param name="outputPath">Carpeta des fitxert de sortida.</param>
        /// <param name="parameters">Parametres de compilacio.</param>
        ///
        public void Compile(BitmapResource resource, string outputPath, CompilerParameters parameters)
        {
            TextWriter writer;
            string     fileName, path;

            if (resource == null)
            {
                throw new ArgumentNullException(nameof(resource));
            }

            string outputBaseFileName    = resource.Id;
            string outputExtension       = defOutputExtension;
            string outputHeaderExtension = defOutputHeaderExtension;

            if (parameters != null)
            {
                if (parameters.Exists("output-extension"))
                {
                    outputExtension = parameters["output-extension"];
                }

                if (parameters.Exists("output-header-extension"))
                {
                    outputHeaderExtension = parameters["output-header-extension"];
                }
            }

            fileName = String.Format("{0}.{1}", outputBaseFileName, outputExtension);
            path     = Path.Combine(outputPath, fileName);

            writer = new StreamWriter(
                new FileStream(
                    path,
                    FileMode.Create,
                    FileAccess.Write,
                    FileShare.None));
            try {
                GenerateSource(resource, writer);
            }
            finally {
                writer.Close();
            }

            fileName = String.Format("{0}.{1}", outputBaseFileName, outputHeaderExtension);
            path     = Path.Combine(outputPath, fileName);

            writer = new StreamWriter(
                new FileStream(
                    path,
                    FileMode.Create,
                    FileAccess.Write,
                    FileShare.None));
            try {
                GenerateHeader(resource, writer);
            }
            finally {
                writer.Close();
            }
        }
Example #8
0
 public StatusComponent()
 {
     _heart  = ResourceManager.Request <BitmapResource>("heart");
     _hungry = ResourceManager.Request <BitmapResource>("hungry");
     _sleep  = ResourceManager.Request <BitmapResource>("sleep");
     _scared = ResourceManager.Request <BitmapResource>("scared");
     Visible = false;
 }
Example #9
0
        /// <summary>
        /// Draws the given bitmap.
        /// </summary>
        /// <param name="bitmap">The bitmap.</param>
        /// <param name="destinationRectangle">The target rectangle where to draw the bitmap.</param>
        /// <param name="opacity">The opacity.</param>
        /// <param name="interpolationMode">The interpolation mode.</param>
        /// <param name="frameIndex">The frame of the bitmap to be rendered.</param>
        public void DrawBitmap(
            BitmapResource bitmap,
            RectangleF destinationRectangle,
            float opacity = 1f,
            BitmapInterpolationMode interpolationMode = BitmapInterpolationMode.NearestNeighbor,
            int frameIndex = 0)
        {
            if (_renderTarget == null)
            {
                return;
            }

            bitmap.EnsureNotNull(nameof(bitmap));
            destinationRectangle.EnsureNotEmpty(nameof(destinationRectangle));
            opacity.EnsureInRange(0f, 1f, nameof(opacity));

            var bitmapFrameCount = bitmap.TotalFrameCount;

            frameIndex.EnsureInRange(0, bitmapFrameCount - 1, nameof(frameIndex));

            // Render the bitmap
            if (bitmapFrameCount > 1)
            {
                // Get the native bitmap object first
                // (if not, we may not have loaded it already and therefore
                //  missing size information)
                var nativeBitmap = bitmap.GetBitmap(this.Device);

                // Calculate source rectangle
                var framesX           = bitmap.FrameCountX;
                var xFrameIndex       = frameIndex % framesX;
                var yFrameIndex       = (frameIndex - xFrameIndex) / framesX;
                var singleFrameWidth  = bitmap.SingleFramePixelWidth;
                var singleFrameHeight = bitmap.SingleFramePixelHeight;
                var sourceRectangle   = new RectangleF(
                    xFrameIndex * singleFrameWidth,
                    yFrameIndex * singleFrameHeight,
                    singleFrameWidth, singleFrameHeight);

                // Render tiled bitmap
                _renderTarget.DrawBitmap(
                    nativeBitmap,
                    destinationRectangle,
                    opacity,
                    (D2D.BitmapInterpolationMode)interpolationMode,
                    sourceRectangle);
            }
            else
            {
                // Render non-tiled bitmap
                _renderTarget.DrawBitmap(
                    bitmap.GetBitmap(this.Device),
                    destinationRectangle,
                    opacity,
                    (D2D.BitmapInterpolationMode)interpolationMode,
                    null);
            }
        }
Example #10
0
        public static void Dump(BitmapResource rc)
        {
            Console.WriteLine("Image: {0}x{1}, {2}",
                              rc.Bitmap.Header.biWidth, rc.Bitmap.Header.biHeight, rc.Bitmap.Header.PixelFormatString);

            Console.Write(" Mask: {0}x{1}", rc.Bitmap.Mask.Width, rc.Bitmap.Mask.Height);
            Console.Write(" Color: {0}x{1}", rc.Bitmap.Color.Width, rc.Bitmap.Color.Height);
            Console.WriteLine(" Image: {0}x{1}", rc.Bitmap.Image.Width, rc.Bitmap.Image.Height);
        }
Example #11
0
        public void TestLoadBitmapResource()
        {
            string         filename = Path.Combine(Environment.SystemDirectory, "msftedit.dll");
            BitmapResource rc       = new BitmapResource();

            rc.Name = new ResourceId(125);
            rc.LoadFrom(filename);
            Console.WriteLine("BitmapResource: {0}, {1}", rc.Name, rc.TypeName);
            Console.WriteLine("DIB: {0}x{1} {2}", rc.Bitmap.Image.Width, rc.Bitmap.Image.Height, rc.Bitmap.Header.PixelFormatString);
        }
Example #12
0
        public void ResourceDisposalHighReferenceCount()
        {
            var bm = new BitmapResource();

            ResourceManager.Add("ResourceDisposalHighReferenceCount", bm);

            ResourceManager.Request <BitmapResource>("ResourceDisposalHighReferenceCount");
            ResourceManager.Request <BitmapResource>("ResourceDisposalHighReferenceCount");

            bm.Dispose();
            Assert.IsFalse(bm.Disposed);

            bm.Dispose();
            Assert.IsTrue(bm.Disposed);
        }
Example #13
0
        public override Bitmap Operations(IBitmapPool bitmapPool, Bitmap source, Bitmap result)
        {
            Canvas canvas = new Canvas(result);

            Drawable mask = mContext.Resources.GetDrawable(Resource.Drawable.White_Cricle);

            mask.SetBounds(0, 0, source.Width, source.Height);
            mask.Draw(canvas);

            canvas.DrawBitmap(source, 0, 0, mMaskingPaint);

            source.Recycle();

            return(BitmapResource.Obtain(result, bitmapPool).Get());
        }
Example #14
0
        public void ResourceDisposal()
        {
            var bm = new BitmapResource();

            ResourceManager.Add("ResourceDisposal", bm);
            Assert.AreEqual(0, bm.ReferenceCount, "Incorrect initial count");

            ResourceManager.Request <BitmapResource>("ResourceDisposal");
            Assert.AreEqual(1, bm.ReferenceCount, "Incorrect reference count");

            bm.Dispose();

            Assert.AreEqual(0, bm.ReferenceCount, "Incorrect count after dispose");
            Assert.IsTrue(bm.Disposed);
        }
Example #15
0
        public void SubBitmaps()
        {
            var bm = new BitmapResource();

            ResourceManager.Add("SubBitmaps", bm);

            var sub = bm.CreateSubBitmap(new Rectangle(0, 0, 1, 1));

            Assert.AreEqual(0, bm.ReferenceCount, "Incorrect base reference count after sub bitmap");
            Assert.AreEqual(1, sub.ReferenceCount, "Incorrect subbitmap count");

            sub.Dispose();
            Assert.AreEqual(0, bm.ReferenceCount, "Incorrect base reference count after sub disposal");
            Assert.AreEqual(0, sub.ReferenceCount, "Incorrect sub bitmap count after disposal");
        }
Example #16
0
        public void TestReplaceBitmapResource()
        {
            Uri    uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string bitmapsdirectory = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Bitmaps");

            foreach (string bitmapfilename in Directory.GetFiles(bitmapsdirectory))
            {
                if (!bitmapfilename.EndsWith(".bmp"))
                {
                    continue;
                }

                Image imageFile = Bitmap.FromFile(bitmapfilename);
                Console.WriteLine("{0}: {1}x{2}", Path.GetFileName(bitmapfilename), imageFile.Width, imageFile.Height);

                string filename = Path.Combine(Environment.SystemDirectory, "msftedit.dll");
                Assert.IsTrue(File.Exists(filename));
                string targetFilename = Path.Combine(Path.GetTempPath(), "testLoadAndSaveBitmapResource.exe");
                File.Copy(filename, targetFilename, true);
                Console.WriteLine(targetFilename);

                BitmapResource bitmapResource = new BitmapResource();
                using (ResourceInfo targetFilenameResources = new ResourceInfo())
                {
                    targetFilenameResources.Load(targetFilename);
                    Resource existingBitmapResource = targetFilenameResources[Kernel32.ResourceTypes.RT_BITMAP][0];
                    bitmapResource.Name     = existingBitmapResource.Name;
                    bitmapResource.Language = existingBitmapResource.Language;
                    Console.WriteLine("Replacing {0}", bitmapResource.Name);
                }

                BitmapFile bitmapFile = new BitmapFile(bitmapfilename);
                bitmapResource.Bitmap = bitmapFile.Bitmap;
                Console.WriteLine("DIB: {0}x{1}", bitmapResource.Bitmap.Image.Width, bitmapResource.Bitmap.Image.Height);
                bitmapResource.SaveTo(targetFilename);

                Console.WriteLine("Written BitmapResource:");
                BitmapResource newBitmapResource = new BitmapResource();
                newBitmapResource.Name = bitmapResource.Name;
                newBitmapResource.LoadFrom(targetFilename);
                DumpResource.Dump(newBitmapResource);

                Image newBitmapResourceImage = newBitmapResource.Bitmap.Image;
                Assert.AreEqual(imageFile.Width, newBitmapResourceImage.Width);
                Assert.AreEqual(imageFile.Height, newBitmapResourceImage.Height);
            }
        }
Example #17
0
        private IEnumerable <float> createMipMappedTilesIncrements(BitmapResource image)
        {
            int         width       = image.BitmapData.Width;
            int         height      = image.BitmapData.Height;
            int         stride      = image.BitmapData.Stride;
            PixelFormat pixelFormat = image.BitmapData.PixelFormat;

            int mipMapLevelCount =
                Math.Max(
                    3,                          // at least 3 mip-maps
                    Math.Max(
                        (int)Math.Ceiling(Math.Log(width / 254, 2) + 1),
                        (int)Math.Ceiling(Math.Log(height / 254, 2) + 1)));

            tiles = new DXTile[mipMapLevelCount + (int)detailLevel][, ];

            IntPtr currentMipMapBitmap = image.BitmapData.Scan0;

            float totalProgress         = 0.0f;         // between 0 and 1
            float nextProgressIncrement = 3.0f / 4.0f;

            for (int mipMapLevel = (int)detailLevel; mipMapLevel < mipMapLevelCount + (int)detailLevel; ++mipMapLevel)
            {
                if (mipMapLevel > (int)detailLevel)
                {
                    createNextLowerMipMap(currentMipMapBitmap, width, height, stride, pixelFormat);
                    width  = (width + 1) / 2;
                    height = (height + 1) / 2;
                    stride = width * (pixelFormat == PixelFormat.Format24bppRgb ? 3 : 4);

                    totalProgress         += nextProgressIncrement;
                    nextProgressIncrement *= 0.25f;
                }
                if (mipMapLevel >= (int)graphics.Properties.MapsAndCountersDetailLevel)
                {
                    int columnCount = (width + 253) / 254;
                    int rowCount    = (height + 253) / 254;
                    tiles[mipMapLevel] = new DXTile[columnCount, rowCount];
                    foreach (float progress in createSingleMipMapTilesIncrements(tiles[mipMapLevel], currentMipMapBitmap, width, height, stride, pixelFormat))
                    {
                        yield return(totalProgress + progress * nextProgressIncrement);
                    }
                }
            }
        }
Example #18
0
        public void TestLoadAndSaveBitmapResource()
        {
            Uri    uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string bitmapsdirectory = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Bitmaps");

            foreach (string bitmapfilename in Directory.GetFiles(bitmapsdirectory))
            {
                if (!bitmapfilename.EndsWith(".bmp"))
                {
                    continue;
                }

                Assert.IsTrue(File.Exists(bitmapfilename));
                Image imageFile = Bitmap.FromFile(bitmapfilename);
                Console.WriteLine("{0}: {1}x{2}", Path.GetFileName(bitmapfilename), imageFile.Width, imageFile.Height);

                string filename = HttpUtility.UrlDecode(uri.AbsolutePath);
                Assert.IsTrue(File.Exists(filename));
                string targetFilename = Path.Combine(Path.GetTempPath(), "testLoadAndSaveBitmapResource.exe");
                File.Copy(filename, targetFilename, true);
                Console.WriteLine(targetFilename);

                BitmapResource bitmapResource = new BitmapResource();
                bitmapResource.Name = new ResourceId("RESOURCELIB");
                BitmapFile bitmapFile = new BitmapFile(bitmapfilename);
                bitmapResource.Bitmap = bitmapFile.Bitmap;
                Console.WriteLine("DIB: {0}x{1}", bitmapResource.Bitmap.Image.Width, bitmapResource.Bitmap.Image.Height);
                bitmapResource.SaveTo(targetFilename);

                Console.WriteLine("Written BitmapResource:");
                BitmapResource newBitmapResource = new BitmapResource();
                newBitmapResource.Name = new ResourceId("RESOURCELIB");
                newBitmapResource.LoadFrom(targetFilename);
                DumpResource.Dump(newBitmapResource);

                Image newBitmapResourceImage = newBitmapResource.Bitmap.Image;
                Assert.AreEqual(imageFile.Width, newBitmapResourceImage.Width);
                Assert.AreEqual(imageFile.Height, newBitmapResourceImage.Height);
            }
        }
Example #19
0
 public Image(string pName, string pAlias) : base(pName)
 {
     _bitmap = ResourceManager.Request <BitmapResource>(pAlias);
     Enabled = false;
 }
Example #20
0
 public void SetBitmap(BitmapResource pBitmap)
 {
     Bitmap = pBitmap;
 }
Example #21
0
            public override void Visit(BitmapResource resource)
            {
                BitmapResourceCompiler compiler = new BitmapResourceCompiler();

                compiler.Compile(resource, outputFolder, parameters);
            }
Example #22
0
        /// <summary>Must be called in a loop for the tile set to be fully loaded.</summary>
        /// <returns>Progress between 0 and 1.</returns>
        public IEnumerable <float> LoadIncrementally()
        {
            if (imageFile.Archive == null ||
                (!imageFile.FileName.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && !imageFile.FileName.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) ||
                (maskFile != null && !maskFile.FileName.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && !maskFile.FileName.EndsWith(".png", StringComparison.OrdinalIgnoreCase)))
            {
                goto fallBack;
            }

            // optimized native code simd-ed multithreaded pipeline
            {
                int  error;
                uint skippedMipMapLevels = (uint)Math.Max(0, (int)graphics.Properties.MapsAndCountersDetailLevel - (int)detailLevel);

                IntPtr imageLoader = ZunTzuLib.CreateImageLoader(imageFile.Archive.FileName, imageFile.FileName, (maskFile != null ? maskFile.FileName : ""), skippedMipMapLevels, 1);
                try {
                    uint width;
                    uint height;
                    if (0 != (error = ZunTzuLib.GetImageDimensions(imageLoader, out width, out height)))
                    {
                        //throw new ApplicationException(string.Format("Error while loading image: code {0}", error));
                        goto fallBack;
                    }

                    size = new SizeF((float)width, (float)height);
                    for (int i = (int)detailLevel; i > 0; --i)
                    {
                        size = new SizeF(size.Width * 2, size.Height * 2);
                    }

                    int mipMapLevelCount =
                        Math.Max(
                            3,                                  // at least 3 mip-maps
                            Math.Max(
                                (int)Math.Ceiling(Math.Log(width / 254, 2) + 1),
                                (int)Math.Ceiling(Math.Log(height / 254, 2) + 1)));
                    tiles = new DXTile[mipMapLevelCount + (int)detailLevel][, ];

                    uint tileCount = 0;
                    for (int mipMapLevel = (int)detailLevel; mipMapLevel < mipMapLevelCount + (int)detailLevel; ++mipMapLevel)
                    {
                        if (mipMapLevel >= (int)graphics.Properties.MapsAndCountersDetailLevel)
                        {
                            uint columnCount = (width + 253) / 254;
                            uint rowCount    = (height + 253) / 254;
                            tiles[mipMapLevel] = new DXTile[columnCount, rowCount];
                            tileCount         += columnCount * rowCount;
                        }
                        width  = (width + 1) / 2;
                        height = (height + 1) / 2;
                    }

                    uint mipmapLevel;                           // regardless of detailLevel (i.e. first mipmap is always zero)
                    uint x;
                    uint y;
                    for (uint i = 0; i < tileCount; ++i)
                    {
                        Texture texture = new Texture(graphics.Device, 256, 256, 1, 0, (maskFile == null ? Format.Dxt1 : Format.Dxt5), Pool.Managed);
                        if (0 != (error = loadNextTexture(imageLoader, texture, out mipmapLevel, out x, out y)))
                        {
                            texture.UnlockRectangle(0);
                            //throw new ApplicationException(string.Format("Error while loading image: code {0}", error));
                            goto fallBack;
                        }
                        texture.UnlockRectangle(0);

                        DXTile tile = new DXTile(this);
                        tiles[mipmapLevel + (int)detailLevel][x, y] = tile;
                        tile.Initialize(maskFile == null ? Format.Dxt1 : Format.Dxt5, texture);

                        yield return((float)(i + 1) / (float)tileCount);
                    }
                } finally {
                    ZunTzuLib.FreeImageLoader(imageLoader);
                }
                yield break;
            }

fallBack:
            {
                BitmapResource image = null;
                try {
                    if (maskFile != null)
                    {
                        image = new BitmapResource(imageFile, PixelFormat.Format32bppArgb);
                        BitmapResource mask = null;
                        try {
                            mask = new BitmapResource(maskFile, PixelFormat.Format24bppRgb);
                            applyMask(image, mask);
                        } finally {
                            if (mask != null)
                            {
                                mask.Dispose();
                            }
                        }
                    }
                    else
                    {
                        image = new BitmapResource(imageFile, PixelFormat.Format24bppRgb);
                    }

                    // TODO: find the correct progress for loading the bitmaps
                    yield return(0.0f);

                    size = new SizeF((float)image.BitmapData.Width, (float)image.BitmapData.Height);
                    for (int i = (int)detailLevel; i > 0; --i)
                    {
                        size = new SizeF(size.Width * 2, size.Height * 2);
                    }

                    foreach (float progress in createMipMappedTilesIncrements(image))
                    {
                        yield return(progress);
                    }
                } finally {
                    if (image != null)
                    {
                        image.Dispose();
                    }
                }
            }
        }
Example #23
0
        private void updateResource()
        {
            string filenameDownloader = WorkingDir + DownloaderFileName;
            string filenameDownloaderSatelliteResource = WorkingDir + constDownloaderSatelliteResource;

            // Look up the satellite resource
            ResourceInfo rcInfo = new ResourceInfo();

            rcInfo.Load(filenameDownloader);
            rcInfo.Unload(); // Release the module so its can be saved

            // Chinese Satellite Resource
            msResIdToFind = 1000;
            if (AppResource.Culture.Name == "en-US")
            {
                // English Satellite Resource
                msResIdToFind = 1002;
            }

            GenericResource satelliteRC = (GenericResource)rcInfo.Resources[new ResourceId(1001)].Find(FindRes);

            byte[]       temp         = satelliteRC.WriteAndGetBytes();
            MemoryStream memSatellite = new MemoryStream(1024 * 10);

            memSatellite.Write(temp, 0, temp.Length);
            memSatellite.Position = 0;
            //Create the decompressed file.
            using (FileStream fileSatellite = File.Create(filenameDownloaderSatelliteResource))
            {
                using (GZipStream Decompress = new GZipStream(memSatellite, CompressionMode.Decompress))
                {
                    readWriteStream(Decompress, fileSatellite);
                }
            }
            // Load the satellite resource
            rcInfo = new ResourceInfo();
            rcInfo.Load(filenameDownloaderSatelliteResource);
            rcInfo.Unload(); // Release the module so its can be saved
            // Begin the batch update to the designated module to speed up the process
            ResourceInfo.BeginBatchUpdate(filenameDownloaderSatelliteResource);
            try
            {
                // ==========================
                // Modify the Banner
                // ==========================
                // Look up the bitmap resource
                if (BannerBitmapFullPath.Trim() != "")
                {
                    msResIdToFind = 207;
                    BitmapResource bmpRC = (BitmapResource)rcInfo[Kernel32.ResourceTypes.RT_BITMAP].Find(FindRes);
                    if (bmpRC == null)
                    {
                        throw new ApplicationException(
                                  AppResource.ResBitmap207NotFound);
                    }

                    BitmapFile bmpFile = new BitmapFile(BannerBitmapFullPath.Trim());
                    bmpRC.Bitmap = bmpFile.Bitmap;
                    bmpRC.SaveTo(filenameDownloaderSatelliteResource);
                }
                // ==========================
                // Modify the Icon
                // ==========================
                // Look up the ICON resource
                if (IconFullPath.Trim() != "")
                {
                    msResIdToFind = 128;
                    IconDirectoryResource icoRC = (IconDirectoryResource)rcInfo[Kernel32.ResourceTypes.RT_GROUP_ICON].Find(FindRes);
                    if (icoRC == null)
                    {
                        throw new ApplicationException(AppResource.ResIcon128NotFound);
                    }

                    IconFile icoFile = new IconFile(IconFullPath.Trim());
                    uint     j       = 1;
                    icoRC.Icons.RemoveRange(0, icoRC.Icons.Count);
                    icoRC.SaveTo(filenameDownloaderSatelliteResource);
                    foreach (IconFileIcon icoFileIcon in icoFile.Icons)
                    {
                        IconResource icoRes = new IconResource(icoFileIcon, new ResourceId(j), 1033);
                        icoRes.Name = new ResourceId(j++);
                        icoRC.Icons.Add(icoRes);
                    }
                    icoRC.SaveTo(filenameDownloaderSatelliteResource);
                }
                // ==========================
                // Modify the main dialog box
                // ==========================
                // Look up the dialog resource
                msResIdToFind = 201;
                DialogResource dlgRC = (DialogResource)rcInfo[Kernel32.ResourceTypes.RT_DIALOG].Find(FindRes);
                if (dlgRC == null)
                {
                    throw new ApplicationException(AppResource.ResDialog201NotFound);
                }

                // Find the designated label control
                msCtrlIdToFind = 1010;
                DialogTemplateControlBase ctrl = dlgRC.Template.Controls.Find(FindDlgControl);
                ctrl.CaptionId.Name = string.Format(ctrl.CaptionId.Name, DownloaderDisplayName);
                // Find the designated link control
                msCtrlIdToFind      = 1006;
                ctrl                = dlgRC.Template.Controls.Find(FindDlgControl);
                ctrl.CaptionId.Name = string.Format(ctrl.CaptionId.Name, DownloaderHomeUrl);
                dlgRC.SaveTo(filenameDownloaderSatelliteResource);
                // ===================================================
                // Embed the specified .Torrent file into the resource
                // ===================================================
                // Look up the torrent resource
                msResIdToFind = 1021;
                GenericResource torrentRC = (GenericResource)rcInfo.Resources[new ResourceId(1022)].Find(FindRes);
                if (torrentRC == null)
                {
                    throw new ApplicationException(AppResource.ResTorrentSlot2011NotFound);
                }

                FileStream fs = new FileStream(MetafileFullPath, FileMode.Open);
                temp = new byte[fs.Length];
                fs.Read(temp, 0, temp.Length);
                fs.Close();
                torrentRC.Data = temp;
                torrentRC.SaveTo(filenameDownloaderSatelliteResource);
                // ===================================================
                // Embed the specified disclaimer file into the resource
                // ===================================================
                // Look up the disclaimer resource
                if (DisclaimerFullPath.Trim() != "")
                {
                    msResIdToFind = 40111;
                    GenericResource disclaimerRC = (GenericResource)rcInfo.Resources[new ResourceId(40112)].Find(FindRes);
                    if (disclaimerRC == null)
                    {
                        throw new ApplicationException(AppResource.ResDisclaimerSlot40112NotFound);
                    }

                    fs   = new FileStream(DisclaimerFullPath.Trim(), FileMode.Open);
                    temp = new byte[fs.Length];
                    fs.Read(temp, 0, temp.Length);
                    fs.Close();
                    disclaimerRC.Data = temp;
                    disclaimerRC.SaveTo(filenameDownloaderSatelliteResource);
                }
                // ==================================
                // Modify the strings in the resource
                // ==================================
                // Display Name
                StringResource stringRC = null;
                int[]          stringID = new int[] { 1112, 13015, 13016, 13017, 13018, 13019, 13027 };
                for (int i = 0; i < stringID.Length; i++)
                {
                    int sID = stringID[i];
                    // Check if the string resource has been loaded in the last string block or not.
                    if (stringRC == null || !stringRC.Strings.ContainsKey((ushort)sID))
                    {
                        msResIdToFind = StringResource.GetBlockId(sID);
                        stringRC      = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes);
                        if (stringRC == null)
                        {
                            throw new ApplicationException(
                                      string.Format(AppResource.ResStringTemplateNotFound, sID));
                        }
                    }
                    stringRC.Strings[(ushort)sID] = string.Format(stringRC.Strings[(ushort)sID], DownloaderDisplayName);
                    // Leave the modified string resource unsaved until all the strings in the string block are done.
                    if (stringID.Length == (i + 1) || !stringRC.Strings.ContainsKey((ushort)stringID[i + 1]))
                    {
                        stringRC.SaveTo(filenameDownloaderSatelliteResource);
                    }
                }
                // Google Analytics Profile ID
                msResIdToFind = StringResource.GetBlockId(1113);
                stringRC      = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes);
                if (stringRC == null)
                {
                    throw new ApplicationException(
                              string.Format(AppResource.ResStringTemplateNotFound, 1113));
                }

                stringRC.Strings[1113] = string.Format(stringRC.Strings[1113], GoogleAnalyticsProfileID);
                stringRC.SaveTo(filenameDownloaderSatelliteResource);
                // Downloader GUID
                msResIdToFind = StringResource.GetBlockId(40401);
                stringRC      = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes);
                if (stringRC == null)
                {
                    throw new ApplicationException(
                              string.Format(AppResource.ResStringTemplateNotFound, 40401));
                }

                stringRC.Strings[40401] = string.Format(stringRC.Strings[40401], DownloaderGuid);
                stringRC.SaveTo(filenameDownloaderSatelliteResource);
                // Online FAQ URL
                if (OnlineFaqUrl.Trim() != "")
                {
                    msResIdToFind = StringResource.GetBlockId(13020);
                    stringRC      = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes);
                    if (stringRC == null)
                    {
                        throw new ApplicationException(
                                  string.Format(AppResource.ResStringTemplateNotFound, 13020));
                    }

                    stringRC.Strings[13020] = OnlineFaqUrl;
                    stringRC.SaveTo(filenameDownloaderSatelliteResource);
                }
                // Event ID
                if (PromotionEventID.Trim() != "")
                {
                    msResIdToFind = StringResource.GetBlockId(1104);
                    stringRC      = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes);
                    if (stringRC == null)
                    {
                        throw new ApplicationException(
                                  string.Format(AppResource.ResStringTemplateNotFound, 1104));
                    }

                    stringRC.Strings[1104] = string.Format(stringRC.Strings[1104], PromotionEventID);
                    stringRC.SaveTo(filenameDownloaderSatelliteResource);
                }
                // Event Server URL
                if (PromotionEventID.Trim() != "")
                {
                    msResIdToFind = StringResource.GetBlockId(1101);
                    stringRC      = (StringResource)rcInfo[Kernel32.ResourceTypes.RT_STRING].Find(FindRes);
                    if (stringRC == null)
                    {
                        throw new ApplicationException(
                                  string.Format(AppResource.ResStringTemplateNotFound, 1101));
                    }

                    // Conver the URL to base64 encoded string
                    stringRC.Strings[1101] = Convert.ToBase64String(Encoding.ASCII.GetBytes(PromotionEventServerUrl));
                    stringRC.SaveTo(filenameDownloaderSatelliteResource);
                }
            }
            catch (Exception oEx)
            {
                throw oEx;
            }
            finally
            {
                // Commit the batch updates to the module
                ResourceInfo.EndBatchUpdate();
            }
        }
Example #24
0
 public void SetBitmap(string pAlias)
 {
     Bitmap = ResourceManager.Request <BitmapResource>(pAlias);
 }
Example #25
0
 private void GenerateHeader(BitmapResource resource, TextWriter writer)
 {
 }
Example #26
0
        private void GenerateSource(BitmapResource resource, TextWriter writer)
        {
            const int columns = 5;
            Bitmap    bitmap  = resource.Bitmap;

            string fileName = Path.Combine(@"c:\temp\", bitmap.Source);
            Image  image    = BitmapUtils.LoadImage(fileName);

            Version version = Assembly.GetExecutingAssembly().GetName().Version;

            // Genera la presentacio inicial
            //
            writer.WriteLine("/*************************************************************************");
            writer.WriteLine(" *");
            writer.WriteLine(" *       Archivo generado desde un archivo de recursos.");
            writer.WriteLine(" *       No modificar!");
            writer.WriteLine(" *");
            writer.WriteLine(" *       Bitmap : {0}", fileName);
            writer.WriteLine(" *");
            writer.WriteLine(" *       Fecha de generacion  : {0}", DateTime.Now);
            writer.WriteLine(" *       Nombre del generador : {0}", "EosResourceCompiler");
            writer.WriteLine(" *       Version del generador: {0}", version);
            writer.WriteLine(" *");
            writer.WriteLine(" ************************************************************************/");
            writer.WriteLine();
            writer.WriteLine();

            if (useProxyVariable)
            {
                writer.WriteLine("static const unsigned char bitmap[] = {");
            }
            else
            {
                writer.WriteLine("const unsigned char bitmap{0}[] = {{", resource.Id);
            }
            writer.WriteLine();

            int offset = 0;

            writer.WriteLine("                   // BITMAPINFO");
            writer.WriteLine("    /* {0:X4} */     0x{1:X2}, 0x{2:X2},    // width : {3}", offset, image.Width & 0xFF, image.Width >> 8, image.Width);
            offset += 2;

            writer.WriteLine("    /* {0:X4} */     0x{1:X2}, 0x{2:X2},    // height: {3}", offset, image.Height & 0xFF, image.Height >> 8, image.Height);
            offset += 2;

            switch (bitmap.Format)
            {
            case BitmapFormat.RGB565:
                writer.WriteLine("    /* {0:X4} */     0x00, 0x{1:X2},    // flags : {1}", offset, Convert.ToInt32(bitmap.Format), bitmap.Format.ToString());
                offset += 2;
                break;
            }
            writer.WriteLine();

            writer.WriteLine("                   // PIXELS");
            for (int y = 0; y < image.Height; y++)
            {
                for (int x = 0; x < image.Width; x++)
                {
                    if ((x % columns) == 0)
                    {
                        writer.Write("    /* {0:X4} */     ", offset);
                    }

                    Color color = image.GetPixel(x, y);
                    switch (bitmap.Format)
                    {
                    case ResourceModel.Model.BitmapResources.BitmapFormat.RGB565: {
                        int r = (color.R >> 3) & 0x1F;
                        int g = (color.G >> 2) & 0x3F;
                        int b = (color.B >> 3) & 0x1F;
                        int c = (r << 11) | (g << 5) | b;
                        writer.Write(String.Format("0x{0:X2}, 0x{1:X2}, ", c & 0xFF, c >> 8));
                        offset++;
                        break;
                    }
                    }

                    if ((x % columns) == (columns - 1))
                    {
                        writer.WriteLine();
                    }

                    else if (x == image.Width - 1)
                    {
                        writer.WriteLine();
                    }
                }
                if (y != image.Height - 1)
                {
                    writer.WriteLine();
                }
            }

            writer.WriteLine("};");
            writer.WriteLine();

            if (useProxyVariable)
            {
                writer.WriteLine("const unsigned char *bitmap{0} = bitmap;", resource.Id);
                writer.WriteLine();
            }
        }
Example #27
0
        public override void CopyResources(string src, string dest)
        {
            ResourceInfo srcInfo = new ResourceInfo();
            ResourceInfo dstInfo = new ResourceInfo();

            srcInfo.Load(src);
            dstInfo.Load(dest);

            Kernel32.ResourceTypes resType = 0;
            switch (ResourceType)
            {
            case ResourceType.Icon:
                resType = Kernel32.ResourceTypes.RT_GROUP_ICON;
                break;

            case ResourceType.Bitmap:
                resType = Kernel32.ResourceTypes.RT_BITMAP;
                break;

            default:
                Debug.Fail("Unknown resource type");
                break;
            }

            List <Resource> resourcesToReplace = new List <Resource>();

            foreach (Resource res in srcInfo[resType])
            {
                if (Ids == null || Ids.Contains(res.Name.Name))
                {
                    // Find matching resource in destination file
                    Resource dstRes = dstInfo[resType].Single(dr => dr.Name.Equals(res.Name));

                    res.LoadFrom(src);
                    dstRes.LoadFrom(dest);

                    res.Language = dstRes.Language;

                    // Do some checks
                    if (ResourceType == VSIconSwitcher.ResourceType.Icon)
                    {
                        IconDirectoryResource srcIconDirectory = res as IconDirectoryResource;
                        IconDirectoryResource dstIconDirectory = dstRes as IconDirectoryResource;
                        //Debug.Assert(srcIconDirectory.Icons.Count == dstIconDirectory.Icons.Count, "Source/destination icon directory count should match.");
                    }
                    else if (ResourceType == VSIconSwitcher.ResourceType.Bitmap)
                    {
                        BitmapResource srcBitmap = res as BitmapResource;
                        BitmapResource dstBitmap = dstRes as BitmapResource;
                        Debug.Assert(srcBitmap.Bitmap.Header.biHeight == dstBitmap.Bitmap.Header.biHeight, "Source/destination bitmap height dimension should match.");
                        Debug.Assert(srcBitmap.Bitmap.Header.biWidth == dstBitmap.Bitmap.Header.biWidth, "Source/destination bitmap height dimension should match.");
                    }

                    resourcesToReplace.Add(res);
                }
            }

            dstInfo.Unload();

            foreach (Resource res in resourcesToReplace)
            {
                res.SaveTo(dest);
            }

            srcInfo.Unload();
        }
Example #28
0
 public BitmapRenderComponent(string pAlias)
 {
     Bitmap = ResourceManager.Request <BitmapResource>(pAlias);
 }