Beispiel #1
0
 public TexChar(TexFont Font, int Index, char CharIndex, bool Supported, float scale)
 {
     fontIndex        = Font.index;
     index            = Index;
     characterIndex   = CharIndex;
     supported        = Supported;
     extentTopHash    = -1;
     extentMiddleHash = -1;
     extentBottomHash = -1;
     extentRepeatHash = -1;
     if (supported)
     {
         if (Font.type == TexFontType.Font)
         {
             CharacterInfo c = getCharInfo(Font.Font_Asset, CharIndex);
             UpdateGlyph(Font.Font_Asset, c);
         }
         else
         {
             depth   = 0;
             height  = scale;
             bearing = 0;
             italic  = scale;
             width   = scale;
         }
     }
 }
        private void RegisterTexFont(TexFormula formula, string value, ref int position, TexFont font)
        {
            SkipWhiteSpace(value, ref position);
            if (position == value.Length)
            {
                return;
            }
            var style = TexUtility.RenderFontStyle;

            if (value [position] == leftBracketChar)
            {
                style = ParseFontStyle(ReadGroup(value, ref position, leftBracketChar, rightBracketChar));
                SkipWhiteSpace(value, ref position);
            }

            var oldType  = TexUtility.RenderFont;
            var oldStyle = TexUtility.RenderFontStyle;

            TexUtility.RenderFont      = font.index;
            TexUtility.RenderFontStyle = style;
            var parsed = Parse(ReadGroup(value, ref position, leftGroupChar, rightGroupChar)).GetRoot;

            TexUtility.RenderFont      = oldType;
            TexUtility.RenderFontStyle = oldStyle;
            formula.Add(parsed);
        }
        private void ProcessEscapeSequence(TexFormula formula, string value, ref int position)
        {
            position++;

            var command = LookForAWord(value, ref position);

            // Check if there's no command
            if (command.Length == 0)
            {
                if (position < value.Length)
                {
                    var nextChar = value [position];
                    if (IsParserReserved(nextChar))
                    {
                        formula.Add(ConvertCharacter(formula, value, ref position, nextChar));
                    }
                }
                return;
            }

            //Check if the command registered in Commands
            if (isCommandRegistered(command))
            {
                formula.Add(AttachScripts(formula, value, ref position,
                                          ProcessCommand(formula, value, ref position, command)));
                return;
            }

            //Check if the command registered in FontID
            TexFont fontID = TEXPreference.main.GetFontByID(command);

            if (fontID != null)
            {
                RegisterTexFont(formula, value, ref position, fontID);
                return;
            }

            SymbolAtom symbolAtom = SymbolAtom.GetAtom(command);

            //Check if the command registered in Symbol database

            if (symbolAtom != null)
            {
                // Symbol was found.
                if (symbolAtom.GetRightType() == CharType.Accent && formula.RootAtom != null)
                {
                    //Accent is Found
                    Atom baseAtom = formula.RootAtom;
                    if (baseAtom is RowAtom)
                    {
                        var row = (RowAtom)baseAtom;
                        baseAtom = MatrixAtom.Last(row.Elements);
                        row.Elements.RemoveAt(row.Elements.Count - 1);
                    }
                    else
                    {
                        formula.RootAtom = null;
                    }
                    formula.Add(AttachScripts(formula, value, ref position, AccentedAtom.Get(baseAtom, symbolAtom)));
                }
                else
                {
                    formula.Add(AttachScripts(formula, value, ref position, symbolAtom));
                }
                return;
            }

            //No lucks, now ...

            {
                // Command aren't defined, use it as command text style
                RowAtom row = RowAtom.Get();
                for (int i = 0; i < command.Length; i++)
                {
                    var charAtom = CharAtom.Get(command [i],
                                                TEXConfiguration.main.Typeface_Commands);
                    row.Add(charAtom);
                }
                formula.Add(AttachScripts(formula, value, ref position, row));
            }
        }
        public static void CreateSDFAsset(TexFont font, string fontPath)
        {
            // Simple checks...
            if (!font.Font_Asset)
            {
                return;
            }
            // Expensive check, somewhat useless

            /*var objs = AssetDatabase.FindAssets("t:TMP_FontAsset");
             * foreach (var obj in objs)
             * {
             *  var asset = AssetDatabase.LoadAssetAtPath<TMP_FontAsset>(AssetDatabase.GUIDToAssetPath(obj));
             *  if (asset.name == font.name)
             *  {
             *      font.SDF_Asset = asset;
             *      return;
             *  }
             * }*/

            //TMPro_FontPlugin.LinkDebugLog();

            var error = 0;

            error = TMPro_FontPlugin.Initialize_FontEngine();
            if (error != 0 && error != 99)
            {
                throw new Exception("ERROR: " + error.ToString());
            }
            error = TMPro_FontPlugin.Load_TrueType_Font(fontPath);
            if (error != 0 && error != 99)
            {
                throw new Exception("ERROR: " + error.ToString());
            }
            error = TMPro_FontPlugin.FT_Size_Font(72);
            if (error != 0 && error != 99)
            {
                throw new Exception("ERROR: " + error.ToString());
            }

            _buffers = new byte[_bufferWidth * _bufferHeight];
            var charSet = new int[font.chars.Length];

            _glyphsInfo = new FT_GlyphInfo[font.chars.Length];
            _atlasInfo  = null;

            for (int i = 0; i < font.chars.Length; i++)
            {
                charSet[i] = font.chars[i].characterIndex;
            }
            float strokeSize = _styleStrokeSize;

            if (_render == RenderModes.DistanceField16)
            {
                strokeSize = _styleStrokeSize * 16;
            }
            if (_render == RenderModes.DistanceField32)
            {
                strokeSize = _styleStrokeSize * 32;
            }

            EditorApplication.update += OnUpdate;

            _renderedFont = font;
            ThreadPool.QueueUserWorkItem(SomeTask =>
            {
                onRendering = true;

                error = TMPro_FontPlugin.Render_Characters(_buffers, _bufferWidth, _bufferHeight, _padding,
                                                           charSet, charSet.Length, _style, strokeSize, true, _render, _optimized ? 4 : 0,
                                                           ref _faceInfo, _glyphsInfo);

                if (error != 0 && error != 99)
                {
                    onRendering = false;
                    throw new Exception("ERROR: " + error.ToString());
                }
                // Can't call OnFinished here because this isn't a Main thread
                hasRendered = true;

                Debug.LogFormat("Font Rendering of {0}.ttf is completed.", font.id);
            });
        }
        public static void CreateSDFAsset(TexFont font)
        {
            var fontPath = AssetDatabase.GetAssetPath(font.Font_Asset);

            CreateSDFAsset(font, fontPath);
        }
        public static void SetupGUI(TexFont font)
        {
            EditorGUI.BeginDisabledGroup(onRendering);
            GUILayout.BeginHorizontal();
            GUI.changed = false;

            GUILayout.Label("Atlas Resolution", GUILayout.Width(EditorGUIUtility.labelWidth));
            _bufferWidth  = EditorGUILayout.IntPopup(_bufferWidth, FontResolutionLabels, FontAtlasResolutions);  //, GUILayout.Width(80));
            _bufferHeight = EditorGUILayout.IntPopup(_bufferHeight, FontResolutionLabels, FontAtlasResolutions); //, GUILayout.Width(80));

            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Label("Padding", GUILayout.Width(EditorGUIUtility.labelWidth));
            _padding = EditorGUILayout.IntSlider(_padding, 1, 10);
            GUILayout.EndHorizontal();

            _render = (RenderModes)EditorGUILayout.EnumPopup(_render);
            if (GUILayout.Button("Render"))
            {
                CreateSDFAsset(font);
            }
            EditorGUI.BeginDisabledGroup(onRendering || !font.SDF_Asset);
            GUI.backgroundColor = Color.red;
            if (GUILayout.Button("Delete SDF Asset"))
            {
                AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(font.SDF_Asset));
                font.type = TexFontType.Font;
                font.Populate();
            }
            GUI.backgroundColor = Color.white;
            EditorGUI.EndDisabledGroup();
            {
                EditorGUILayout.Space();
                if (GUILayout.Button("Render All Fonts"))
                {
                    onRenderingBatch = (EditorUtility.DisplayDialogComplex("Confirm Action", "Are you sure? This will take few moments.\nAnd what will you do with existing SDF Asset?",
                                                                           "Overwrite", "Cancel", "Skip (Faster)"));
                    onRenderingBatch = onRenderingBatch == 1 ? 0 : (onRenderingBatch == 0 ? 1: 2);
                    if (onRenderingBatch > 0)
                    {
                        DoBatchRendering();
                    }
                }
                EditorGUI.BeginDisabledGroup(onRendering || !font.SDF_Asset);
                GUI.backgroundColor = new Color(0.5f, 0, 0.5f);
                if (GUILayout.Button("Delete All SDF Asset"))
                {
                    if (EditorUtility.DisplayDialog("Confirm Deletion", "Are you sure you want to delete ALL SDF Font Asset?", "Yes", "No"))
                    {
                        var fonts = TEXPreference.main.fontData;
                        for (int i = 0; i < fonts.Length; i++)
                        {
                            EditorUtility.DisplayProgressBar("Please wait", "Reimporting Fonts...", i / (float)fonts.Length);
                            var f = fonts[i];
                            if (f.type != TexFontType.Font_SDF)
                            {
                                continue;
                            }
                            AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(f.SDF_Asset));
                            f.type = TexFontType.Font;
                            f.Populate(false);
                        }
                        TEXPreference.main.RebuildMaterial();
                        EditorUtility.ClearProgressBar();
                    }
                }
                GUI.backgroundColor = Color.white;
                EditorGUI.EndDisabledGroup();
            }

            EditorGUI.EndDisabledGroup();
            if (onRendering)
            {
                var prog = TMPro_FontPlugin.Check_RenderProgress();
                EditorGUI.ProgressBar(EditorGUILayout.GetControlRect(), prog, prog.ToString("P"));
                if (onRenderingBatch > 0)
                {
                    if (onRenderingBatch == 3)
                    {
                        EditorGUILayout.HelpBox("Will be stopped after current rendering is done", MessageType.Info);
                    }
                    else
                    {
                        GUI.backgroundColor = Color.yellow;
                        if (GUILayout.Button("Cancel"))
                        {
                            onRenderingBatch = 3;
                        }
                        GUI.backgroundColor = Color.white;
                    }
                }
            }
        }
        static void OnFinished(TexFont font)
        {
            var sdfPath = TEXPreference.main.MainFolderPath + "/Fonts/TMPro/" + font.id + ".asset";

            TMP_FontAsset asset;

            if (!(asset = AssetDatabase.LoadAssetAtPath <TMP_FontAsset>(sdfPath)))
            {
                // It doesn't exist (or invalid), so create new
                asset = font.SDF_Asset = ScriptableObject.CreateInstance <TMP_FontAsset>();
                if (!AssetDatabase.IsValidFolder(TEXPreference.main.MainFolderPath + "/Fonts/TMPro"))
                {
                    AssetDatabase.CreateFolder(TEXPreference.main.MainFolderPath + "/Fonts", "TMPro");
                }
                AssetDatabase.CreateAsset(asset, sdfPath);
            }
            asset.fontAssetType = _render >= RenderModes.DistanceField16 ? TMP_FontAsset.FontAssetTypes.SDF : TMP_FontAsset.FontAssetTypes.Bitmap;
            FaceInfo face = GetFaceInfo(_faceInfo, 1);

            asset.AddFaceInfo(face);


            _atlasInfo = new Texture2D(_bufferWidth, _bufferHeight, TextureFormat.Alpha8, false, true);
            var _buffer32 = Array.ConvertAll(_buffers, x => new Color32(x, x, x, x));

            _atlasInfo.SetPixels32(_buffer32);
            _atlasInfo.Apply(false, true);


            // Add GlyphInfo[] to Font Asset
            TMP_Glyph[] glyphs = GetGlyphInfo(_glyphsInfo, 1);
            asset.AddGlyphInfo(glyphs);

            // Get and Add Kerning Pairs to Font Asset

            string       fontFilePath = AssetDatabase.GetAssetPath(font.Font_Asset);
            KerningTable kerningTable = GetKerningTable(fontFilePath, (int)face.PointSize);

            asset.AddKerningInfo(kerningTable);


            // Add Line Breaking Rules
            //LineBreakingTable lineBreakingTable = new LineBreakingTable();
            //


            // Add Font Atlas as Sub-Asset
            asset.atlas     = _atlasInfo;
            _atlasInfo.name = font.id + " Atlas";
#if !(UNITY_5_3 || UNITY_5_4)
            _atlasInfo.hideFlags = HideFlags.HideInHierarchy;
#endif
            AssetDatabase.AddObjectToAsset(_atlasInfo, asset);

            // Create new Material and Add it as Sub-Asset
            Shader   default_Shader = Shader.Find("TextMeshPro/Distance Field"); //m_shaderSelection;
            Material tmp_material   = new Material(default_Shader);

            tmp_material.name = _atlasInfo + " Material";
            tmp_material.SetTexture(ShaderUtilities.ID_MainTex, _atlasInfo);
            tmp_material.SetFloat(ShaderUtilities.ID_TextureWidth, _atlasInfo.width);
            tmp_material.SetFloat(ShaderUtilities.ID_TextureHeight, _atlasInfo.height);


            tmp_material.SetFloat(ShaderUtilities.ID_WeightNormal, asset.normalStyle);
            tmp_material.SetFloat(ShaderUtilities.ID_WeightBold, asset.boldStyle);

            int spread = _render >= RenderModes.DistanceField16 ? _padding + 1 : _padding;
            tmp_material.SetFloat(ShaderUtilities.ID_GradientScale, spread); // Spread = Padding for Brute Force SDF.

            asset.material = tmp_material;
#if !(UNITY_5_3 || UNITY_5_4)
            tmp_material.hideFlags = HideFlags.HideInHierarchy;
#endif
            AssetDatabase.AddObjectToAsset(tmp_material, asset);

            font.type      = TexFontType.Font_SDF;
            font.SDF_Asset = asset;
            font.Populate();
            AssetDatabase.SaveAssets();
        }