Beispiel #1
0
        public static FontTexture CreateFont(Library ftLibrary, string filename, ushort fontSize)
        {
            if(ftLibrary != null)
            {
                var glf = new FontTexture();

                Face face = null;
                try
                {
                    face = new Face(ftLibrary, filename, 0);
                }
                catch
                {
                    return null;
                }
                glf.FTFace = face;

                Array.Resize(ref glf.Glyphs, glf.FTFace.GlyphCount);

                glf.GLMaxTexWidth = GL.GetInteger(GetPName.MaxTextureSize);
                glf.GLTexWidth = glf.GLMaxTexWidth;
                glf.GLTexIndexes = new uint[0];
                glf.GLRealTexIndexesCount = 0;
                glf.GLFontColor = new [] {0.0f, 0.0f, 0.0f, 1.0f};

                Resize(glf, fontSize);
                glf.FTFace.SelectCharmap(Encoding.Unicode);

                return glf;
            }

            return null;
        }
        static int Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Please supply a path and a list of font sizes.");
                return 1;
            }

            string path = args[0];
            Face face = new Face(library, path);
            Console.WriteLine("Font family: {0}, style: {1}", face.FamilyName, face.StyleName);
            
            for (int i = 1; i < args.Length; i++)
            {
                int fontSize = int.Parse(args[i]);
                string saveLocation = face.FamilyName + face.StyleName + "-" + fontSize + "pt.png";
                string dataSaveLocation = face.FamilyName + face.StyleName + "-" + fontSize + "pt-data.lua";

                Console.WriteLine("Font size: {0}", fontSize);

                FontExporter exporter = new FontExporter(face, fontSize);
                exporter.Export(saveLocation, dataSaveLocation);
            }

            return 0;
        }
Beispiel #3
0
 public SpriteSheet(Face[] faces, string characters, int[] sizes, string family)
 {
     this.faces = faces;
     this.characters = characters;
     this.sizes = sizes;
     this.family = family;
 }
Beispiel #4
0
        static void Main(string[] args)
        {
            Console.WriteLine("Version string: " + HB.VersionString);
            Version v = HB.Version;

            Console.WriteLine("Version: " + v.Major + "." + v.Minor + "." + v.Build);
            Console.WriteLine("VersionCheck: " + HB.VersionAtLeast(v));

            var lib  = new Library();
            var face = new SharpFont.Face(lib, @"C:\Windows\Fonts\tahoma.ttf");

            face.SetCharSize(0, 50, 72, 72);

            var font = HarfBuzz.Font.FromFTFace(face);
            var buf  = new HarfBuzz.Buffer();

            buf.Direction = Direction.RightToLeft;
            buf.Script    = Script.Arabic;
            buf.AddText("متن");
            font.Shape(buf);

            var glyphInfos     = buf.GlyphInfo();
            var glyphPositions = buf.GlyphPositions();

            int height = (face.MaxAdvanceHeight - face.Descender) >> 6;
            int width  = 0;

            for (int i = 0; i < glyphInfos.Length; ++i)
            {
                width += glyphPositions[i].xAdvance >> 6;
            }

            Bitmap   bmp = new Bitmap(width, height);
            Graphics g   = Graphics.FromImage(bmp);

            g.Clear(Color.Gray);

            int penX = 0, penY = face.MaxAdvanceHeight >> 6;

            //draw the string
            for (int i = 0; i < glyphInfos.Length; ++i)
            {
                face.LoadGlyph(glyphInfos[i].codepoint, LoadFlags.Default, LoadTarget.Normal);
                face.Glyph.RenderGlyph(RenderMode.Normal);

                Bitmap cBmp = face.Glyph.Bitmap.ToGdipBitmap(Color.Firebrick);
                g.DrawImageUnscaled(cBmp,
                                    penX + (glyphPositions[i].xOffset >> 6) + face.Glyph.BitmapLeft,
                                    penY - (glyphPositions[i].yOffset >> 6) - face.Glyph.BitmapTop);

                penX += glyphPositions[i].xAdvance >> 6;
                penY -= glyphPositions[i].yAdvance >> 6;
            }

            g.Dispose();

            bmp.Save("output.bmp");
        }
Beispiel #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Font"/> class.
 /// </summary>
 public Font()
 {
     _library    = null;
     _face       = null;
     _stroker    = null;
     _familyName = string.Empty;
     _pages      = new Dictionary <int, Page>();
     _fontData   = null;
 }
Beispiel #6
0
        /// <summary>
        /// Creates a new VectorFont with the File specified at path and the specified size in pixels.
        /// It is assumed that the font is either Monospaced or only single chars are used.
        /// </summary>
        /// <param name="path">path to the font-file</param>
        /// <param name="size">size in pixles</param>
        public VectorFont(string path, uint size)
        {
            lib = new Library();

            face = new Face(lib, path);

            face.SetPixelSizes(0, size);

            this.size = face.Size;
        }
Beispiel #7
0
		/// <summary>
		/// Initializes a new instance of the <see cref="FTSize"/> class.
		/// </summary>
		/// <param name="parent">The parent face.</param>
		public FTSize(Face parent)
		{
			IntPtr reference;
			Error err = FT.FT_New_Size(parent.Reference, out reference);

			if (err != Error.Ok)
				throw new FreeTypeException(err);

			Reference = reference;
			userAlloc = true;
		}
        public override void Reload()
        {
            if (Filename != null)
            {
                Face?.Dispose();
                Face = new SharpFont.Face(Library, Filename);
            }

            Face.SetCharSize(NominalWidth, NominalHeight, 96, 96);
            Load();
        }
		static void Main(string[] args)
		{
			Console.WriteLine("Version string: " + HB.VersionString);
			Version v = HB.Version;
			Console.WriteLine("Version: " + v.Major + "." + v.Minor + "." + v.Build);
			Console.WriteLine("VersionCheck: " + HB.VersionAtLeast(v));

			var lib = new Library();
			var face = new SharpFont.Face(lib, @"C:\Windows\Fonts\tahoma.ttf");
			face.SetCharSize(0, 50, 72, 72);

			var font = HarfBuzz.Font.FromFTFace(face);
			var buf = new HarfBuzz.Buffer();
			buf.Direction = Direction.RightToLeft;
			buf.Script = Script.Arabic;
			buf.AddText("متن");
			font.Shape(buf);

			var glyphInfos = buf.GlyphInfo();
			var glyphPositions = buf.GlyphPositions();

			int height = (face.MaxAdvanceHeight - face.Descender) >> 6;
			int width = 0;
			for (int i = 0; i < glyphInfos.Length; ++i)
			{
				width += glyphPositions[i].xAdvance >> 6;
			}

			Bitmap bmp = new Bitmap(width, height);
			Graphics g = Graphics.FromImage(bmp);
			g.Clear(Color.Gray);

			int penX = 0, penY = face.MaxAdvanceHeight >> 6;
			//draw the string
			for (int i = 0; i < glyphInfos.Length; ++i)
			{
				face.LoadGlyph(glyphInfos[i].codepoint, LoadFlags.Default, LoadTarget.Normal);
				face.Glyph.RenderGlyph(RenderMode.Normal);

				Bitmap cBmp = face.Glyph.Bitmap.ToGdipBitmap(Color.Firebrick);
				g.DrawImageUnscaled(cBmp,
					penX + (glyphPositions[i].xOffset >> 6) + face.Glyph.BitmapLeft,
					penY - (glyphPositions[i].yOffset >> 6) - face.Glyph.BitmapTop);

				penX += glyphPositions[i].xAdvance >> 6;
				penY -= glyphPositions[i].yAdvance >> 6;
			}

			g.Dispose();

			bmp.Save("output.bmp");
		}
Beispiel #10
0
        static public RasterInterf getInstance()
        {
            if (_Rasterizer == null)
            {
                _Rasterizer = new RasterInterf ();
            }
            if ( _face != null )
            {
                _face.Dispose();
                _face = null;
            }

            return _Rasterizer;
        }
Beispiel #11
0
        public FontDef(Face face, int size)
        {
            const int atlasSize = 1024;
            atlas = new RenderTarget2D(GraphicsManager.device, atlasSize, atlasSize, false, SurfaceFormat.Color, DepthFormat.None, 1, RenderTargetUsage.PreserveContents);
            fontFace = face;
            pxSize = size;

            face.SetPixelSizes((uint)size, (uint)size);
            face.LoadGlyph(face.GetCharIndex('A'), loadFlags, loadTarget);
            lineSize = (int)Math.Ceiling((float)face.Glyph.Metrics.Height * 2f);

            const string defaultCharset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ!@#$%^&*()`-=~_+[]{}\\|;',./:\"<>? ";
            foreach (char c in defaultCharset) AddGlyph(c);
        }
        public FontExporter(Face face, int size)
        {
            this.face = face;
            this.pointsSize = size;
            this.fontInfo = new FontInfo(face.FamilyName + "." + face.StyleName, size);

            this.face.SetCharSize(size * 96 / 72, 0, 96, 96);

            exportedCharacters = "";
            for (int i = 32; i < 126; i++)
            {
                exportedCharacters += (char)i;
            }
        }
        public FontFaceRenderMap(SharpFont.Face face, float size)
        {
            if (face == null)
            {
                throw new System.ArgumentNullException(nameof(face));
            }

            Face = face;
            Face.SetPixelSizes((uint)Util.Math.Round(size), (uint)Util.Math.Round(size));

            NominalWidth  = Face.Size.Metrics.NominalWidth;
            NominalHeight = Face.Size.Metrics.NominalHeight;

            Load();
        }
Beispiel #14
0
        public TextGenerator(string path, string fontName, uint fontSize = 12)
        {
            if (_textPs == null)
            {
                LoadProgramShader();
            }

            FontName = fontName;
            FontSize = fontSize;

            SharpFont.Library fontLib  = new SharpFont.Library();
            SharpFont.Face    fontFace = new SharpFont.Face(fontLib, path);
            fontFace.SetPixelSizes(0, FontSize);

            GL.PixelStore(PixelStoreParameter.UnpackAlignment, 1);

            for (char c = (char)0x20; c <= (char)0x7E; c++)
            {
                fontFace.LoadChar(c, LoadFlags.Render, LoadTarget.Normal);

                Texture texture = Texture.CreateTexture(
                    fontFace.Glyph.Bitmap.Width,
                    fontFace.Glyph.Bitmap.Rows,
                    PixelInternalFormat.R8,
                    PixelFormat.Red,
                    fontFace.Glyph.Bitmap.Buffer);

                Character character = new Character(
                    texture.ID,
                    new Vector2(fontFace.Glyph.Bitmap.Width, fontFace.Glyph.Bitmap.Rows),
                    new Vector2(fontFace.Glyph.BitmapLeft, fontFace.Glyph.BitmapTop),
                    (int)fontFace.Glyph.Advance.X);

                _characters.Add(c, character);
            }

            fontFace.Dispose();
            fontLib.Dispose();

            vao = VAO.Create();
            vao.LinkPS(_textPs);

            vbo     = VBO.Create <float>(vertices.Length, 4, "vertex");
            indices = new IndicesCollection();
            indices.Add(4, vertices.Length);
            vao.AddVBuff(vbo);
            vao.AddIndicesCollection(indices);
        }
Beispiel #15
0
        public SpriteFont(string name, int size)
        {
            this.size = size;

            face = library.NewFace(name, 0);
            face.SetPixelSizes((uint)size, (uint)size);

            glyphs = new Cache<Pair<char, Color>, GlyphInfo>(CreateGlyph,
                     Pair<char,Color>.EqualityComparer);

            // setup a 1-channel SheetBuilder for our private use
            if (builder == null) builder = new SheetBuilder(TextureChannel.Alpha);

            PrecacheColor(Color.White);
            PrecacheColor(Color.Red);
        }
Beispiel #16
0
		internal FTSize(IntPtr reference, bool userAlloc, Face parentFace)
		{
			Reference = reference;

			this.userAlloc = userAlloc;

			if (parentFace != null)
			{
				this.parentFace = parentFace;
				parentFace.AddChildSize(this);
			}
			else
			{
				duplicate = true;
			}
		}
Beispiel #17
0
        public SpriteFont(string name, int size)
        {
            this.size = size;

            face = library.NewFace(name, 0);
            face.SetPixelSizes((uint)size, (uint)size);

            glyphs = new Cache<Pair<char, Color>, GlyphInfo>(CreateGlyph,
                     Pair<char,Color>.EqualityComparer);

            // setup a SheetBuilder for our private use
            // TODO: SheetBuilder state is leaked between mod switches
            if (builder == null)
                builder = new SheetBuilder(SheetType.BGRA);

            PrecacheColor(Color.White);
            PrecacheColor(Color.Red);
        }
Beispiel #18
0
        private void Initialize()
        {
            // Initialize FreeType
            // Note: we initialize FreeType for every font instance in order to avoid having a single
            // global manager that would create a lot of issues regarding creation and destruction order.
            _library = new SharpFont.Library();

            // Load the new font face from the specified data
            _face = new SharpFont.Face(_library, _fontData, 0);

            // Load the stroker that will be used to outline the font
            _stroker = new SharpFont.Stroker(_library);

            // Select the unicode character map
            _face.SelectCharmap(SharpFont.Encoding.Unicode);

            // Store the font family name
            _familyName = _face.FamilyName;
        }
Beispiel #19
0
        public SpriteFont(string name, int size, SheetBuilder builder)
        {
            if (builder.Type != SheetType.BGRA)
                throw new ArgumentException("The sheet builder must create BGRA sheets.", "builder");

            this.size = size;
            this.builder = builder;

            face = new Face(Library, name);
            face.SetPixelSizes((uint)size, (uint)size);

            glyphs = new Cache<Pair<char, Color>, GlyphInfo>(CreateGlyph, Pair<char, Color>.EqualityComparer);

            Func<char, float> characterWidth = character => glyphs[Pair.New(character, Color.White)].Advance;
            lineWidth = line => line.Sum(characterWidth);

            PrecacheColor(Color.White, name);
            PrecacheColor(Color.Red, name);
        }
Beispiel #20
0
        private void Clear()
        {
            try {
                if (Font != null)
                {
                    Font.Dispose();
                    Font = null;
                }

                GL.BindTexture(TextureTarget.Texture2D, 0);

                if (GlyphCount > 0)
                {
                    if (m_ListBase > 0)
                    {
                        GL.DeleteLists(m_ListBase, GlyphCount);
                    }
                    else if (!CharMap.IsNullOrEmpty())
                    {
                        CharMap.Values.Select(val => val.ListID).ForEach(lid => GL.DeleteLists(lid, 1));
                        CharMap.Clear();
                    }
                }
                if (!m_Textures.IsNullOrEmpty())
                {
                    GL.DeleteTextures(m_Textures.Length, m_Textures);
                }
            } catch (Exception ex) {
                ex.LogError();
            } finally {
                GlyphCount           = 0;
                m_ListBase           = 0;
                m_Textures           = null;
                Height               = 0;
                Count                = 0;
                m_EllipsisGlyphIndex = GlyphInfo.Empty;
            }
        }
Beispiel #21
0
		private void listBoxFont_SelectedIndexChanged(object sender, EventArgs e)
		{
			fontFace = new Face(lib, Path.Combine(Path.GetFullPath(fontFolder), (string)listBoxFont.SelectedItem));
			fontFace.SetCharSize(0, 62, 0, 96);

            dataGridView1.Columns.Add("PlatformId", "PlatformId");
            dataGridView1.Columns.Add("Encoding", "Encoding");
            dataGridView1.Columns.Add("EncodingId", "EncodingId");
            CharMap[] cmaps = fontFace.CharMaps;
            foreach(CharMap cmap in cmaps)
            {
                dataGridView1.Rows.Add(cmap.PlatformId, cmap.Encoding, cmap.EncodingId);
            }

            Header headerTable = (Header)fontFace.GetSfntTable(SfntTag.Header);
            HoriHeader horiHeaderTable = (HoriHeader)fontFace.GetSfntTable(SfntTag.HorizontalHeader);
            MaxProfile maxpTable = (MaxProfile)fontFace.GetSfntTable(SfntTag.MaxProfile);
            OS2 os2Table = (OS2)fontFace.GetSfntTable(SfntTag.OS2);
            Pclt PcltTable = (Pclt)fontFace.GetSfntTable(SfntTag.Pclt);
            Postscript postTable = (Postscript)fontFace.GetSfntTable(SfntTag.Postscript);
            VertHeader vertTable = (VertHeader)fontFace.GetSfntTable(SfntTag.VertHeader);

            pictureBoxText.Invalidate();
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="IncreaseXHeightProperty"/> class.
		/// </summary>
		/// <param name="face">The face to increase the X height of.</param>
		public IncreaseXHeightProperty(Face face)
		{
			this.rec.face = face.Reference;
			this.face = face;
		}
Beispiel #23
0
        private void InitFont(float scaleFactor)
        {
            try {
                System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();

                ScaleFactor   = scaleFactor;
                YOffsetScaled = YOffset * scaleFactor;

                // Reset everything
                Clear();

                Font = new Face(FontManager.Library, FilePath);

                // Go on

                float size = Size.Scale(ScaleFactor);

                Fixed26Dot6 sz = new Fixed26Dot6(size / 64);
                Font.SetCharSize(sz, sz, 72, 72);

                int pixelSize = (size * 1.3334).Ceil();
                Font.SetPixelSizes((uint)pixelSize, (uint)pixelSize);

                GlyphCount = Font.GlyphCount;
                int glyphCount = GlyphCount;
                Monospace = Font.FaceFlags.HasFlag(FaceFlags.FixedWidth);

                string tmpName = Font.GetPostscriptName();
                if (!String.IsNullOrEmpty(tmpName))
                {
                    Name = tmpName;
                }


                // We support 4 different glyph loading strategies:
                //
                // (1) All: all glyphs loaded at once on start
                // (2) Filtered: all filtered glyphs loaded at once on start
                // (3) OnDemand: no glyphs loaded at start, all glyphs on demand


                if (OnDemand)
                {
                    // Startegy (3)
                    GlyphCount = 0;
                }
                else if (Filter > GlyphFilterFlags.OnDemand)
                {
                    // Startegy (2)
                    // If we have a Filter set, let's count the number of valid glyphs
                    // to minimize graphics memory.
                    uint glyphindex;
                    uint cc    = Font.GetFirstChar(out glyphindex);
                    int  count = 0;
                    while (glyphindex > 0)
                    {
                        char c = (char)cc;
                        if (Filter.IsValid(c))
                        {
                            count++;
                        }
                        cc = Font.GetNextChar(cc, out glyphindex);
                    }
                    GlyphCount = count;
                }
                else
                {
                    // Strategy (1), loading the entire font
                }

                m_Textures = new int[Math.Max(32, GlyphCount)];
                CharMap    = new ThreadSafeDictionary <char, GlyphInfo>(Math.Max(31, GlyphCount));

                if (!OnDemand)
                {
                    // Strategy (1) + (2): Load all or filtered glyphs
                    m_ListBase = GL.GenLists(GlyphCount);
                    GL.GenTextures(GlyphCount, m_Textures);

                    uint glyphindex;
                    uint cc = Font.GetFirstChar(out glyphindex);
                    while (glyphindex > 0)
                    {
                        char c = (char)cc;
                        if (!CharMap.ContainsKey(c) && Filter.IsValid(c))
                        {
                            try {
                                CharMap.Add(c, CompileCharacter(Font, glyphindex, c));
                            } catch (Exception ex) {
                                ex.LogWarning();
                            }
                        }
                        cc = Font.GetNextChar(cc, out glyphindex);
                    }
                    CharMap.TryGetValue(SpecialCharacters.Ellipsis, out m_EllipsisGlyphIndex);
                }
                else
                {
                    try {
                        GetGlyphIndex(SpecialCharacters.Ellipsis, out m_EllipsisGlyphIndex);
                    } catch (Exception ex) {
                        ex.LogError();
                    }
                }

                //if (Height <= 1)
                //Height = pixelSize.NextPowerOf2();
                //Height = pixelSize * 1.33335f;

                Height = pixelSize;

                float fscale = Height / Font.Height * 1.33334f;
                //float fscale = Height / Font.Height * 0.776f;

                Ascender  = Font.Ascender * fscale;
                Descender = Font.Descender * fscale;
                //HalfHeight = Height / 2;

                Height     = (Ascender).Ceil();
                HalfHeight = (int)(Height / 2);

                //LineHeight = Height * 1.42f * LineSpacing;
                LineHeight = (int)((Height * 1.42f * LineSpacing) + 0.5f);

                //TextBoxHeight = ((Height * 2f) + (ScaleFactor * 2f)).Ceil();
                //TextBoxHeight = (int)(Height * 1.85f + 0.5f);
                TextBoxHeight = (int)(Height * 1.85f + 2);
                CaptionHeight = (int)(Height * 1.55 + 2);

                YOffsetScaled = (YOffset * ScaleFactor) - HalfHeight;

                if (OnDemand)
                {
                    Count.LogInformation("Font {0} ({1}), {2}/{3} glyphs pre-loaded in {4} ms, more glyphs are loaded on demand.", Name, Size, Count, glyphCount, sw.ElapsedMilliseconds);
                }
                else
                {
                    Count.LogInformation("Font {0} ({1}), {2}/{3} glyphs loaded in {4} ms.", Name, Size, Count, glyphCount, sw.ElapsedMilliseconds);
                }
            } catch (Exception ex) {
                ex.LogError();
            } finally {
                if (!OnDemand && Font != null)
                {
                    Font.Dispose();
                    Font = null;
                }
            }
        }
Beispiel #24
0
        public FontGroup GetGroupForFont(string fontName)
        {
            // Review Linux: very likely something here is not portable.
            if (FontNameToFiles == null)
            {
                FontNameToFiles = new Dictionary <string, FontGroup>();
#if __MonoCS__
                using (var lib = new SharpFont.Library())
                {
                    // Find all the font files in the standard system location (/usr/share/font) and $HOME/.font (if it exists)
                    foreach (var fontFile in FindLinuxFonts())
                    {
                        try
                        {
                            using (var face = new SharpFont.Face(lib, fontFile))
                            {
                                var embeddingTypes = face.GetFSTypeFlags();
                                if ((embeddingTypes & EmbeddingTypes.RestrictedLicense) == EmbeddingTypes.RestrictedLicense ||
                                    (embeddingTypes & EmbeddingTypes.BitmapOnly) == EmbeddingTypes.BitmapOnly)
                                {
                                    continue;
                                }
                                var name = face.FamilyName;
                                // If you care about bold, italic, etc, you can filter here.
                                FontGroup files;
                                if (!FontNameToFiles.TryGetValue(name, out files))
                                {
                                    files = new FontGroup();
                                    FontNameToFiles[name] = files;
                                }
                                files.Add(face, fontFile);
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
#else
                foreach (var fontFile in Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Fonts)))
                {
                    // ePUB only understands these types, so skip anything else.
                    switch (Path.GetExtension(fontFile))
                    {
                    case ".ttf":
                    case ".otf":
                    case ".woff":
                        break;

                    default:
                        continue;
                    }
                    GlyphTypeface gtf;
                    try
                    {
                        gtf = new GlyphTypeface(new Uri("file:///" + fontFile));
                    }
                    catch (Exception)
                    {
                        continue;                         // file is somehow corrupt or not really a font file? Just ignore it.
                    }
                    switch (gtf.EmbeddingRights)
                    {
                    case FontEmbeddingRight.Editable:
                    case FontEmbeddingRight.EditableButNoSubsetting:
                    case FontEmbeddingRight.Installable:
                    case FontEmbeddingRight.InstallableButNoSubsetting:
                    case FontEmbeddingRight.PreviewAndPrint:
                    case FontEmbeddingRight.PreviewAndPrintButNoSubsetting:
                        break;

                    default:
                        continue;                                 // not allowed to embed (enhance: warn user?)
                    }

                    var fc = new PrivateFontCollection();
                    try
                    {
                        fc.AddFontFile(fontFile);
                    }
                    catch (FileNotFoundException)
                    {
                        continue;                         // not sure how this can happen but I've seen it.
                    }
                    var name = fc.Families[0].Name;
                    // If you care about bold, italic, etc, you can filter here.
                    FontGroup files;
                    if (!FontNameToFiles.TryGetValue(name, out files))
                    {
                        files = new FontGroup();
                        FontNameToFiles[name] = files;
                    }
                    files.Add(gtf, fontFile);
                }
#endif
            }
            FontGroup result;
            FontNameToFiles.TryGetValue(fontName, out result);
            return(result);
        }
        void BuildTextureOld()
        {
            #region attribution
            // Significant parts of this method were based off the following example:
            // https://github.com/Robmaister/SharpFont/blob/master/Source/Examples/Program.cs
            // The following license and attribution applies to those parts:

            /*Copyright (c) 2012 Robert Rouhani <*****@*****.**>
            Permission is hereby granted, free of charge, to any person obtaining a copy of
            this software and associated documentation files (the "Software"), to deal in
            the Software without restriction, including without limitation the rights to
            use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
            of the Software, and to permit persons to whom the Software is furnished to do
            so, subject to the following conditions:
            The above copyright notice and this permission notice shall be included in all
            copies or substantial portions of the Software.
            THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
            IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
            FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
            AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
            LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
            OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
            SOFTWARE.*/
            #endregion

            Face face = new Face(ftLib, "C:\\Windows\\Fonts\\segoeui.ttf");
            face.SetCharSize(0, 14, 72, 72);
            //face.SetPixelSizes(0, 14);

            const LoadFlags loadFlags = LoadFlags.Default;
            const LoadTarget loadTarget = LoadTarget.Light;
            const RenderMode renderMode = RenderMode.Light;

            float cx = 0, cy = 0, tw = 0, th = 0;

            // base size
            face.LoadGlyph(face.GetCharIndex('A'), loadFlags, loadTarget);
            th = (float)face.Glyph.Metrics.Height;

            for (int i = 0; i < text.Length; i++) {
                char c = text[i];
                uint cnum = face.GetCharIndex(c);
                face.LoadGlyph(cnum, loadFlags, loadTarget);
                tw += (float)face.Glyph.Advance.X;
                if (face.HasKerning && i < text.Length - 1)  tw += (float)face.GetKerning(cnum, face.GetCharIndex(text[i + 1]), KerningMode.Default).X;
                th = Math.Max(th, (float)face.Glyph.Metrics.Height);

            }
            if (tw == 0) tw = th;

            Bitmap bmp = new Bitmap((int)Math.Ceiling(tw), (int)Math.Ceiling(th*2)); // assumption that any downstem is at most half the height of a capital letter
            cy = th * 0.5f; // adjustment for such
            //Bitmap bmp = new Bitmap(128, 32);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);
            g.Clear(System.Drawing.Color.Transparent);
            //g.Clear(System.Drawing.Color.DimGray);

            for (int i = 0; i < text.Length; i++) {
                char c = text[i];
                uint cnum = face.GetCharIndex(c);
                face.LoadGlyph(cnum, loadFlags, loadTarget);
                face.Glyph.RenderGlyph(renderMode);
                if (c == ' ') {
                    cx += (float)face.Glyph.Advance.X;
                    // omitted an if statement that didn't seem to do anything relevant??
                    cy += (float)face.Glyph.Advance.Y;
                    continue;
                }

                FTBitmap ftb = face.Glyph.Bitmap; // lol ftb
                Bitmap cb = ftb.ToGdipBitmap(System.Drawing.Color.White);
                g.DrawImageUnscaled(cb, (int)Math.Round(cx + face.Glyph.BitmapLeft), (int)Math.Round(cy + (Math.Ceiling(th) - face.Glyph.BitmapTop))); // th and not bitmap.height
                cx += (float)face.Glyph.Metrics.HorizontalAdvance;
                cy += (float)face.Glyph.Advance.Y;
                if (face.HasKerning && i < text.Length - 1) cx += (float)face.GetKerning(cnum, face.GetCharIndex(text[i + 1]), KerningMode.Default).X;
            }
            g.Dispose();
            if (texture != null) texture.Dispose();
            //texture = GraphicsManager.ConvertToPreMultipliedAlphaGPU(GetTexture(GraphicsManager.device, bmp));
            texture = GetTexture(GraphicsManager.device, bmp);
        }
Beispiel #26
0
        /// <summary>
        /// Note: There is some performance overhead to initializing this.
        /// </summary>
        private void InitializeFontData()
        {
            FontNameToFiles    = new Dictionary <string, FontGroup>();
            FontsWeCantInstall = new HashSet <string>();
#if __MonoCS__
            using (var lib = new SharpFont.Library())
            {
                // Find all the font files in the standard system location (/usr/share/font) and $HOME/.local/share/fonts (if it exists)
                foreach (var fontFile in FindLinuxFonts())
                {
                    try
                    {
                        using (var face = new SharpFont.Face(lib, fontFile))
                        {
                            var embeddingTypes = face.GetFSTypeFlags();
                            if ((embeddingTypes & EmbeddingTypes.RestrictedLicense) == EmbeddingTypes.RestrictedLicense ||
                                (embeddingTypes & EmbeddingTypes.BitmapOnly) == EmbeddingTypes.BitmapOnly)
                            {
                                // Our font UI allows any font on the computer, but gives the user indications that some are more
                                // useable in publishing Bloom books. The NoteFontsWeCantInstall prop is only true when we call this
                                // from BloomPubMaker so that it can note that certain fonts are unsuitable for embedding in ePUBs.
                                if (NoteFontsWeCantInstall)
                                {
                                    FontsWeCantInstall.Add(face.FamilyName);
                                    continue;
                                }
                            }
                            var name = face.FamilyName;
                            // If you care about bold, italic, etc, you can filter here.
                            FontGroup files;
                            if (!FontNameToFiles.TryGetValue(name, out files))
                            {
                                files = new FontGroup();
                                FontNameToFiles[name] = files;
                            }
                            files.Add(face, fontFile);
                        }
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            }
#else
            foreach (var fontFile in FindWindowsFonts())
            {
                GlyphTypeface gtf;
                try
                {
                    gtf = new GlyphTypeface(new Uri("file:///" + fontFile));
                }
                catch (Exception)
                {
                    continue;                     // file is somehow corrupt or not really a font file? Just ignore it.
                }

                // Our font UI allows any font on the computer, but gives the user indications that some are more
                // useable in publishing Bloom books. The NoteFontsWeCantInstall prop is only true when we call this
                // from BloomPubMaker so that it can note that certain fonts are unsuitable for embedding in ePUBs.
                if (!FontIsEmbeddable(gtf.EmbeddingRights) && NoteFontsWeCantInstall)
                {
                    string name1 = GetFontNameFromFile(fontFile);
                    if (name1 != null)
                    {
                        FontsWeCantInstall.Add(name1);
                    }
                    continue;                     // not allowed to embed in ePUB
                }

                string name = GetFontNameFromFile(fontFile);
                if (name == null)
                {
                    continue;                     // not sure how this can happen but I've seen it.
                }
                // If you care about bold, italic, etc, you can filter here.
                FontGroup files;
                if (!FontNameToFiles.TryGetValue(name, out files))
                {
                    files = new FontGroup();
                    FontNameToFiles[name] = files;
                }
                files.Add(gtf, fontFile);
            }
#endif
        }
Beispiel #27
0
 public static void Reface(FontTexture glf, string filename, ushort fontSize)
 {
     Face face;
     try
     {
         face = new Face(glf.FTLibrary, filename, 0);
     }
     catch
     {
         return;
     }
     glf.FTFace = face;
     Resize(glf, fontSize);
 }
Beispiel #28
0
        public static Bitmap RenderString(Library library, Face face, string text)
        {
            float penX = 0, penY = 0;
            float width = 0;
            float height = 0;

            //measure the size of the string before rendering it, requirement of Bitmap.
            for (int i = 0; i < text.Length; i++)
            {
                char c = text[i];

                uint glyphIndex = face.GetCharIndex(c);
                face.LoadGlyph(glyphIndex, LoadFlags.Default, LoadTarget.Normal);

                width += (float)face.Glyph.Advance.X;

                if (face.HasKerning && i < text.Length - 1)
                {
                    char cNext = text[i + 1];
                    width += (float)face.GetKerning(glyphIndex, face.GetCharIndex(cNext), KerningMode.Default).X;
                }

                if ((float)face.Glyph.Metrics.Height > height)
                    height = (float)face.Glyph.Metrics.Height;
            }

            //create a new bitmap that fits the string.
            Bitmap bmp = new Bitmap((int)Math.Ceiling(width), (int)Math.Ceiling(height));
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(SystemColors.Control);

            //draw the string
            for (int i = 0; i < text.Length; i++)
            {
                char c = text[i];

                uint glyphIndex = face.GetCharIndex(c);
                face.LoadGlyph(glyphIndex, LoadFlags.Default, LoadTarget.Normal);
                face.Glyph.RenderGlyph(RenderMode.Normal);

                if (c == ' ')
                {
                    penX += (float)face.Glyph.Advance.X;

                    if (face.HasKerning && i < text.Length - 1)
                    {
                        char cNext = text[i + 1];
                        width += (float)face.GetKerning(glyphIndex, face.GetCharIndex(cNext), KerningMode.Default).X;
                    }

                    penY += (float)face.Glyph.Advance.Y;
                    continue;
                }

                //FTBitmap ftbmp = face.Glyph.Bitmap.Copy(library);
                FTBitmap ftbmp = face.Glyph.Bitmap;
                Bitmap cBmp = ftbmp.ToGdipBitmap(Color.Black);

                //Not using g.DrawImage because some characters come out blurry/clipped.
                //g.DrawImage(cBmp, penX + face.Glyph.BitmapLeft, penY + (bmp.Height - face.Glyph.Bitmap.Rows));
                g.DrawImageUnscaled(cBmp, (int)Math.Round(penX + face.Glyph.BitmapLeft), (int)Math.Round(penY + (bmp.Height - face.Glyph.BitmapTop)));

                penX += (float)face.Glyph.Metrics.HorizontalAdvance;
                penY += (float)face.Glyph.Advance.Y;

                if (face.HasKerning && i < text.Length - 1)
                {
                    char cNext = text[i + 1];
                    var kern = face.GetKerning(glyphIndex, face.GetCharIndex(cNext), KerningMode.Default);
                    penX += (float)kern.X;
                }
            }

            g.Dispose();
            return bmp;
        }
Beispiel #29
0
        public static FontTexture CreateFontMem(Library ftLibrary, byte[] faceData, ushort fontSize)
        {
            if (ftLibrary != null)
            {
                var glf = new FontTexture();

                Face face = null;
                try
                {
                    face = new Face(ftLibrary, faceData, 0);
                }
                catch
                {
                    glf.Dispose();
                    return null;
                }
                glf.FTFace = face;

                Array.Resize(ref glf.Glyphs, glf.FTFace.GlyphCount);

                glf.GLMaxTexWidth = GL.GetInteger(GetPName.MaxTextureSize);
                glf.GLTexWidth = glf.GLMaxTexWidth;
                glf.GLTexIndexes = new uint[0];
                glf.GLRealTexIndexesCount = 0;
                Resize(glf, fontSize);
                glf.FTFace.SelectCharmap(Encoding.Unicode);

                return glf;
            }

            return null;
        }
Beispiel #30
0
 internal CharMap(IntPtr reference, Face parent)
 {
     Reference = reference;
     this.parentFace = parent;
 }
Beispiel #31
0
        private int renderCharacter(Face face, char character, int posX, int posY, int atlas, FontInfo info, Graphics graphics)
        {
            uint index = face.GetCharIndex(character);
            face.LoadGlyph(index, LoadFlags.Default, LoadTarget.Normal);
            face.Glyph.RenderGlyph(RenderMode.Normal);

            GlyphMetrics metrics = face.Glyph.Metrics;
            int width = metrics.Width.ToInt32() + metrics.HorizontalBearingX.ToInt32();
            int xAdvance = metrics.HorizontalAdvance.ToInt32();
            int yoffset = metrics.VerticalAdvance.ToInt32() - metrics.HorizontalBearingY.ToInt32();
            int charHeight = metrics.Height.ToInt32();

            if (face.Glyph.Bitmap.Width > 0)
            {
                FTBitmap ftbmp = face.Glyph.Bitmap;
                Bitmap copy = ftbmp.ToGdipBitmap(Color.White);
                graphics.DrawImageUnscaled(copy, posX + metrics.HorizontalBearingX.ToInt32(), posY);
            }

            info.addCharacter(new CharacterInfo(character, posX, posY, width, charHeight, xAdvance, yoffset, atlas));

            return width;
        }
		internal IncreaseXHeightProperty(IncreaseXHeightPropertyRec rec, Face face)
		{
			this.rec = rec;
			this.face = face;
		}
Beispiel #33
0
        public ushort RasterNewSfnt(FileStream fontFileStream, uint faceIndex)
        {
            _face = _lib.NewFace(fontFileStream.Name, (int)faceIndex);
            m_UserCancelledTest = false;
            m_RastErrorCount = 0;

            return 1; //Not used by caller
        }
Beispiel #34
0
        private void getKernWidthHeight(Face face, FontInfo info, out int width, out int maxHeight, out int firstAdjust)
        {
            width = 0;
            maxHeight = 0;
            firstAdjust = 0;

            for (int i = 0; i < characters.Length; i++)
            {
                char character1 = characters[i];
                uint index1 = face.GetCharIndex(character1);

                face.LoadGlyph(index1, LoadFlags.Default, LoadTarget.Normal);
                GlyphMetrics metrics = face.Glyph.Metrics;

                int yoffset = metrics.VerticalAdvance.ToInt32() - metrics.HorizontalBearingY.ToInt32();
                int nheight = yoffset + metrics.Height.ToInt32();
                int height = metrics.Height.ToInt32();
                if (height > maxHeight)
                {
                    maxHeight = height; //nheight;
                    firstAdjust = yoffset;
                }

                for (int j = 0; j < characters.Length; j++)
                {
                    char character2 = characters[j];
                    uint index2 = face.GetCharIndex(character2);

                    FTVector26Dot6 kern = face.GetKerning(index1, index2, KerningMode.Default);
                    int kernX = kern.X.ToInt32();
                    int kernY = kern.Y.ToInt32();
                    if (kernX != 0 || kernY != 0)
                    {
                        info.addKerning(new KerningInfo(character1, character2, kernX, kernY));
                    }
                }

                if (i + 1 == characters.Length)
                {
                    width += metrics.Width.ToInt32() + metrics.HorizontalBearingX.ToInt32() + padX;
                }
                else
                {
                    width += metrics.HorizontalAdvance.ToInt32() + padX;
                }
            }
        }
Beispiel #35
0
		internal GlyphSlot(IntPtr reference, Face parentFace, Library parentLibrary)
		{
			Reference = reference;
			this.parentFace = parentFace;
			this.parentLibrary = parentLibrary;
		}
		internal GlyphToScriptMapProperty(GlyphToScriptMapPropertyRec rec, Face face)
		{
			this.rec = rec;
			this.face = face;
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="GlyphToScriptMapProperty"/> class.
		/// </summary>
		/// <param name="face">The face to apply the property to.</param>
		public GlyphToScriptMapProperty(Face face)
		{
			Face = face;
		}
Beispiel #38
0
        /// <summary>
        /// Note: There is some performance overhead to initializing this.
        /// </summary>
        private void InitializeFontData()
        {
            FontNameToFiles = new Dictionary <string, FontGroup>();
            if (NoteFontsWeCantInstall)
            {
                FontsWeCantInstall = new HashSet <string>();
            }
#if __MonoCS__
            using (var lib = new SharpFont.Library())
            {
                // Find all the font files in the standard system location (/usr/share/font) and $HOME/.font (if it exists)
                foreach (var fontFile in FindLinuxFonts())
                {
                    try
                    {
                        using (var face = new SharpFont.Face(lib, fontFile))
                        {
                            var embeddingTypes = face.GetFSTypeFlags();
                            if ((embeddingTypes & EmbeddingTypes.RestrictedLicense) == EmbeddingTypes.RestrictedLicense ||
                                (embeddingTypes & EmbeddingTypes.BitmapOnly) == EmbeddingTypes.BitmapOnly)
                            {
                                if (NoteFontsWeCantInstall)
                                {
                                    FontsWeCantInstall.Add(face.FamilyName);
                                }
                                continue;
                            }
                            var name = face.FamilyName;
                            // If you care about bold, italic, etc, you can filter here.
                            FontGroup files;
                            if (!FontNameToFiles.TryGetValue(name, out files))
                            {
                                files = new FontGroup();
                                FontNameToFiles[name] = files;
                            }
                            files.Add(face, fontFile);
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
#else
            foreach (var fontFile in FindWindowsFonts())
            {
                GlyphTypeface gtf;
                try
                {
                    gtf = new GlyphTypeface(new Uri("file:///" + fontFile));
                }
                catch (Exception)
                {
                    continue;                     // file is somehow corrupt or not really a font file? Just ignore it.
                }
                switch (gtf.EmbeddingRights)
                {
                case FontEmbeddingRight.Editable:
                case FontEmbeddingRight.EditableButNoSubsetting:
                case FontEmbeddingRight.Installable:
                case FontEmbeddingRight.InstallableButNoSubsetting:
                case FontEmbeddingRight.PreviewAndPrint:
                case FontEmbeddingRight.PreviewAndPrintButNoSubsetting:
                    break;

                default:
                    if (NoteFontsWeCantInstall)
                    {
                        string name1 = GetFontNameFromFile(fontFile);
                        if (name1 != null)
                        {
                            FontsWeCantInstall.Add(name1);
                        }
                    }
                    continue;                             // not allowed to embed
                }

                string name = GetFontNameFromFile(fontFile);
                if (name == null)
                {
                    continue;                     // not sure how this can happen but I've seen it.
                }
                // If you care about bold, italic, etc, you can filter here.
                FontGroup files;
                if (!FontNameToFiles.TryGetValue(name, out files))
                {
                    files = new FontGroup();
                    FontNameToFiles[name] = files;
                }
                files.Add(gtf, fontFile);
            }
#endif
        }
Beispiel #39
0
        private void RenderBitmap(CharacterSpecification character, Face fontFace)
        {
            // choose the rendering type and render the glyph
            var renderingMode = character.AntiAlias == FontAntiAliasMode.Aliased ? RenderMode.Mono : RenderMode.Normal;
            fontFace.Glyph.RenderGlyph(renderingMode);

            // create the bitmap
            var bitmap = fontFace.Glyph.Bitmap;
            if (bitmap.Width != 0 && bitmap.Rows != 0)
                character.Bitmap = new CharacterBitmap(bitmap.Buffer, ref borderSize, bitmap.Width, bitmap.Rows, bitmap.Pitch, bitmap.GrayLevels, bitmap.PixelMode);
            else
                character.Bitmap = new CharacterBitmap();

            // set the glyph offsets
            character.Glyph.Offset = new Vector2(fontFace.Glyph.BitmapLeft - borderSize.X, -fontFace.Glyph.BitmapTop - borderSize.Y);
        }
Beispiel #40
0
		// Rasterizes a single character glyph.
		private Glyph ImportGlyph(char character, Face face)
		{
			uint glyphIndex = face.GetCharIndex(character);
			face.LoadGlyph(glyphIndex, LoadFlags.Default, LoadTarget.Normal);
			face.Glyph.RenderGlyph(RenderMode.Normal);

			// Render the character.
            BitmapContent glyphBitmap = null;
			if (face.Glyph.Bitmap.Width > 0 && face.Glyph.Bitmap.Rows > 0)
            {
                glyphBitmap = new PixelBitmapContent<byte>(face.Glyph.Bitmap.Width, face.Glyph.Bitmap.Rows);
				byte[] gpixelAlphas = new byte[face.Glyph.Bitmap.Width * face.Glyph.Bitmap.Rows];
                //if the character bitmap has 1bpp we have to expand the buffer data to get the 8bpp pixel data
                //each byte in bitmap.bufferdata contains the value of to 8 pixels in the row
                //if bitmap is of width 10, each row has 2 bytes with 10 valid bits, and the last 6 bits of 2nd byte must be discarded
                if(face.Glyph.Bitmap.PixelMode == PixelMode.Mono)
                {
                    //variables needed for the expansion, amount of written data, length of the data to write
                    int written = 0, length = face.Glyph.Bitmap.Width * face.Glyph.Bitmap.Rows;
                    for(int i = 0; written < length; i++)
                    {
                        //width in pixels of each row
                        int width = face.Glyph.Bitmap.Width;
                        while(width > 0)
                        {
                            //valid data in the current byte
                            int stride = MathHelper.Min(8, width);
                            //copy the valid bytes to pixeldata
                            //System.Array.Copy(ExpandByte(face.Glyph.Bitmap.BufferData[i]), 0, gpixelAlphas, written, stride);
                            ExpandByteAndCopy(face.Glyph.Bitmap.BufferData[i], stride, gpixelAlphas, written);
                            written += stride;
                            width -= stride;
                            if(width > 0)
                                i++;
                        }
                    }
                }
                else
                    Marshal.Copy(face.Glyph.Bitmap.Buffer, gpixelAlphas, 0, gpixelAlphas.Length);
                glyphBitmap.SetPixelData(gpixelAlphas);
			}

            if (glyphBitmap == null) 
			{
				var gHA = face.Glyph.Metrics.HorizontalAdvance >> 6;
				var gVA = face.Size.Metrics.Height >> 6;

				gHA = gHA > 0 ? gHA : gVA;
				gVA = gVA > 0 ? gVA : gHA;

                glyphBitmap = new PixelBitmapContent<byte>(gHA, gVA);
			}

			// not sure about this at all
			var abc = new ABCFloat ();
			abc.A = face.Glyph.Metrics.HorizontalBearingX >> 6;
			abc.B = face.Glyph.Metrics.Width >> 6;
			abc.C = (face.Glyph.Metrics.HorizontalAdvance >> 6) - (abc.A + abc.B);

			// Construct the output Glyph object.
			return new Glyph(character, glyphBitmap)
			{
				XOffset = -(face.Glyph.Advance.X >> 6),
				XAdvance = face.Glyph.Metrics.HorizontalAdvance >> 6,
                YOffset = -(face.Glyph.Metrics.HorizontalBearingY >> 6),
				CharacterWidths = abc
			};
		}
Beispiel #41
0
 private void SetFontFaceSize(Face fontFace, Vector2 size)
 {
     // calculate and set the size of the font
     // size is in 26.6 factional points (that is in 1/64th of points)
     // 72 => the sizes are in "points" (=1/72 inch), setting resolution to 72 dpi let us specify the size in pixels directly
     fontFace.SetCharSize((int)Math.Ceiling(size.X * 64), (int)Math.Ceiling(size.Y * 64), 72, 72);
 }