예제 #1
0
        public override SpriteFontContent Process(FontDescription input,
                                                  ContentProcessorContext context)
        {
            var output = new SpriteFontContent(input);

            var fontName = input.FontName;

#if WINDOWS
            var windowsfolder = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
            var fontDirectory = Path.Combine(windowsfolder, "Fonts");
            fontName = FindFontFileFromFontName(fontName, fontDirectory);
            if (string.IsNullOrWhiteSpace(fontName))
            {
                fontName = input.FontName;
#endif

            var directory   = Path.GetDirectoryName(input.Identity.SourceFilename);
            var directories = new string[] { directory,
                                             "/Library/Fonts",
#if WINDOWS
                                             fontDirectory,
#endif
            }
            ;

            foreach (var dir in directories)
            {
                if (File.Exists(Path.Combine(dir, fontName + ".ttf")))
                {
                    fontName += ".ttf";
                    directory = dir;
                    break;
                }
                if (File.Exists(Path.Combine(dir, fontName + ".ttc")))
                {
                    fontName += ".ttc";
                    directory = dir;
                    break;
                }
                if (File.Exists(Path.Combine(dir, fontName + ".otf")))
                {
                    fontName += ".otf";
                    directory = dir;
                    break;
                }
            }

            fontName = Path.Combine(directory, fontName);
#if WINDOWS
        }
#endif

            context.Logger.LogMessage("Building Font {0}", fontName);
            try {
                if (!File.Exists(fontName))
                {
                    throw new Exception(string.Format("Could not load {0}", fontName));
                }
                var lineSpacing = 0f;
                var glyphs      = ImportFont(input, out lineSpacing, context, fontName);

                // Optimize.
                foreach (Glyph glyph in glyphs)
                {
                    GlyphCropper.Crop(glyph);
                }

                Bitmap outputBitmap = GlyphPacker.ArrangeGlyphs(glyphs, true, true);

                //outputBitmap.Save ("/Users/Jimmy/Desktop/Cocos2D-XNAImages/fontglyphs.png");

                // Adjust line and character spacing.
                lineSpacing += input.Spacing;

                foreach (Glyph glyph in glyphs)
                {
                    glyph.XAdvance += input.Spacing;
                    if (!output.CharacterMap.Contains(glyph.Character))
                    {
                        output.CharacterMap.Add(glyph.Character);
                    }
                    output.Glyphs.Add(new Rectangle(glyph.Subrect.X, glyph.Subrect.Y, glyph.Subrect.Width, glyph.Subrect.Height));
                    output.Cropping.Add(new Rectangle(0, (int)(glyph.YOffset + glyphs.Select(x => x.YOffset).Max()), glyph.Subrect.Width, glyph.Subrect.Height));
                    ABCFloat abc = glyph.CharacterWidths;
                    output.Kerning.Add(new Vector3(abc.A, abc.B, abc.C));
                }

//				outputBitmap.Save("/Users/Jimmy/Desktop/Cocos2D-XNAImages/test.png");
                output.Texture._bitmap = outputBitmap;

                var bitmapContent = new PixelBitmapContent <Color>(outputBitmap.Width, outputBitmap.Height);
                bitmapContent.SetPixelData(outputBitmap.GetData());
                output.Texture.Faces.Add(new MipmapChain(bitmapContent));

                GraphicsUtil.CompressTexture(output.Texture, context, false, false);
            }
            catch (Exception ex) {
                context.Logger.LogImportantMessage("{0}", ex.ToString());
            }

            return(output);
        }
        public void Save()
        {
            if (String.IsNullOrEmpty(oldImg.Value) || oldImg.Value != LargeImage)
            {
                PROD_IMAGES image = new PROD_IMAGES();
                image.Image      = Image;
                image.Principal  = Principal;
                image.LargeImage = LargeImage;
                image.Thumbnail  = Thumbnail;
                image.ProductID  = Int32.Parse(ProdID);

                int id = 0;
                lblErrors.Visible   = true;
                lblErrors.ForeColor = Color.Green;
                string operation = String.Empty;

                try
                {
                    GraphicsUtil.SaveProductImages(LargeImage, Principal);

                    // TODO the following code should be removed as it was encapsulated in the GraphicsUtil.SaveProductImages method
                    //string fileWithPath = Path.Combine(Configuration.ImagesUploadPath, LargeImage);
                    //string thumbWithPath = Path.Combine(Configuration.ImagesUploadPath, Thumbnail);
                    //System.Drawing.Image img = System.Drawing.Image.FromFile(fileWithPath);
                    //FileInfo fi2 = new FileInfo(thumbWithPath);
                    //if (!fi2.Exists)
                    //{

                    //    using (System.Drawing.Image imgResized = GraphicsUtil.ResizeProductImage(img, ImageType.Small))
                    //    {
                    //        imgResized.Save(thumbWithPath);
                    //    }
                    //}

                    //string mediumWithPath = Path.Combine(Configuration.ImagesUploadPath, Image);
                    //fi2 = new FileInfo(mediumWithPath);
                    //if (!fi2.Exists)
                    //{
                    //    using (System.Drawing.Image imgResized = GraphicsUtil.ResizeProductImage(img, ImageType.Medium))
                    //    {
                    //        imgResized.Save(mediumWithPath);
                    //    }
                    //}


                    //if (Principal && !String.IsNullOrEmpty(image.Image))
                    //{
                    //    //string fileWithPath = Path.Combine(Server.MapPath(Configuration.ImagesUploadPath), image.Image);
                    //    //string fileListWithPath = Path.Combine(Server.MapPath(Configuration.ImagesUploadPath), "LIST" + image.Image);

                    //    string fileListWithPath = Path.Combine(Configuration.ImagesUploadPath, "LIST" + image.LargeImage);

                    //    FileInfo fi = new FileInfo(fileListWithPath);
                    //    if (!fi.Exists)
                    //    {
                    //        using (System.Drawing.Image imgResized = GraphicsUtil.ResizeProductImage(img, ImageType.List))
                    //        {
                    //            imgResized.Save(fileListWithPath);
                    //        }
                    //    }
                    //}

                    //img.Dispose();
                    //img = null;

                    if (!String.IsNullOrWhiteSpace(ImgID) && Int32.TryParse(ImgID, out id) && id != 0)
                    {
                        image.ID = id;
                        ApplicationContext.Current.Products.UpdateImage(image);
                        operation = "updated";
                    }
                    else
                    {
                        ApplicationContext.Current.Products.InsertImage(image);
                        operation = "inserted";
                        ImgID     = image.ID.ToString();
                    }
                    lblErrors.Text = "Images " + operation + " correctly.";
                    oldImg.Value   = LargeImage;
                    if (!String.IsNullOrEmpty(Page.User.Identity.Name))
                    {
                        USER user = ApplicationContext.Current.Users.GetByUserName(Page.User.Identity.Name);
                        // not an administrator neither a moderator
                        if (user.RoleID <= 2)
                        {
                            lnkDelete.Visible = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    // TODO log error
                    lblErrors.ForeColor = Color.Red;
                    lblErrors.Text      = "Error occurred: " + ex.Message;
                }
            }
        }
예제 #3
0
 // Toggles the boolean controlling whether images should be compressed.
 public void ToggleImageCompression(Office.IRibbonControl control, bool pressed)
 {
     ShouldCompressImages = pressed;
     _ribbon.InvalidateControl("ShouldCompressImagesCheckbox");
     GraphicsUtil.ShouldCompressPictureExport(ShouldCompressImages);
 }
예제 #4
0
        public override void Render(Graphics destinationGraphics, Rectangle destinationRectangle)
        {
            if (!_imagesLoaded)
            {
                LoadImageResources();
            }
            lock (_imagesLock)
            {
                //store the canvas's transform and clip settings so we can restore them later
                var initialState = destinationGraphics.Save();

                //set up the canvas scale and clipping region
                var width  = _background.Width;
                var height = _background.Height - 29;
                width -= 154;
                destinationGraphics.ResetTransform();              //clear any existing transforms
                destinationGraphics.SetClip(destinationRectangle); //set the clipping region on the graphics object to our render rectangle's boundaries
                destinationGraphics.FillRectangle(Brushes.Black, destinationRectangle);
                destinationGraphics.ScaleTransform(destinationRectangle.Width / (float)width, destinationRectangle.Height / (float)height);
                //set the initial scale transformation

                destinationGraphics.TranslateTransform(-76, 0);
                destinationGraphics.TranslateTransform(0, -15);
                //save the basic canvas transform and clip settings so we can revert to them later, as needed
                var basicState = destinationGraphics.Save();

                //draw the background image
                GraphicsUtil.RestoreGraphicsState(destinationGraphics, ref basicState);
                destinationGraphics.DrawImageFast(
                    _background, new Rectangle(0, 0, _background.Width, _background.Height), new Rectangle(0, 0, _background.Width, _background.Height), GraphicsUnit.Pixel);
                GraphicsUtil.RestoreGraphicsState(destinationGraphics, ref basicState);

                //draw the OFF flag
                if (InstrumentState.OffFlag)
                {
                    GraphicsUtil.RestoreGraphicsState(destinationGraphics, ref basicState);
                    destinationGraphics.DrawImageFast(_offFlag.MaskedImage, new Point(0, 0));
                    GraphicsUtil.RestoreGraphicsState(destinationGraphics, ref basicState);
                }

                //draw the needle
                const float centerX = 156.0f;
                const float centerY = 130.0f;
                var         vv      = InstrumentState.VerticalVelocityFeet;
                if (Math.Abs(vv) > 6000.0)
                {
                    vv = Math.Sign(vv) * 6000.0f;
                }
                var   vviInThousands = vv / 1000.0f;
                float angle;
                if (Math.Abs(vviInThousands) > 1.0f)
                {
                    angle = -45.0f + Math.Sign(vviInThousands) * ((Math.Abs(vviInThousands) - 1.0f) * (45.0f / 5.0f));
                    if (vviInThousands < 0)
                    {
                        angle -= 90;
                    }
                }
                else
                {
                    angle = -90.0f + vviInThousands * 45.0f;
                }
                GraphicsUtil.RestoreGraphicsState(destinationGraphics, ref basicState);
                destinationGraphics.TranslateTransform(centerX, centerY);
                destinationGraphics.RotateTransform(angle);
                destinationGraphics.TranslateTransform(-centerX, -centerY);
                destinationGraphics.TranslateTransform(28, 0);
                destinationGraphics.DrawImageFast(_needle.MaskedImage, new Point(0, 0));
                GraphicsUtil.RestoreGraphicsState(destinationGraphics, ref basicState);

                //restore the canvas's transform and clip settings to what they were when we entered this method
                destinationGraphics.Restore(initialState);
            }
        }
예제 #5
0
 protected override int GetShader() => GraphicsUtil.GetShaderProgram("Resources/Shaders/Sprites.vert.glsl", "Resources/Shaders/DepthMask.frag.glsl");
예제 #6
0
        public override TextureContent Process(TextureContent input, ContentProcessorContext context)
        {
            if (ColorKeyEnabled)
            {
                var replaceColor = System.Drawing.Color.FromArgb(0);
                for (var x = 0; x < input._bitmap.Width; x++)
                {
                    for (var y = 0; y < input._bitmap.Height; y++)
                    {
                        var col = input._bitmap.GetPixel(x, y);

                        if (col.ColorsEqual(ColorKeyColor))
                        {
                            input._bitmap.SetPixel(x, y, replaceColor);
                        }
                    }
                }
            }

            var face = input.Faces[0][0];

            if (ResizeToPowerOfTwo)
            {
                if (!GraphicsUtil.IsPowerOfTwo(face.Width) || !GraphicsUtil.IsPowerOfTwo(face.Height))
                {
                    input.Resize(GraphicsUtil.GetNextPowerOfTwo(face.Width), GraphicsUtil.GetNextPowerOfTwo(face.Height));
                }
            }

            if (PremultiplyAlpha)
            {
                for (var x = 0; x < input._bitmap.Width; x++)
                {
                    for (var y = 0; y < input._bitmap.Height; y++)
                    {
                        var oldCol             = input._bitmap.GetPixel(x, y);
                        var preMultipliedColor = Color.FromNonPremultiplied(oldCol.R, oldCol.G, oldCol.B, oldCol.A);
                        input._bitmap.SetPixel(x, y, System.Drawing.Color.FromArgb(preMultipliedColor.A,
                                                                                   preMultipliedColor.R,
                                                                                   preMultipliedColor.G,
                                                                                   preMultipliedColor.B));
                    }
                }
            }

            // Set the first layer
            input.Faces[0][0].SetPixelData(input._bitmap.GetData());

            if (TextureFormat == TextureProcessorOutputFormat.NoChange)
            {
                return(input);
            }
            try
            {
                if (TextureFormat == TextureProcessorOutputFormat.DXTCompressed ||
                    TextureFormat == TextureProcessorOutputFormat.Compressed)
                {
                    context.Logger.LogMessage("Compressing using {0}", TextureFormat);
                }
                GraphicsUtil.CompressTexture(input, context, GenerateMipmaps, PremultiplyAlpha);
                context.Logger.LogMessage("Compression {0} Suceeded", TextureFormat);
            }
            catch (EntryPointNotFoundException ex) {
                context.Logger.LogImportantMessage("Could not find the entry point to compress the texture", ex.ToString());
                TextureFormat = TextureProcessorOutputFormat.Color;
            }
            catch (DllNotFoundException ex) {
                context.Logger.LogImportantMessage("Could not compress texture. Required shared lib is missing. {0}", ex.ToString());
                TextureFormat = TextureProcessorOutputFormat.Color;
            }
            catch (Exception ex)
            {
                context.Logger.LogImportantMessage("Could not compress texture {0}", ex.ToString());
                TextureFormat = TextureProcessorOutputFormat.Color;
            }

            return(input);
        }
        public override void Render(Graphics destinationGraphics, Rectangle destinationRectangle)
        {
            if (!_imagesLoaded)
            {
                LoadImageResources();
            }
            lock (_imagesLock)
            {
                //store the canvas's transform and clip settings so we can restore them later
                var initialState = destinationGraphics.Save();

                //set up the canvas scale and clipping region
                var width = _background.Image.Width;
                width -= 154;
                var height = _background.Image.Height - 29;
                destinationGraphics.ResetTransform();              //clear any existing transforms
                destinationGraphics.SetClip(destinationRectangle); //set the clipping region on the graphics object to our render rectangle's boundaries
                destinationGraphics.FillRectangle(Brushes.Black, destinationRectangle);
                destinationGraphics.ScaleTransform(destinationRectangle.Width / (float)width, destinationRectangle.Height / (float)height);
                //set the initial scale transformation
                destinationGraphics.TranslateTransform(-76, 0);
                destinationGraphics.TranslateTransform(0, -15);
                //save the basic canvas transform and clip settings so we can revert to them later, as needed
                var basicState = destinationGraphics.Save();

                if (!InstrumentState.OffFlag)
                {
                    //draw the number tape
                    GraphicsUtil.RestoreGraphicsState(destinationGraphics, ref basicState);
                    const float translateX           = 110;
                    float       translateY           = 236;
                    const float pixelsPerHundredFeet = 4.75f;
                    var         vv = InstrumentState.VerticalVelocityFeet;
                    if (Math.Abs(vv) > 6000.0)
                    {
                        vv = Math.Sign(vv) * 6000.0f;
                    }
                    var verticalVelocityThousands = vv / 1000.0f;
                    translateY -= -pixelsPerHundredFeet * verticalVelocityThousands * 10.0f;
                    translateY -= _numberTape.Height / 2.0f;
                    destinationGraphics.TranslateTransform(translateX, translateY);
                    destinationGraphics.ScaleTransform(0.79f, 0.79f);
                    destinationGraphics.DrawImageFast(_numberTape, new Point(0, 0));
                    GraphicsUtil.RestoreGraphicsState(destinationGraphics, ref basicState);
                }
                //draw the background image
                GraphicsUtil.RestoreGraphicsState(destinationGraphics, ref basicState);
                destinationGraphics.DrawImageFast(_background.MaskedImage, new Point(0, 0));
                GraphicsUtil.RestoreGraphicsState(destinationGraphics, ref basicState);

                //draw the indicator line
                GraphicsUtil.RestoreGraphicsState(destinationGraphics, ref basicState);
                destinationGraphics.TranslateTransform(0, 1);
                destinationGraphics.DrawImageFast(_indicatorLine.MaskedImage, new Point(0, 0));
                GraphicsUtil.RestoreGraphicsState(destinationGraphics, ref basicState);

                //draw the OFF flag
                if (InstrumentState.OffFlag)
                {
                    GraphicsUtil.RestoreGraphicsState(destinationGraphics, ref basicState);
                    destinationGraphics.TranslateTransform(0, -3);
                    destinationGraphics.DrawImageFast(_offFlag.MaskedImage, new Point(0, 0));
                    GraphicsUtil.RestoreGraphicsState(destinationGraphics, ref basicState);
                }

                //restore the canvas's transform and clip settings to what they were when we entered this method
                destinationGraphics.Restore(initialState);
            }
        }
예제 #8
0
 public TooltipsLabSettingsShapeEntry(MsoAutoShapeType type, Bitmap image)
 {
     InitializeComponent();
     Type            = type;
     imageBox.Source = GraphicsUtil.BitmapToImageSource(image);
 }
예제 #9
0
 protected virtual int GetShader() => GraphicsUtil.GetShaderProgram(
     "Resources/Shaders/Triangles.vert.glsl",
     "Resources/Shaders/Triangles.frag.glsl",
     "Resources/Shaders/Triangles.geom.glsl");
 private Color GetColor(SolidColorBrush brush)
 {
     return(GraphicsUtil.DrawingColorFromBrush(brush));
 }
 public static void drawNumberByImage(Graphics g, int number, int x, int y, int anchor)
 {
     if (imgFonts == null)
     {
         imgFonts = new Image[11];
         if (instance == null)
         {
             instance = new GraphicsUtil();
         }
         imgFonts[0] = IOUtil.createImage(instance.GetType().Assembly.GetManifestResourceStream("Cyclone.Resources.font_0.png"));
         imgFonts[1] = IOUtil.createImage(instance.GetType().Assembly.GetManifestResourceStream("Cyclone.Resources.font_1.png"));
         imgFonts[2] = IOUtil.createImage(instance.GetType().Assembly.GetManifestResourceStream("Cyclone.Resources.font_2.png"));
         imgFonts[3] = IOUtil.createImage(instance.GetType().Assembly.GetManifestResourceStream("Cyclone.Resources.font_3.png"));
         imgFonts[4] = IOUtil.createImage(instance.GetType().Assembly.GetManifestResourceStream("Cyclone.Resources.font_4.png"));
         imgFonts[5] = IOUtil.createImage(instance.GetType().Assembly.GetManifestResourceStream("Cyclone.Resources.font_5.png"));
         imgFonts[6] = IOUtil.createImage(instance.GetType().Assembly.GetManifestResourceStream("Cyclone.Resources.font_6.png"));
         imgFonts[7] = IOUtil.createImage(instance.GetType().Assembly.GetManifestResourceStream("Cyclone.Resources.font_7.png"));
         imgFonts[8] = IOUtil.createImage(instance.GetType().Assembly.GetManifestResourceStream("Cyclone.Resources.font_8.png"));
         imgFonts[9] = IOUtil.createImage(instance.GetType().Assembly.GetManifestResourceStream("Cyclone.Resources.font_9.png"));
         imgFonts[10] = IOUtil.createImage(instance.GetType().Assembly.GetManifestResourceStream("Cyclone.Resources.font_10.png"));
     }
     drawNumberByImage(g, imgFonts, number, x, y, 1, anchor);
 }
예제 #12
0
        public override TextureContent Process(TextureContent input, ContentProcessorContext context)
        {
            var bmp = input.Faces[0][0];

            if (ColorKeyEnabled)
            {
                var data = bmp.GetPixelData();
                var idx  = 0;
                for (; idx < data.Length;)
                {
                    var r   = data[idx + 0];
                    var g   = data[idx + 1];
                    var b   = data[idx + 2];
                    var a   = data[idx + 3];
                    var col = new Color(r, g, b, a);
                    if (col.Equals(ColorKeyColor))
                    {
                        data[idx + 0] = 0;
                        data[idx + 1] = 0;
                        data[idx + 2] = 0;
                        data[idx + 3] = 0;
                    }

                    idx += 4;
                }

                bmp.SetPixelData(data);
            }


            if (ResizeToPowerOfTwo)
            {
                if (!GraphicsUtil.IsPowerOfTwo(bmp.Width) || !GraphicsUtil.IsPowerOfTwo(bmp.Height))
                {
                    input.Resize(GraphicsUtil.GetNextPowerOfTwo(bmp.Width), GraphicsUtil.GetNextPowerOfTwo(bmp.Height));
                    bmp = input.Faces[0][0];
                }
            }

            if (PremultiplyAlpha)
            {
                var data = bmp.GetPixelData();
                var idx  = 0;
                for (; idx < data.Length;)
                {
                    var r   = data[idx + 0];
                    var g   = data[idx + 1];
                    var b   = data[idx + 2];
                    var a   = data[idx + 3];
                    var col = Color.FromNonPremultiplied(r, g, b, a);

                    data[idx + 0] = col.R;
                    data[idx + 1] = col.G;
                    data[idx + 2] = col.B;
                    data[idx + 3] = col.A;

                    idx += 4;
                }

                bmp.SetPixelData(data);
            }

            if (TextureFormat == TextureProcessorOutputFormat.NoChange)
            {
                return(input);
            }

            try
            {
                if (TextureFormat == TextureProcessorOutputFormat.DxtCompressed ||
                    TextureFormat == TextureProcessorOutputFormat.Compressed)
                {
                    GraphicsUtil.CompressTexture(context.TargetProfile, input, context, GenerateMipmaps, PremultiplyAlpha, false);
                }
            }
            catch (EntryPointNotFoundException ex) {
                context.Logger.LogImportantMessage("Could not find the entry point to compress the texture", ex.ToString());
                TextureFormat = TextureProcessorOutputFormat.Color;
            }
            catch (DllNotFoundException ex) {
                context.Logger.LogImportantMessage("Could not compress texture. Required shared lib is missing. {0}", ex.ToString());
                TextureFormat = TextureProcessorOutputFormat.Color;
            }
            catch (Exception ex)
            {
                context.Logger.LogImportantMessage("Could not compress texture {0}", ex.ToString());
                TextureFormat = TextureProcessorOutputFormat.Color;
            }

            // Generate mipmaps for the non-compressed textures.
            if (GenerateMipmaps && TextureFormat == TextureProcessorOutputFormat.Color)
            {
                context.Logger.LogMessage("Generating mipmaps.");
                input.GenerateMipmaps(false);
            }

            return(input);
        }
예제 #13
0
        public void Generate(Client tclient, ClientCVar cvars, TextureEngine eng, bool delayable)
        {
            TheClient = tclient;
            if (TextureID > -1)
            {
                GL.DeleteTexture(TextureID);
                GL.DeleteTexture(NormalTextureID);
                GL.DeleteTexture(HelpTextureID);
            }
            List <MaterialTextureInfo> texs = new List <MaterialTextureInfo>(MaterialHelpers.Textures.Length);

            TexList = texs;
            int extras = 0;

            for (int i = 0; i < MaterialHelpers.Textures.Length; i++)
            {
                string[] basic = MaterialHelpers.Textures[i].SplitFast('@')[0].SplitFast('$')[0].SplitFast('%')[0].SplitFast(',');
                texs.Add(new MaterialTextureInfo()
                {
                    Mat = i, ResultantID = extras
                });
                extras += basic.Length;
            }
            TEngine   = eng;
            TextureID = GL.GenTexture();
            TWidth    = cvars.r_blocktexturewidth.ValueI;
            HelpTWMin = TEX_REQUIRED_BITS / (TWidth * TWidth);
            GL.BindTexture(TextureTarget.Texture2DArray, TextureID);
            int levels = TheClient.CVars.r_block_mipmaps.ValueB ? (TWidth == 256 ? 6 : 4) : 1; // TODO: 6/4 -> Setting

            GL.TexStorage3D(TextureTarget3d.Texture2DArray, levels, SizedInternalFormat.Rgba8, TWidth, TWidth, extras);
            GL.GenerateMipmap(GenerateMipmapTarget.Texture2DArray);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMinFilter, (int)(cvars.r_blocktexturelinear.ValueB ? TextureMinFilter.LinearMipmapLinear : TextureMinFilter.Nearest));
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMagFilter, (int)(cvars.r_blocktexturelinear.ValueB ? TextureMagFilter.Linear : TextureMagFilter.Nearest));
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
            HelpTextureID = GL.GenTexture();
            GL.BindTexture(TextureTarget.Texture2DArray, HelpTextureID);
            GL.TexStorage3D(TextureTarget3d.Texture2DArray, levels, SizedInternalFormat.Rgba8, TWidth, TWidth, extras + HelpTWMin);
            GL.GenerateMipmap(GenerateMipmapTarget.Texture2DArray);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
            NormalTextureID = GL.GenTexture();
            GL.BindTexture(TextureTarget.Texture2DArray, NormalTextureID);
            GL.TexStorage3D(TextureTarget3d.Texture2DArray, levels, SizedInternalFormat.Rgba8, TWidth, TWidth, extras);
            GL.GenerateMipmap(GenerateMipmapTarget.Texture2DArray);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
            // TODO: Use normal.a!
            IntTexs = new string[MaterialHelpers.Textures.Length];
            for (int ia = 0; ia < MaterialHelpers.Textures.Length; ia++)
            {
                int    i = ia;
                Action a = () =>
                {
                    MaterialTextureInfo tex = texs[i];
                    int      resID          = tex.ResultantID;
                    string[] refrornot      = MaterialHelpers.Textures[i].SplitFast('@');
                    if (refrornot.Length > 1)
                    {
                        string[] rorn = refrornot[1].SplitFast('%');
                        if (rorn.Length > 1)
                        {
                            tex.RefrRate = Utilities.StringToFloat(rorn[1]);
                        }
                        tex.RefractTextures = rorn[0].SplitFast(',');
                    }
                    string[] glowornot = refrornot[0].SplitFast('!');
                    if (glowornot.Length > 1)
                    {
                        tex.GlowingTextures = glowornot[1].SplitFast(',');
                    }
                    string[] reflornot = glowornot[0].SplitFast('*');
                    if (reflornot.Length > 1)
                    {
                        tex.ReflectTextures = reflornot[1].SplitFast(',');
                    }
                    string[] specularornot = reflornot[0].SplitFast('&');
                    if (specularornot.Length > 1)
                    {
                        tex.SpecularTextures = specularornot[1].SplitFast(',');
                    }
                    string[] normalornot = specularornot[0].SplitFast('$');
                    GL.BindTexture(TextureTarget.Texture2DArray, NormalTextureID);
                    if (normalornot.Length > 1)
                    {
                        string[] rorn = normalornot[1].SplitFast('%');
                        if (rorn.Length > 1)
                        {
                            tex.NormRate = Utilities.StringToFloat(rorn[1]);
                        }
                        tex.NormalTextures = rorn[0].SplitFast(',');
                        if (tex.NormalTextures.Length > 1)
                        {
                            SetAnimated((int)resID, tex.NormRate, tex.NormalTextures, NormalTextureID, -1);
                        }
                    }
                    else
                    {
                        SetTexture((int)resID, "normal_def", -1);
                    }
                    string[] rateornot = normalornot[0].SplitFast('%');
                    if (rateornot.Length > 1)
                    {
                        tex.Rate = Utilities.StringToFloat(rateornot[1]);
                    }
                    tex.Textures = rateornot[0].SplitFast(',');
                    GL.BindTexture(TextureTarget.Texture2DArray, TextureID);
                    if (tex.Textures.Length > 1)
                    {
                        SetAnimated((int)resID, tex.Rate, tex.Textures, TextureID, resID);
                        if (tex.NormalTextures == null)
                        {
                            GL.BindTexture(TextureTarget.Texture2DArray, NormalTextureID);
                            tex.NormalTextures = new string[tex.Textures.Length];
                            tex.NormRate       = tex.Rate;
                            for (int fz = 0; fz < tex.NormalTextures.Length; fz++)
                            {
                                tex.NormalTextures[fz] = "normal_def";
                            }
                            SetAnimated((int)resID, tex.Rate, tex.NormalTextures, NormalTextureID, -1);
                        }
                    }
                    else
                    {
                        SetTexture((int)resID, tex.Textures[0], resID);
                        if (tex.NormalTextures == null)
                        {
                            tex.NormalTextures = new string[] { "normal_def" };
                        }
                    }
                    if (tex.ReflectTextures == null)
                    {
                        tex.ReflectTextures = new string[tex.Textures.Length];
                        for (int fz = 0; fz < tex.ReflectTextures.Length; fz++)
                        {
                            tex.ReflectTextures[fz] = "black";
                        }
                        tex.RefractTextures  = tex.ReflectTextures;
                        tex.GlowingTextures  = tex.ReflectTextures;
                        tex.SpecularTextures = tex.ReflectTextures;
                    }
                    if (tex.NormRate != tex.Rate || tex.RefrRate != tex.Rate)
                    {
                        SysConsole.Output(OutputType.WARNING, "Rates wrong for " + MaterialHelpers.Textures[i]);
                        tex.NormRate = tex.Rate;
                        tex.RefrRate = tex.Rate;
                    }
                    if (tex.Textures.Length != tex.NormalTextures.Length || tex.ReflectTextures.Length != tex.Textures.Length)
                    {
                        SysConsole.Output(OutputType.WARNING, "Texture counts wrong for " + MaterialHelpers.Textures[i]);
                    }
                    IntTexs[(int)tex.Mat] = tex.Textures[0];
                    if (!delayable)
                    {
                        TheClient.PassLoadScreen();
                    }
                };
                if (delayable)
                {
                    TheClient.Schedule.ScheduleSyncTask(a, i * LoadRate);
                }
                else
                {
                    a();
                }
            }
            double time = (MaterialHelpers.Textures.Length + 1) * LoadRate;

            for (int ia = 0; ia < texs.Count; ia++)
            {
                int    i = ia;
                Action a = () =>
                {
                    GL.BindTexture(TextureTarget.Texture2DArray, HelpTextureID);
                    Bitmap combo = GetCombo(texs[i], 0);
                    if ((texs[i].SpecularTextures != null) && (texs[i].ReflectTextures != null) && (texs[i].RefractTextures != null) && (texs[i].GlowingTextures != null) && texs[i].SpecularTextures.Length > 1)
                    {
                        Bitmap[] bmps = new Bitmap[texs[i].SpecularTextures.Length];
                        bmps[0] = combo;
                        for (int x = 1; x < bmps.Length; x++)
                        {
                            bmps[x] = GetCombo(texs[i], x);
                        }
                        SetAnimated((int)texs[i].ResultantID + HelpTWMin, texs[i].RefrRate, bmps, HelpTextureID);
                        for (int x = 1; x < bmps.Length; x++)
                        {
                            bmps[x].Dispose();
                        }
                    }
                    else
                    {
                        TEngine.LockBitmapToTexture(combo, (int)texs[i].ResultantID + HelpTWMin);
                    }
                    combo.Dispose();
                    if (!delayable)
                    {
                        TheClient.PassLoadScreen();
                    }
                };
                if (delayable)
                {
                    TheClient.Schedule.ScheduleSyncTask(a, time + i * LoadRate);
                }
                else
                {
                    a();
                }
            }
            if (TheClient.CVars.r_block_mipmaps.ValueB)
            {
                Action mipmap = () =>
                {
                    GL.BindTexture(TextureTarget.Texture2DArray, TextureID);
                    GL.GenerateMipmap(GenerateMipmapTarget.Texture2DArray);
                    GL.BindTexture(TextureTarget.Texture2DArray, NormalTextureID);
                    GL.GenerateMipmap(GenerateMipmapTarget.Texture2DArray);
                    GL.BindTexture(TextureTarget.Texture2DArray, HelpTextureID);
                    GL.GenerateMipmap(GenerateMipmapTarget.Texture2DArray);
                    GraphicsUtil.CheckError("Mipmapping");
                };
                if (delayable)
                {
                    TheClient.Schedule.ScheduleSyncTask(mipmap, time * 2);
                }
                else
                {
                    mipmap();
                }
            }
            GL.BindTexture(TextureTarget.Texture2DArray, 0);
        }
예제 #14
0
        public override void Render(Graphics destinationGraphics, Rectangle destinationRectangle)
        {
            var    gfx        = destinationGraphics;
            Bitmap fullBright = null;

            if (InstrumentState.Brightness != InstrumentState.MaxBrightness)
            {
                fullBright = new Bitmap(destinationRectangle.Size.Width, destinationRectangle.Size.Height, PixelFormat.Format16bppRgb565);
                gfx        = Graphics.FromImage(fullBright);
            }
            //store the canvas's transform and clip settings so we can restore them later
            var initialState = gfx.Save();
            //set up the canvas scale and clipping region
            const int width  = 256;
            const int height = 256;

            gfx.ResetTransform(); //clear any existing transforms
            gfx.SetClip(destinationRectangle);
            //set the clipping region on the graphics object to our render rectangle's boundaries
            gfx.FillRectangle(Brushes.Black, destinationRectangle);
            gfx.ScaleTransform(destinationRectangle.Width / (float)width, destinationRectangle.Height / (float)height);
            //set the initial scale transformation

            //save the basic canvas transform and clip settings so we can revert to them later, as needed
            var basicState = gfx.Save();

            GraphicsUtil.RestoreGraphicsState(gfx, ref basicState);
            gfx.TranslateTransform(-7, 0);
            AttitudeRenderer.DrawAttitude(gfx, width, height, InstrumentState, Fonts.Value);
            GraphicsUtil.RestoreGraphicsState(gfx, ref basicState);

            //draw heading tape
            var headingTapeSize = HeadingTapeRenderer.DrawHeadingTape(gfx, width, height, ref basicState, InstrumentState, Fonts.Value);

            //draw heading triangle
            HeadingTriangleRenderer.DrawHeadingTriangle(gfx, ref basicState, width, height, headingTapeSize);

            //draw airspeed tape
            AirspeedTapeRenderer.DrawAirspeedTape(gfx, ref basicState, height, InstrumentState, Fonts.Value);

            //draw altitude tape
            AltitudeTapeRenderer.DrawAltitudeTape(gfx, ref basicState, width, height, InstrumentState, Fonts.Value);

            //draw top rectangle
            var topRectangle = TopRectangleRenderer.DrawTopRectangle(gfx, width, ref basicState);

            //draw mach rectangle
            MachRectangleRenderer.DrawMachRectangle(gfx, ref basicState, topRectangle, InstrumentState, Fonts.Value);

            //draw the radar altimeter area
            RadarAltimeterAreaRenderer.DrawRadarAltimeterArea(gfx, ref basicState, topRectangle, InstrumentState, Options, Fonts.Value);

            //draw the barometric pressure area
            BarometricPressureAreaRenderer.DrawBarometricPressureArea(gfx, ref basicState, topRectangle, InstrumentState, Options, Fonts.Value);

            //draw the ILS bars
            ILSBarsRenderer.DrawIlsBars(gfx, width, height, ref basicState, InstrumentState);

            //restore the canvas's transform and clip settings to what they were when we entered this method
            gfx.Restore(initialState);

            if (fullBright != null)
            {
                var ia            = new ImageAttributes();
                var dimmingMatrix = Util.GetDimmingColorMatrix(InstrumentState.Brightness / (float)InstrumentState.MaxBrightness);
                ia.SetColorMatrix(dimmingMatrix);
                destinationGraphics.DrawImageFast(fullBright, destinationRectangle, 0, 0, fullBright.Width, fullBright.Height, GraphicsUnit.Pixel, ia);
                Common.Util.DisposeObject(gfx);
                Common.Util.DisposeObject(fullBright);
            }
        }
 private SKColor GetRandomColor()
 {
     return(SKColor.Parse(GraphicsUtil.HexConverter()));
 }
예제 #16
0
        public override void Draw(CGRect rect)
        {
            const int padright = 21;
            var       ctx      = UIGraphics.GetCurrentContext();
            nfloat    boxWidth;
            CGSize    ssize;

            if (MessageCount > 0)
            {
                var ms = MessageCount.ToString();
                ssize    = ms.StringSize(CountFont);
                boxWidth = NMath.Min(22 + ssize.Width, 18);
                var crect = new CGRect(Bounds.Width - 20 - boxWidth, 32, boxWidth, 16);

                UIColor.Gray.SetFill();
                GraphicsUtil.FillRoundedRect(ctx, crect, 3);
                UIColor.White.SetColor();
                crect.X += 5;
                ms.DrawString(crect, CountFont);

                boxWidth += padright;
            }
            else
            {
                boxWidth = 0;
            }

            UIColor.FromRGB(36, 112, 216).SetColor();
            var    diff = DateTime.Now - Date;
            string label;

            if (DateTime.Now.Day == Date.Day)
            {
                label = Date.ToShortTimeString();
            }
            else if (diff <= TimeSpan.FromHours(24))
            {
                label = "Yesterday".GetText();
            }
            else if (diff < TimeSpan.FromDays(6))
            {
                label = Date.ToString("dddd");
            }
            else
            {
                label = Date.ToShortDateString();
            }
            ssize = label.StringSize(SubjectFont);
            nfloat dateSize = ssize.Width + padright + 5;

            label.DrawString(new CGRect(Bounds.Width - dateSize, 6, dateSize, 14), SubjectFont,
                             UILineBreakMode.Clip, UITextAlignment.Left);

            const int offset = 33;
            nfloat    bw     = Bounds.Width - offset;

            UIColor.Black.SetColor();
            Sender.DrawString(new CGPoint(offset, 2), bw - dateSize, SenderFont, UILineBreakMode.TailTruncation);
            Subject.DrawString(new CGPoint(offset, 23), bw - offset - boxWidth, SubjectFont,
                               UILineBreakMode.TailTruncation);

            //UIColor.Black.SetFill ();
            //ctx.FillRect (new CGRect(offset, 40, bw - boxWidth, 34));
            UIColor.Gray.SetColor();
            Body.DrawString(new CGRect(offset, 40, bw - boxWidth, 34), TextFont, UILineBreakMode.TailTruncation,
                            UITextAlignment.Left);

            if (NewFlag)
            {
                ctx.SaveState();
                ctx.AddEllipseInRect(new CGRect(10, 32, 12, 12));
                ctx.Clip();
                ctx.DrawLinearGradient(Gradient, new CGPoint(10, 32), new CGPoint(22, 44),
                                       CGGradientDrawingOptions.DrawsAfterEndLocation);
                ctx.RestoreState();
            }

#if WANT_SHADOWS
            ctx.SaveState();
            UIColor.FromRGB(78, 122, 198).SetStroke();
            ctx.SetShadow(new CGSize(1, 1), 3);
            ctx.StrokeEllipseInRect(new CGRect(10, 32, 12, 12));
            ctx.RestoreState();
#endif
        }
예제 #17
0
        public TransparencyRenderer(int maxDepthComplexity)
        {
            shader = GraphicsUtil.GetShaderProgram("Resources/Shaders/Sprites.vert.glsl", "Resources/Shaders/BlendTransparency.frag.glsl");
            Init(1);
            SpriteRenderer.GenSpriteVAO(vertexArray, instanceBuffer);
            instances.Add(new SpriteRenderer.InstanceData()
            {
                transform = Matrix4.CreateScale(2), textureIndex = 0
            });
            UpdateBuffer(instances.Count);

            maskFBO     = GL.GenFramebuffer();
            colorBuffer = GL.GenTexture();

            canStencil = true;
            //Generate the Framebuffer for creating the masks front to back
tryMakeMaskFBO:
            maskFBO       = GL.GenFramebuffer();
            stencilBuffer = GL.GenRenderbuffer();
            renderTexture = GL.GenTexture();
            renderFBO     = GL.GenFramebuffer();
            originalDepth = GL.GenTexture();

            GL.BindFramebuffer(FramebufferTarget.Framebuffer, renderFBO);
            GL.FramebufferTexture(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, renderTexture, 0);
            GL.DrawBuffers(1, new[] { DrawBuffersEnum.ColorAttachment0 });

            GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);

            SetMaxDepthComplexity(maxDepthComplexity);

            SetDimensions(800, 600);

            GL.BindFramebuffer(FramebufferTarget.Framebuffer, maskFBO);
            GL.FramebufferTexture(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthAttachment, maskTexture[0], 0);
            if (canStencil)
            {
                GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferAttachment.StencilAttachment, RenderbufferTarget.Renderbuffer, stencilBuffer);
            }
            GL.DrawBuffer(DrawBufferMode.None);

            FramebufferErrorCode error;

            if ((error = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer)) != FramebufferErrorCode.FramebufferComplete)
            {
                GL.DeleteFramebuffer(maskFBO);
                if (!canStencil)
                {
                    throw new NotSupportedException("Transparency rendering doesn't work on this system.");
                }
                canStencil = false;
                goto tryMakeMaskFBO;
            }

            originalDepthFBO = GL.GenFramebuffer();
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, originalDepthFBO);
            GL.FramebufferTexture(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthAttachment, originalDepth, 0);
            GL.DrawBuffers(0, new DrawBuffersEnum[0]);

            if ((error = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer)) != FramebufferErrorCode.FramebufferComplete)
            {
                throw null;
            }

            GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
        }
        DrawVertexCategoryShape
        (
            DrawingObjects oDrawingObjects,
            VertexShape eVertexShape,
            Pen oPen,
            SolidBrush oBrush,
            Color oColor,
            Single fXShapeCenter,
            Single fYShapeCenter,
            Single fShapeHalfWidth
        )
        {
            Debug.Assert(oDrawingObjects != null);
            Debug.Assert(oPen != null);
            Debug.Assert(oBrush != null);
            Debug.Assert(fShapeHalfWidth >= 0);
            AssertValid();

            Graphics oGraphics = oDrawingObjects.Graphics;

            oPen.Color   = oColor;
            oBrush.Color = oColor;

            switch (eVertexShape)
            {
            case VertexShape.Circle:

                GraphicsUtil.DrawCircle(oGraphics, oPen, fXShapeCenter,
                                        fYShapeCenter, fShapeHalfWidth);

                break;

            case VertexShape.Disk:

                GraphicsUtil.FillCircle(oGraphics, oBrush, fXShapeCenter,
                                        fYShapeCenter, fShapeHalfWidth);

                break;

            case VertexShape.Sphere:

                GraphicsUtil.FillCircle3D(oGraphics, oColor,
                                          fXShapeCenter, fYShapeCenter, fShapeHalfWidth);

                break;

            case VertexShape.Square:

                GraphicsUtil.DrawSquare(oGraphics, oPen, fXShapeCenter,
                                        fYShapeCenter, fShapeHalfWidth);

                break;

            case VertexShape.SolidSquare:

                GraphicsUtil.FillSquare(oGraphics, oBrush, fXShapeCenter,
                                        fYShapeCenter, fShapeHalfWidth);

                break;

            case VertexShape.Diamond:

                GraphicsUtil.DrawDiamond(oGraphics, oPen, fXShapeCenter,
                                         fYShapeCenter, fShapeHalfWidth);

                break;

            case VertexShape.SolidDiamond:

                GraphicsUtil.FillDiamond(oGraphics, oBrush, fXShapeCenter,
                                         fYShapeCenter, fShapeHalfWidth);

                break;

            case VertexShape.Triangle:

                GraphicsUtil.DrawTriangle(oGraphics, oPen, fXShapeCenter,
                                          fYShapeCenter, fShapeHalfWidth);

                break;

            case VertexShape.SolidTriangle:

                GraphicsUtil.FillTriangle(oGraphics, oBrush, fXShapeCenter,
                                          fYShapeCenter, fShapeHalfWidth);

                break;

            default:

                Debug.Assert(false);
                break;
            }
        }
 public static void GetCursorScreenPosition_Postfix(FPSInputModule __instance, ref Vector2 __result)
 {
     if (XRSettings.enabled)
     {
         if (Cursor.lockState == CursorLockMode.Locked)
         {
             __result = GraphicsUtil.GetScreenSize() * 0.5f;
             return;
         }
         if (!MainPatcher.actualGazedBasedCursor)
         {
             __result = new Vector2(Input.mousePosition.x / (float)Screen.width * GraphicsUtil.GetScreenSize().x, Input.mousePosition.y / (float)Screen.height * GraphicsUtil.GetScreenSize().y);
         }
     }
 }
예제 #20
0
 protected virtual int GetShader() => GraphicsUtil.GetShaderProgram("Resources/Shaders/Sprites.vert.glsl", "Resources/Shaders/Texture.frag.glsl");
예제 #21
0
 /// <summary>
 /// Renders a single frame of the game, and also ticks.
 /// </summary>
 /// <param name="sender">Irrelevant.</param>
 /// <param name="e">Holds the frame time (delta).</param>
 private void Window_RenderFrame(object sender, FrameEventArgs e)
 {
     try
     {
         StackNoteHelper.Push("GameClientWindow - Render and tick frame", this);
         // First step: check delta
         Delta = e.Time;
         CurrentEngine.Delta = Delta;
         if (e.Time <= 0.0)
         {
             return;
         }
         GlobalTickTime += Delta;
         ErrorCode ec = GL.GetError();
         while (ec != ErrorCode.NoError)
         {
             SysConsole.Output(OutputType.WARNING, "Uncaught GL Error: " + ec);
             ec = GL.GetError();
         }
         // Second step: clear the screen
         GL.ClearBuffer(ClearBuffer.Color, 0, ScreenClearColor);
         GL.ClearBuffer(ClearBuffer.Depth, 0, DepthClear);
         GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
         GL.DrawBuffer(DrawBufferMode.Back);
         GraphicsUtil.CheckError("GameClient - Pre");
         // Tick helpers
         Models.Update(GlobalTickTime);
         GraphicsUtil.CheckError("GameClient - PostModelUpdate");
         // Third step: general game rendering
         if (ProcessMainEngine)
         {
             CurrentEngine.RenderSingleFrame();
             GraphicsUtil.CheckError("GameClient - PostMainEngine");
         }
         // Add the UI Layer too
         MainUI.Draw();
         GraphicsUtil.CheckError("GameClient - PostUI");
         // Fourth step: clean up!
         GL.BindTexture(TextureTarget.Texture2D, 0);
         GL.BindVertexArray(0);
         GL.UseProgram(0);
         // Semi-final step: Tick logic!
         GraphicsUtil.CheckError("GameClient - PreTick");
         // Pre-tick.
         ClientEngineTick();
         // Primary entity tick
         if (ProcessMainEngine)
         {
             CurrentEngine.Tick();
         }
         // Primary UI tick
         MainUI.Tick();
         GraphicsUtil.CheckError("GameClient - PostTick");
         // Final step: Swap the render buffer onto the screen!
         Window.SwapBuffers();
         GraphicsUtil.CheckError("GameClient - Post");
     }
     finally
     {
         StackNoteHelper.Pop();
     }
 }
        public override SpriteFontContent Process(FontDescription input,
                                                  ContentProcessorContext context)
        {
            var output = new SpriteFontContent(input);

            var fontName = input.FontName;

#if WINDOWS || LINUX
#if WINDOWS
            var windowsfolder = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
            var fontDirectory = Path.Combine(windowsfolder, "Fonts");
            fontName = FindFontFileFromFontName(fontName, fontDirectory);
#elif LINUX
            fontName = FindFontFileFromFontName(fontName, input.Style.ToString());
#endif
            if (string.IsNullOrWhiteSpace(fontName))
            {
                fontName = input.FontName;
#endif

            var directory = Path.GetDirectoryName(input.Identity.SourceFilename);

            List <string> directories = new List <string>();
            directories.Add(directory);
            directories.Add("/Library/Fonts");
#if WINDOWS
            directories.Add(fontDirectory);
#endif

            foreach (var dir in directories)
            {
                if (File.Exists(Path.Combine(dir, fontName + ".ttf")))
                {
                    fontName += ".ttf";
                    directory = dir;
                    break;
                }
                if (File.Exists(Path.Combine(dir, fontName + ".ttc")))
                {
                    fontName += ".ttc";
                    directory = dir;
                    break;
                }
                if (File.Exists(Path.Combine(dir, fontName + ".otf")))
                {
                    fontName += ".otf";
                    directory = dir;
                    break;
                }
            }

            fontName = Path.Combine(directory, fontName);

#if WINDOWS || LINUX
        }
#endif

            context.Logger.LogMessage("Building Font {0}", fontName);
            try {
                if (!File.Exists(fontName))
                {
                    throw new Exception(string.Format("Could not load {0}", fontName));
                }
                var lineSpacing = 0f;
                int yOffsetMin  = 0;
                var glyphs      = ImportFont(input, out lineSpacing, out yOffsetMin, context, fontName);

                // Optimize.
                foreach (Glyph glyph in glyphs)
                {
                    GlyphCropper.Crop(glyph);
                }

                var compressed   = TextureFormat == TextureProcessorOutputFormat.DxtCompressed || TextureFormat == TextureProcessorOutputFormat.Compressed;
                var systemBitmap = GlyphPacker.ArrangeGlyphs(glyphs, compressed, compressed);

                //systemBitmap.Save ("fontglyphs.png");

                // Adjust line and character spacing.
                lineSpacing += input.Spacing;
                output.VerticalLineSpacing = (int)lineSpacing;

                foreach (var glyph in glyphs)
                {
                    output.CharacterMap.Add(glyph.Character);

                    var texRect = new Rectangle(glyph.Subrect.X, glyph.Subrect.Y, glyph.Subrect.Width, glyph.Subrect.Height);
                    output.Glyphs.Add(texRect);

                    var cropping = new Rectangle(0, (int)(glyph.YOffset - yOffsetMin), (int)glyph.XAdvance, output.VerticalLineSpacing);
                    output.Cropping.Add(cropping);

                    // Set the optional character kerning.
                    if (input.UseKerning)
                    {
                        output.Kerning.Add(new Vector3(glyph.CharacterWidths.A, glyph.CharacterWidths.B, glyph.CharacterWidths.C));
                    }
                    else
                    {
                        output.Kerning.Add(new Vector3(0, texRect.Width, 0));
                    }
                }

                output.Texture.Faces[0].Add(systemBitmap.ToXnaBitmap(true));
                systemBitmap.Dispose();

                if (compressed)
                {
                    GraphicsUtil.CompressTexture(context.TargetProfile, output.Texture, context, false, true, true);
                }
            }
            catch (Exception ex) {
                context.Logger.LogImportantMessage("{0}", ex.ToString());
            }

            return(output);
        }
예제 #23
0
 private static void TakeScreenshotProxy(PowerPointSlide currentSlide, ShapeRange shapeRange)
 {
     shapeRange.Visible = Office.MsoTriState.msoFalse;
     GraphicsUtil.ExportSlide(currentSlide, SlidePicture);
     shapeRange.Visible = Office.MsoTriState.msoTrue;
 }
 protected override bool GetEnabled(string ribbonId)
 {
     return(!GraphicsUtil.IsClipboardEmpty());
 }
예제 #25
0
        public static void AddDrillDownAnimation(PowerPoint.Shape selectedShape, PowerPointSlide currentSlide,
                                                 out PowerPointDrillDownSlide addedSlide, bool includeAckSlide = true, bool deletePreviouslyAdded = true)
        {
            try
            {
                if (currentSlide == null || currentSlide.Index == PowerPointPresentation.Current.SlideCount)
                {
                    System.Windows.Forms.MessageBox.Show(TextCollection.ZoomLabText.ErrorInvalidNextSlide, TextCollection.ZoomLabText.ErrorUnableToAddAnimationsCaption);
                    addedSlide = null;
                    return;
                }

                //Pick up the border and shadow style, to be applied to zoomed shape
                selectedShape.PickUp();
                PrepareZoomShape(currentSlide, ref selectedShape);
                PowerPointSlide nextSlide = GetNextSlide(currentSlide, deletePreviouslyAdded);

                PowerPoint.Shape nextSlidePicture = null, shapeToZoom = null;

                currentSlide.HideIndicator();
                if (ZoomLabSettings.BackgroundZoomChecked)
                {
                    nextSlidePicture = GetNextSlidePictureWithBackground(currentSlide, nextSlide);
                    nextSlidePicture.Apply();
                    PrepareNextSlidePicture(currentSlide, selectedShape, ref nextSlidePicture);

                    addedSlide = (PowerPointDrillDownSlide)currentSlide.CreateDrillDownSlide();
                    addedSlide.DeleteAllShapes();

                    shapeToZoom = addedSlide.Shapes.SafeCopyPlaceholder(nextSlidePicture);
                    addedSlide.DeleteShapeAnimations(shapeToZoom);

                    PowerPoint.Shape backgroundShape = GraphicsUtil.AddSlideAsShape(currentSlide, addedSlide);
                    backgroundShape.Apply();
                    ShapeUtil.FitShapeToSlide(ref backgroundShape);
                    backgroundShape.ZOrder(Office.MsoZOrderCmd.msoSendBackward);
                    backgroundShape.Name = "PPTZoomInShape" + DateTime.Now.ToString("yyyyMMddHHmmssffff");

                    addedSlide.PrepareForDrillDown();
                    addedSlide.AddDrillDownAnimationBackground(backgroundShape, shapeToZoom, nextSlidePicture);
                }
                else
                {
                    PowerPoint.Shape pictureOnNextSlide = null;
                    nextSlidePicture = GetNextSlidePictureWithoutBackground(currentSlide, nextSlide, out pictureOnNextSlide);
                    nextSlidePicture.Apply();
                    PrepareNextSlidePicture(currentSlide, selectedShape, ref nextSlidePicture);

                    addedSlide = (PowerPointDrillDownSlide)currentSlide.CreateDrillDownSlide();
                    addedSlide.DeleteAllShapes();

                    shapeToZoom = addedSlide.Shapes.SafeCopyPlaceholder(nextSlidePicture);
                    addedSlide.DeleteShapeAnimations(shapeToZoom);

                    PowerPoint.Shape backgroundShape = GraphicsUtil.AddSlideAsShape(currentSlide, addedSlide);
                    backgroundShape.Apply();
                    ShapeUtil.FitShapeToSlide(ref backgroundShape);
                    backgroundShape.ZOrder(Office.MsoZOrderCmd.msoSendBackward);
                    backgroundShape.Name = "PPTZoomInShape" + DateTime.Now.ToString("yyyyMMddHHmmssffff");

                    addedSlide.PrepareForDrillDown();
                    addedSlide.AddDrillDownAnimationNoBackground(backgroundShape, shapeToZoom, pictureOnNextSlide);
                    pictureOnNextSlide.SafeDelete();
                }
                currentSlide.ShowIndicator();

                Globals.ThisAddIn.Application.ActiveWindow.View.GotoSlide(addedSlide.Index);
                Globals.ThisAddIn.Application.CommandBars.ExecuteMso("AnimationPreview");
                if (includeAckSlide)
                {
                    PowerPointPresentation.Current.AddAckSlide();
                }
            }
            catch (Exception e)
            {
                Logger.LogException(e, "AddDrillDownAnimation");
                ErrorDialogBox.ShowDialog("Error when adding drill down animation", "An error occurred when adding drill down animation.", e);
                throw;
            }
        }
 public TooltipsLabSettingsAnimationEntry(MsoAnimEffect defaultEffectType, Bitmap image)
 {
     InitializeComponent();
     Type            = defaultEffectType;
     imageBox.Source = GraphicsUtil.BitmapToImageSource(image);
 }
예제 #27
0
        private Image imgClipsLevelBuf = null;//ÇÐƬ²ãÏÔʾÇøÓò»º³å
        //(ÇÐƬ²ãͼƬ¿ò)Ë¢ÐÂÇÐƬ²ãͼƬ¿òÏÔʾÇøÓò
        public void UpdateRegion_FrameLevel()
        {
            if (pictureBox_clipsLevel.Height <= 0 || pictureBox_clipsLevel.Width <= 0)
            {
                return;
            }
            //µ÷Õû»º³å
            if (imgClipsLevelBuf == null || imgClipsLevelBuf.Width != pictureBox_clipsLevel.Width || imgClipsLevelBuf.Height != pictureBox_clipsLevel.Height)
            {
                imgClipsLevelBuf = new Bitmap(pictureBox_clipsLevel.Width, pictureBox_clipsLevel.Height);
            }
            //¼ÆËã×î´óÇÐƬ³ß´çÒÔµ÷Õû¹ö¶¯Ìõ
            //³ß´ç,ͬÈÝÆ÷¿ò´óС
            int containerW = imgClipsLevelBuf.Width;
            int containerH = imgClipsLevelBuf.Height;
            //»æÖƵ½»º³å
            Graphics gBuf = Graphics.FromImage(imgClipsLevelBuf);

            gBuf.Clear(Color.Transparent);
            if (form_MA != null && form_MA.form_MTimeLine != null && form_MA.form_MTimeLine.focusFrame != null)
            {
                //ɨÃèÇÐƬ£¬¼ÆË㻺³å´óС
                float maxWidth = 0;
                for (int i = 0; i < form_MA.form_MTimeLine.focusFrame.Count(); i++)//ºáÏòɨÃè×î´óÇÐƬ¿í¶È
                {
                    MFrameUnit clip = form_MA.form_MTimeLine.focusFrame[i];
                    float      wI   = clip.getTransformSize(zoomLevel_ClipsLevel).Width;
                    if (maxWidth < wI)
                    {
                        maxWidth = wI;
                    }
                }
                float maxHeight = 0;
                for (int i = 0; i < form_MA.form_MTimeLine.focusFrame.Count(); i++)//×ÝÏòɨÃè×î´óÇÐƬ¸ß¶È
                {
                    MFrameUnit clip = form_MA.form_MTimeLine.focusFrame[i];
                    maxHeight += clip.getLastTransformSize().Height + form_MA.LEVEL_GAP;
                }
                //µ÷Õû¹ö¶¯Ìõ
                int   maxHeightS = (int)maxHeight;
                int   scrollH    = maxHeightS > containerH ? maxHeightS - containerH : 0;
                int   x          = 0;
                float y          = (vScrollBar_ClipsLevel.Maximum - 9) == 0 ? 0 : vScrollBar_ClipsLevel.Value * scrollH / (vScrollBar_ClipsLevel.Maximum - 9);
                y = -y;
                //»æÖÆËùÓÐÇпé
                for (int i = 0; i < form_MA.form_MTimeLine.focusFrame.Count(); i++)
                {
                    MFrameUnit clip    = form_MA.form_MTimeLine.focusFrame[i];
                    SizeF      clipBox = clip.getLastTransformSize();
                    clip.GdiDisplay(gBuf, x + clipBox.Width / 2 + form_MA.LEVEL_GAP, y + clipBox.Height / 2 + form_MA.LEVEL_GAP, zoomLevel_ClipsLevel, Form_MTimeLine.timePosition);
                    if (clip.isLocked)
                    {
                        GraphicsUtil.fillRect(gBuf, x + form_MA.LEVEL_GAP, y + form_MA.LEVEL_GAP, clipBox.Width, clipBox.Height, 0x00FF00, 0x44);
                    }
                    if (!clip.isVisible)
                    {
                        GraphicsUtil.fillRect(gBuf, x + form_MA.LEVEL_GAP, y + form_MA.LEVEL_GAP, clipBox.Width, clipBox.Height, Consts.colorRed, 0x44);
                        if (form_MA.form_MFrameEdit.currentUnits.Contains(clip))
                        {
                            GraphicsUtil.drawRect(gBuf, x + form_MA.LEVEL_GAP, y + form_MA.LEVEL_GAP, clipBox.Width, clipBox.Height, Consts.colorBlue);
                        }
                    }
                    else if (form_MA.form_MFrameEdit.currentUnits.Contains(clip))
                    {
                        GraphicsUtil.fillRect(gBuf, x + form_MA.LEVEL_GAP, y + form_MA.LEVEL_GAP, clipBox.Width, clipBox.Height, Consts.colorBlue, 0x44);
                        GraphicsUtil.drawRect(gBuf, x + form_MA.LEVEL_GAP, y + form_MA.LEVEL_GAP, clipBox.Width, clipBox.Height, Consts.colorBlue);
                    }
                    else
                    {
                        GraphicsUtil.drawRect(gBuf, x + form_MA.LEVEL_GAP, y + form_MA.LEVEL_GAP, clipBox.Width, clipBox.Height, Consts.colorDarkGray);
                    }
                    y += clipBox.Height + form_MA.LEVEL_GAP;
                }
            }
            gBuf.Dispose();
            //»æÖƵ½ÆÁÄ»
            if (pictureBox_clipsLevel.Image == null || !pictureBox_clipsLevel.Image.Equals(imgClipsLevelBuf))
            {
                pictureBox_clipsLevel.Image = imgClipsLevelBuf;
            }
            else
            {
                pictureBox_clipsLevel.Refresh();
            }
        }
예제 #28
0
 public override Bitmap DisplayImage(Shape formatShape)
 {
     Bitmap image = GraphicsUtil.ShapeToBitmap(formatShape);
     return image;
 }
 private void UpdateBarcodeDialog_Load(object sender, EventArgs e)
 {
     pictureEdit1.Image = GraphicsUtil.CreateRandomBitmap(out text);
 }
예제 #30
0
        LayoutAllGroupsInU
        (
            Rectangle graphRectangle,
            IList <GroupInfo> sortedGroups,
            double alpha,
            double gamma,
            double ARs,
            Int32 iSortedGroupCount,
            Double dTotalNumberOfVertices
        )
        {
            aoGroupRectangles = new RectangleF[iSortedGroupCount];
            Boolean done = false;

            while (!done)
            {
redoU:
                // Place the biggest group at the top center
                double ratioFirstGroup = gamma * ((double)sortedGroups[0].Vertices.Count / dTotalNumberOfVertices);

                Debug.Assert(ratioFirstGroup > 0);

                double AreaFirstGroup   = ratioFirstGroup * graphRectangle.Width * graphRectangle.Height;
                double firstGroupWidth  = Math.Sqrt(ratioFirstGroup * graphRectangle.Width * graphRectangle.Height / ARs);
                double firstGroupHeight = Math.Sqrt(ratioFirstGroup * graphRectangle.Width * graphRectangle.Height * ARs);
                double dGroupTop        = (double)graphRectangle.Top;
                double dGroupBottom     = dGroupTop + firstGroupHeight;
                double dGroupLeft       = (double)graphRectangle.Left + ((double)(graphRectangle.Width - firstGroupWidth) / 2.0);
                double dGroupRight      = dGroupLeft + firstGroupWidth;

                // Assign the boundaries to center(first) group's rectangle
                aoGroupRectangles[0] = RectangleF.FromLTRB((float)dGroupLeft,
                                                           (float)dGroupTop, (float)dGroupRight, (float)dGroupBottom);

                // Calculate the free spaces. Constructor follows the Left, Top, Right, Bottom order
                FreeSpaceBox B2 = new FreeSpaceBox(graphRectangle.Left, (float)dGroupTop, (float)dGroupLeft, graphRectangle.Bottom, FreeSpaceBox.Orientation.Vert);
                FreeSpaceBox B3 = new FreeSpaceBox((float)dGroupLeft, (float)dGroupBottom, graphRectangle.Right, graphRectangle.Bottom, FreeSpaceBox.Orientation.Horiz);
                FreeSpaceBox B4 = new FreeSpaceBox((float)dGroupRight, (float)dGroupTop, graphRectangle.Right, (float)dGroupBottom, FreeSpaceBox.Orientation.Vert);

                // Place the boxes in the linked list
                freeSpaceBoxList = new LinkedList <FreeSpaceBox>();
                freeSpaceBoxList.AddFirst(B3);
                freeSpaceBoxList.AddLast(B2);
                freeSpaceBoxList.AddLast(B4);

                done = ArrangeRemainingGroupsInFreeSpaces(graphRectangle, sortedGroups, gamma, iSortedGroupCount, dTotalNumberOfVertices);
                if (!done)
                {
                    gamma = gamma * alpha; // alpha has been set in Layouts->Layouts->LayoutBase.cs
                    Debug.Assert(gamma > 0);
                    for (int j = 0; j < iSortedGroupCount; j++)
                    {
                        aoGroupRectangles[j] = RectangleF.Empty;
                        freeSpaceBoxList     = new LinkedList <FreeSpaceBox>();
                    }
                    goto redoU;
                }
            }
            for (Int32 i = 0; i < iSortedGroupCount; i++)
            {
                sortedGroups[i].Rectangle = GraphicsUtil.RectangleFToRectangle(aoGroupRectangles[i], 1);
            }

            // Calculate the screen space wasted
            double totalFreeAreaLeft           = 0;
            LinkedListNode <FreeSpaceBox> next = freeSpaceBoxList.First;

            while (next != null)
            {
                totalFreeAreaLeft = totalFreeAreaLeft + next.Value.GetArea();
                next = next.Next;
            }
        }
        internal static void DrawAltitudeDigits(
            Graphics g, float digit, RectangleF layoutRectangle, RectangleF clipRectangle, float pointSize, bool goByTwenty, bool cyclical, StringAlignment alignment, PrivateFontCollection fonts)
        {
            if (_digitFont == null)
            {
                _digitFont = new ThreadLocal <Font>(() => new Font(fonts.Families[0], pointSize, FontStyle.Regular, GraphicsUnit.Point));
            }
            if (!DigitStringFormats.Value.ContainsKey(alignment))
            {
                DigitStringFormats.Value.Add(
                    alignment,
                    new StringFormat
                {
                    Alignment     = alignment,
                    FormatFlags   = StringFormatFlags.NoWrap | StringFormatFlags.NoClip | StringFormatFlags.FitBlackBox,
                    LineAlignment = StringAlignment.Center,
                    Trimming      = StringTrimming.None
                });
            }
            var digitSF = DigitStringFormats.Value[alignment];

            var initialClip  = g.Clip;
            var initialState = g.Save();

            g.SetClip(clipRectangle);
            var basicState = g.Save();

            GraphicsUtil.RestoreGraphicsState(g, ref basicState);

            const float digitSpacing = 0;

            if (cyclical)
            {
                for (var i = -1; i <= 11; i++)
                {
                    int thisDigit;
                    if (i >= 0)
                    {
                        thisDigit = i % 10;
                    }
                    else
                    {
                        thisDigit = 10 - Math.Abs(i) % 10;
                    }

                    var toDraw = $"{thisDigit:#0}";
                    if (goByTwenty)
                    {
                        toDraw = $"{thisDigit * 20 % 100:00}";
                        if (toDraw == "100")
                        {
                            toDraw = "00";
                        }
                    }
                    var digitSize        = g.MeasureString(toDraw, _digitFont.Value);
                    var layoutRectangle2 = new RectangleF(layoutRectangle.X, layoutRectangle.Y - i * (digitSize.Height + digitSpacing), layoutRectangle.Width, digitSize.Height);
                    layoutRectangle2.Offset(0, (digitSize.Height + digitSpacing) * digit);
                    g.DrawStringFast(toDraw, _digitFont.Value, DigitBrush.Value, layoutRectangle2, digitSF);
                }
            }
            else
            {
                var thisDigit = (int)Math.Floor(digit);
                var toDraw    = $"{thisDigit:0}";
                if (toDraw.Length > 1)
                {
                    toDraw = toDraw.Substring(0, 1);
                }
                if (goByTwenty)
                {
                    toDraw = $"{thisDigit * 20:00}";
                }
                var digitSize        = g.MeasureString(toDraw, _digitFont.Value);
                var layoutRectangle2 = new RectangleF(layoutRectangle.X, layoutRectangle.Y - digit * (digitSize.Height + digitSpacing), layoutRectangle.Width, digitSize.Height);
                layoutRectangle2.Offset(0, (digitSize.Height + digitSpacing) * digit);
                g.DrawStringFast(toDraw, _digitFont.Value, DigitBrush.Value, layoutRectangle2, digitSF);
            }

            GraphicsUtil.RestoreGraphicsState(g, ref initialState);
            g.Clip = initialClip;
        }