0030748: Visualization - Marker displayed in immediate layer ruins QT Quick view...
[occt.git] / src / OpenGl / OpenGl_Text.cxx
old mode 100755 (executable)
new mode 100644 (file)
index 4b95885..1fc4503
@@ -13,7 +13,7 @@
 // Alternatively, this file may be used under the terms of Open CASCADE
 // commercial license or contractual agreement.
 
-#include <OpenGl_AspectText.hxx>
+#include <OpenGl_Aspects.hxx>
 #include <OpenGl_GlCore11.hxx>
 #include <OpenGl_GraphicDriver.hxx>
 #include <OpenGl_ShaderManager.hxx>
 #include <OpenGl_ShaderStates.hxx>
 #include <OpenGl_Text.hxx>
 #include <OpenGl_Workspace.hxx>
+#include <OpenGl_View.hxx>
+#include <OpenGl_VertexBufferCompat.hxx>
 
 #include <Font_FontMgr.hxx>
+#include <Font_FTFont.hxx>
+#include <Graphic3d_TransformUtils.hxx>
 #include <TCollection_HAsciiString.hxx>
 
-#ifdef HAVE_CONFIG_H
-  #include <config.h>
-#endif
-
-#ifdef HAVE_GL2PS
-  #include <gl2ps.h>
-#endif
-
 namespace
 {
-  static const GLdouble THE_IDENTITY_MATRIX[4][4] =
+  static const GLdouble THE_IDENTITY_MATRIX[16] =
   {
-    {1.,0.,0.,0.},
-    {0.,1.,0.,0.},
-    {0.,0.,1.,0.},
-    {0.,0.,0.,1.}
+    1.0, 0.0, 0.0, 0.0,
+    0.0, 1.0, 0.0, 0.0,
+    0.0, 0.0, 1.0, 0.0,
+    0.0, 0.0, 0.0, 1.0
   };
 
-#ifdef HAVE_GL2PS
-  static char const* TheFamily[] = {"Helvetica", "Courier", "Times"};
-  static char const* TheItalic[] = {"Oblique",   "Oblique", "Italic"};
-  static char const* TheBase[]   = {"", "", "-Roman"};
+  static const TCollection_AsciiString THE_DEFAULT_FONT (Font_NOF_ASCII_MONO);
 
-  //! Convert font name used for rendering to some "good" font names
-  //! that produce good vector text.
-  static void getGL2PSFontName (const char* theSrcFont,
-                                char*       thePsFont)
+  //! Auxiliary tool for setting polygon offset temporarily.
+  struct BackPolygonOffsetSentry
   {
-    if (strstr (theSrcFont, "Symbol"))
-    {
-      sprintf (thePsFont, "%s", "Symbol");
-      return;
-    }
-    else if (strstr (theSrcFont, "ZapfDingbats"))
-    {
-      sprintf (thePsFont, "%s", "WingDings");
-      return;
-    }
-
-    int  aFontId  = 0;
-    bool isBold   = false;
-    bool isItalic = false;
-    if (strstr (theSrcFont, "Courier"))
-    {
-      aFontId = 1;
-    }
-    else if (strstr (theSrcFont, "Times"))
-    {
-      aFontId = 2;
-    }
-
-    if (strstr (theSrcFont, "Bold"))
-    {
-      isBold = true;
-    }
-    if (strstr (theSrcFont, "Italic")
-     || strstr (theSrcFont, "Oblique"))
-    {
-      isItalic = true;
-    }
-
-    if (isBold)
+    BackPolygonOffsetSentry (const Handle(OpenGl_Context)& theCtx)
+    : myCtx (theCtx),
+      myOffsetBack (!theCtx.IsNull() ? theCtx->PolygonOffset() : Graphic3d_PolygonOffset())
     {
-      if (isItalic)
-      {
-        sprintf (thePsFont, "%s-Bold%s", TheFamily[aFontId], TheItalic[aFontId]);
-      }
-      else
+      if (!theCtx.IsNull())
       {
-        sprintf (thePsFont, "%s-Bold", TheFamily[aFontId]);
+        Graphic3d_PolygonOffset aPolyOffset = myOffsetBack;
+        aPolyOffset.Mode = Aspect_POM_Fill;
+        aPolyOffset.Units += 1.0f;
+        theCtx->SetPolygonOffset (aPolyOffset);
       }
     }
-    else if (isItalic)
-    {
-      sprintf (thePsFont, "%s-%s", TheFamily[aFontId], TheItalic[aFontId]);
-    }
-    else
-    {
-      sprintf (thePsFont, "%s%s", TheFamily[aFontId], TheBase[aFontId]);
-    }
-  }
-
-  static void exportText (const NCollection_String& theText,
-                          const Standard_Boolean    theIs2d,
-                          const OpenGl_AspectText&  theAspect,
-                          const Standard_Integer    theHeight)
-  {
 
-    char aPsFont[64];
-    getGL2PSFontName (theAspect.FontName().ToCString(), aPsFont);
-
-    if (theIs2d)
-    {
-      glRasterPos2f (0.0f, 0.0f);
-    }
-    else
+    ~BackPolygonOffsetSentry()
     {
-      glRasterPos3f (0.0f, 0.0f, 0.0f);
+      if (!myCtx.IsNull())
+      {
+        myCtx->SetPolygonOffset (myOffsetBack);
+      }
     }
 
-    GLubyte aZero = 0;
-    glBitmap (1, 1, 0, 0, 0, 0, &aZero);
-
-    // Standard GL2PS's alignment isn't used, because it doesn't work correctly
-    // for all formats, therefore alignment is calculated manually relative
-    // to the bottom-left corner, which corresponds to the GL2PS_TEXT_BL value
-    gl2psTextOpt (theText.ToCString(), aPsFont, (GLshort)theHeight, GL2PS_TEXT_BL, theAspect.Angle());
-  }
-#endif
+  private:
+    BackPolygonOffsetSentry (const BackPolygonOffsetSentry& );
+    BackPolygonOffsetSentry& operator= (const BackPolygonOffsetSentry& );
+  private:
+    const Handle(OpenGl_Context)& myCtx;
+    const Graphic3d_PolygonOffset myOffsetBack;
+  };
 
-};
+} // anonymous namespace
 
 // =======================================================================
 // function : OpenGl_Text
@@ -147,7 +85,9 @@ OpenGl_Text::OpenGl_Text()
   myWinZ (0.0f),
   myScaleHeight (1.0f),
   myPoint  (0.0f, 0.0f, 0.0f),
-  myIs2d   (false)
+  myIs2d   (false),
+  myHasPlane (false),
+  myHasAnchorPoint (true)
 {
   myParams.Height = 10;
   myParams.HAlign = Graphic3d_HTA_LEFT;
@@ -169,11 +109,39 @@ OpenGl_Text::OpenGl_Text (const Standard_Utf8Char* theText,
   myParams (theParams),
   myString (theText),
   myPoint  (thePoint),
-  myIs2d   (false)
+  myIs2d   (false),
+  myHasPlane (false),
+  myHasAnchorPoint (true)
 {
   //
 }
 
+// =======================================================================
+// function : OpenGl_Text
+// purpose  :
+// =======================================================================
+OpenGl_Text::OpenGl_Text (const Standard_Utf8Char* theText,
+                          const gp_Ax2&            theOrientation,
+                          const OpenGl_TextParam&  theParams,
+                          const bool               theHasOwnAnchor)
+: myWinX         (0.0),
+  myWinY         (0.0),
+  myWinZ         (0.0),
+  myScaleHeight  (1.0),
+  myExportHeight (1.0),
+  myParams       (theParams),
+  myString       (theText),
+  myIs2d         (false),
+  myOrientation  (theOrientation),
+  myHasPlane     (true),
+  myHasAnchorPoint (theHasOwnAnchor)
+{
+  const gp_Pnt& aPoint = theOrientation.Location();
+  myPoint = OpenGl_Vec3 (static_cast<Standard_ShortReal> (aPoint.X()),
+                         static_cast<Standard_ShortReal> (aPoint.Y()),
+                         static_cast<Standard_ShortReal> (aPoint.Z()));
+}
+
 // =======================================================================
 // function : SetPosition
 // purpose  :
@@ -192,7 +160,7 @@ void OpenGl_Text::SetFontSize (const Handle(OpenGl_Context)& theCtx,
 {
   if (myParams.Height != theFontSize)
   {
-    Release (theCtx);
+    Release (theCtx.operator->());
   }
   myParams.Height = theFontSize;
 }
@@ -205,7 +173,7 @@ void OpenGl_Text::Init (const Handle(OpenGl_Context)& theCtx,
                         const Standard_Utf8Char*      theText,
                         const OpenGl_Vec3&            thePoint)
 {
-  releaseVbos (theCtx);
+  releaseVbos (theCtx.operator->());
   myIs2d   = false;
   myPoint  = thePoint;
   myString.FromUnicode (theText);
@@ -222,11 +190,11 @@ void OpenGl_Text::Init (const Handle(OpenGl_Context)& theCtx,
 {
   if (myParams.Height != theParams.Height)
   {
-    Release (theCtx);
+    Release (theCtx.operator->());
   }
   else
   {
-    releaseVbos (theCtx);
+    releaseVbos (theCtx.operator->());
   }
   myIs2d   = false;
   myParams = theParams;
@@ -245,17 +213,16 @@ void OpenGl_Text::Init (const Handle(OpenGl_Context)&     theCtx,
 {
   if (myParams.Height != theParams.Height)
   {
-    Release (theCtx);
+    Release (theCtx.operator->());
   }
   else
   {
-    releaseVbos (theCtx);
+    releaseVbos (theCtx.operator->());
   }
   myIs2d       = true;
   myParams     = theParams;
-  myPoint.xy() = thePoint;
-  myPoint.z()  = 0.0f;
-  myString.FromUnicode ((Standard_Utf16Char* )theText.ToExtString());
+  myPoint.SetValues (thePoint, 0.0f);
+  myString.FromUnicode (theText.ToExtString());
 }
 
 // =======================================================================
@@ -271,14 +238,14 @@ OpenGl_Text::~OpenGl_Text()
 // function : releaseVbos
 // purpose  :
 // =======================================================================
-void OpenGl_Text::releaseVbos (const Handle(OpenGl_Context)& theCtx)
+void OpenGl_Text::releaseVbos (OpenGl_Context* theCtx)
 {
   for (Standard_Integer anIter = 0; anIter < myVertsVbo.Length(); ++anIter)
   {
     Handle(OpenGl_VertexBuffer)& aVerts = myVertsVbo.ChangeValue (anIter);
     Handle(OpenGl_VertexBuffer)& aTCrds = myTCrdsVbo.ChangeValue (anIter);
 
-    if (!theCtx.IsNull())
+    if (theCtx != NULL)
     {
       theCtx->DelayedRelease (aVerts);
       theCtx->DelayedRelease (aTCrds);
@@ -286,26 +253,33 @@ void OpenGl_Text::releaseVbos (const Handle(OpenGl_Context)& theCtx)
     aVerts.Nullify();
     aTCrds.Nullify();
   }
+  if (theCtx != NULL
+  && !myBndVertsVbo.IsNull())
+  {
+    theCtx->DelayedRelease (myBndVertsVbo);
+  }
+
   myTextures.Clear();
   myVertsVbo.Clear();
   myTCrdsVbo.Clear();
-  myVertsArray.Clear();
-  myTCrdsArray.Clear();
+  myBndVertsVbo.Nullify();
 }
 
 // =======================================================================
 // function : Release
 // purpose  :
 // =======================================================================
-void OpenGl_Text::Release (const Handle(OpenGl_Context)& theCtx)
+void OpenGl_Text::Release (OpenGl_Context* theCtx)
 {
   releaseVbos (theCtx);
   if (!myFont.IsNull())
   {
-    Handle(OpenGl_Context) aCtx = theCtx;
     const TCollection_AsciiString aKey = myFont->ResourceKey();
     myFont.Nullify();
-    aCtx->ReleaseResource (aKey, Standard_True);
+    if (theCtx != NULL)
+    {
+      theCtx->ReleaseResource (aKey, Standard_True);
+    }
   }
 }
 
@@ -315,8 +289,9 @@ void OpenGl_Text::Release (const Handle(OpenGl_Context)& theCtx)
 // =======================================================================
 void OpenGl_Text::StringSize (const Handle(OpenGl_Context)& theCtx,
                               const NCollection_String&     theText,
-                              const OpenGl_AspectText&      theTextAspect,
+                              const OpenGl_Aspects&         theTextAspect,
                               const OpenGl_TextParam&       theParams,
+                              const unsigned int            theResolution,
                               Standard_ShortReal&           theWidth,
                               Standard_ShortReal&           theAscent,
                               Standard_ShortReal&           theDescent)
@@ -324,8 +299,8 @@ void OpenGl_Text::StringSize (const Handle(OpenGl_Context)& theCtx,
   theWidth   = 0.0f;
   theAscent  = 0.0f;
   theDescent = 0.0f;
-  const TCollection_AsciiString aFontKey = FontKey (theTextAspect, theParams.Height);
-  Handle(OpenGl_Font) aFont = FindFont (theCtx, theTextAspect, theParams.Height, aFontKey);
+  const TCollection_AsciiString aFontKey = FontKey (theTextAspect, theParams.Height, theResolution);
+  Handle(OpenGl_Font) aFont = FindFont (theCtx, theTextAspect, theParams.Height, theResolution, aFontKey);
   if (aFont.IsNull() || !aFont->IsValid())
   {
     return;
@@ -356,16 +331,16 @@ void OpenGl_Text::StringSize (const Handle(OpenGl_Context)& theCtx,
     }
     else if (aCharThis == ' ')
     {
-      aWidth += aFont->AdvanceX (aCharThis, aCharNext);
+      aWidth += aFont->FTFont()->AdvanceX (aCharThis, aCharNext);
       continue;
     }
     else if (aCharThis == '\t')
     {
-      aWidth += aFont->AdvanceX (' ', aCharNext) * 8.0f;
+      aWidth += aFont->FTFont()->AdvanceX (' ', aCharNext) * 8.0f;
       continue;
     }
 
-    aWidth += aFont->AdvanceX (aCharThis, aCharNext);
+    aWidth += aFont->FTFont()->AdvanceX (aCharThis, aCharNext);
   }
   theWidth = Max (theWidth, aWidth);
 
@@ -380,54 +355,33 @@ void OpenGl_Text::StringSize (const Handle(OpenGl_Context)& theCtx,
 // =======================================================================
 void OpenGl_Text::Render (const Handle(OpenGl_Workspace)& theWorkspace) const
 {
-  const OpenGl_AspectText* aTextAspect = theWorkspace->AspectText (Standard_True);
-  const Handle(OpenGl_Texture) aPrevTexture = theWorkspace->DisableTexture();
-
+  const OpenGl_Aspects* aTextAspect = theWorkspace->ApplyAspects();
   const Handle(OpenGl_Context)& aCtx = theWorkspace->GetGlContext();
+  const Handle(OpenGl_TextureSet) aPrevTexture = aCtx->BindTextures (Handle(OpenGl_TextureSet)());
 
-  if (aCtx->IsGlGreaterEqual (2, 0))
-  {
-    Handle(OpenGl_ShaderProgram) aProgram = aTextAspect->ShaderProgramRes (theWorkspace);
-
-    if (!aProgram.IsNull())
-    {
-      aProgram->BindWithVariables (aCtx);
-
-      const OpenGl_MaterialState* aMaterialState = aCtx->ShaderManager()->MaterialState (aProgram);
-
-      if (aMaterialState == NULL || aMaterialState->Aspect() != aTextAspect)
-        aCtx->ShaderManager()->UpdateMaterialStateTo (aProgram, aTextAspect);
+  // Bind custom shader program or generate default version
+  aCtx->ShaderManager()->BindFontProgram (aTextAspect->ShaderProgramRes (aCtx));
 
-      aCtx->ShaderManager()->PushState (aProgram);
-    }
-    else
-    {
-      OpenGl_ShaderProgram::Unbind (aCtx);
-    }
-  }
+  myOrientationMatrix = theWorkspace->View()->Camera()->OrientationMatrix();
+  myProjMatrix.Convert (aCtx->ProjectionState.Current());
 
   // use highlight color or colors from aspect
-  if (theWorkspace->NamedStatus & OPENGL_NS_HIGHLIGHT)
-  {
-    render (theWorkspace->PrinterContext(),
-            aCtx,
-            *aTextAspect,
-            *theWorkspace->HighlightColor,
-            *theWorkspace->HighlightColor);
-  }
-  else
-  {
-    render (theWorkspace->PrinterContext(),
-            aCtx,
-            *aTextAspect,
-            aTextAspect->Color(),
-            aTextAspect->SubtitleColor());
-  }
+  render (aCtx,
+          *aTextAspect,
+          theWorkspace->TextColor(),
+          theWorkspace->TextSubtitleColor(),
+          aCtx->Resolution());
 
   // restore aspects
   if (!aPrevTexture.IsNull())
   {
-    theWorkspace->EnableTexture (aPrevTexture);
+    aCtx->BindTextures (aPrevTexture);
+  }
+
+  // restore Z buffer settings
+  if (theWorkspace->UseZBuffer())
+  {
+    glEnable (GL_DEPTH_TEST);
   }
 }
 
@@ -435,138 +389,173 @@ void OpenGl_Text::Render (const Handle(OpenGl_Workspace)& theWorkspace) const
 // function : Render
 // purpose  :
 // =======================================================================
-void OpenGl_Text::Render (const Handle(OpenGl_PrinterContext)& thePrintCtx,
-                          const Handle(OpenGl_Context)&        theCtx,
-                          const OpenGl_AspectText&             theTextAspect) const
+void OpenGl_Text::Render (const Handle(OpenGl_Context)& theCtx,
+                          const OpenGl_Aspects& theTextAspect,
+                          unsigned int theResolution) const
 {
-  render (thePrintCtx, theCtx, theTextAspect, theTextAspect.Color(), theTextAspect.SubtitleColor());
+#if !defined(GL_ES_VERSION_2_0)
+  const Standard_Integer aPrevPolygonMode  = theCtx->SetPolygonMode (GL_FILL);
+  const bool             aPrevHatchingMode = theCtx->SetPolygonHatchEnabled (false);
+#endif
+
+  render (theCtx, theTextAspect,
+          theTextAspect.Aspect()->ColorRGBA(),
+          theTextAspect.Aspect()->ColorSubTitleRGBA(),
+          theResolution);
+
+#if !defined(GL_ES_VERSION_2_0)
+  theCtx->SetPolygonMode         (aPrevPolygonMode);
+  theCtx->SetPolygonHatchEnabled (aPrevHatchingMode);
+#endif
 }
 
 // =======================================================================
 // function : setupMatrix
 // purpose  :
 // =======================================================================
-void OpenGl_Text::setupMatrix (const Handle(OpenGl_PrinterContext)& thePrintCtx,
-                               const Handle(OpenGl_Context)&        /*theCtx*/,
-                               const OpenGl_AspectText&             theTextAspect,
-                               const OpenGl_Vec3                    theDVec) const
+void OpenGl_Text::setupMatrix (const Handle(OpenGl_Context)& theCtx,
+                               const OpenGl_Aspects& theTextAspect,
+                               const OpenGl_Vec3& theDVec) const
 {
-  // setup matrix
+  OpenGl_Mat4d aModViewMat;
+  OpenGl_Mat4d aProjectMat;
+  if (myHasPlane && myHasAnchorPoint)
+  {
+    aProjectMat = myProjMatrix * myOrientationMatrix;
+  }
+  else
+  {
+    aProjectMat = myProjMatrix;
+  }
+
   if (myIs2d)
   {
-    glLoadIdentity();
-    glTranslatef (myPoint.x() + theDVec.x(), myPoint.y() + theDVec.y(), 0.0f);
-    glScalef (1.0f, -1.0f, 1.0f);
-    glRotatef (theTextAspect.Angle(), 0.0, 0.0, 1.0);
+    Graphic3d_TransformUtils::Translate<GLdouble> (aModViewMat, myPoint.x() + theDVec.x(), myPoint.y() + theDVec.y(), 0.f);
+    Graphic3d_TransformUtils::Scale<GLdouble> (aModViewMat, 1.f, -1.f, 1.f);
+    Graphic3d_TransformUtils::Rotate<GLdouble> (aModViewMat, theTextAspect.Aspect()->TextAngle(), 0.f, 0.f, 1.f);
   }
   else
   {
     // align coordinates to the nearest integer
     // to avoid extra interpolation issues
     GLdouble anObjX, anObjY, anObjZ;
-    gluUnProject (std::floor (myWinX + (GLdouble )theDVec.x()),
-                  std::floor (myWinY + (GLdouble )theDVec.y()),
-                  myWinZ + (GLdouble )theDVec.z(),
-                  (GLdouble* )THE_IDENTITY_MATRIX, myProjMatrix, myViewport,
-                  &anObjX, &anObjY, &anObjZ);
-
-    glLoadIdentity();
-    glTranslated (anObjX, anObjY, anObjZ);
-    glRotated (theTextAspect.Angle(), 0.0, 0.0, 1.0);
-    if (!theTextAspect.IsZoomable())
-    {
-    #ifdef _WIN32
-      // if the context has assigned printer context, use it's parameters
-      if (!thePrintCtx.IsNull())
+    Graphic3d_TransformUtils::UnProject<Standard_Real> (std::floor (myWinX + theDVec.x()),
+                                                        std::floor (myWinY + theDVec.y()),
+                                                        myWinZ + theDVec.z(),
+                                                        OpenGl_Mat4d::Map (THE_IDENTITY_MATRIX),
+                                                        OpenGl_Mat4d::Map (aProjectMat),
+                                                        theCtx->Viewport(),
+                                                        anObjX,
+                                                        anObjY,
+                                                        anObjZ);
+
+    if (myHasPlane)
+    {
+      const gp_Dir& aVectorDir   = myOrientation.XDirection();
+      const gp_Dir& aVectorUp    = myOrientation.Direction();
+      const gp_Dir& aVectorRight = myOrientation.YDirection();
+
+      aModViewMat.SetColumn (2, OpenGl_Vec3d (aVectorUp.X(), aVectorUp.Y(), aVectorUp.Z()));
+      aModViewMat.SetColumn (1, OpenGl_Vec3d (aVectorRight.X(), aVectorRight.Y(), aVectorRight.Z()));
+      aModViewMat.SetColumn (0, OpenGl_Vec3d (aVectorDir.X(), aVectorDir.Y(), aVectorDir.Z()));
+
+      if (!myHasAnchorPoint)
       {
-        // get printing scaling in x and y dimensions
-        GLfloat aTextScalex = 1.0f, aTextScaley = 1.0f;
-        thePrintCtx->GetScale (aTextScalex, aTextScaley);
-
-        // text should be scaled in all directions with same
-        // factor to save its proportions, so use height (y) scaling
-        // as it is better for keeping text/3d graphics proportions
-        glScalef (aTextScaley, aTextScaley, aTextScaley);
+        OpenGl_Mat4d aPosMat;
+        aPosMat.SetColumn (3, OpenGl_Vec3d (myPoint.x(), myPoint.y(), myPoint.z()));
+        aPosMat *= aModViewMat;
+        aModViewMat.SetColumn (3, aPosMat.GetColumn (3));
       }
-    #endif
-      glScaled (myScaleHeight, myScaleHeight, myScaleHeight);
+      else
+      {
+        aModViewMat.SetColumn (3, OpenGl_Vec3d (anObjX, anObjY, anObjZ));
+      }
+    }
+    else
+    {
+      Graphic3d_TransformUtils::Translate<GLdouble> (aModViewMat, anObjX, anObjY, anObjZ);
+      Graphic3d_TransformUtils::Rotate<GLdouble> (aModViewMat, theTextAspect.Aspect()->TextAngle(), 0.0, 0.0, 1.0);
+    }
+
+    if (!theTextAspect.Aspect()->IsTextZoomable())
+    {
+      Graphic3d_TransformUtils::Scale<GLdouble> (aModViewMat, myScaleHeight, myScaleHeight, myScaleHeight);
     }
+    else if (theCtx->HasRenderScale())
+    {
+      Graphic3d_TransformUtils::Scale<GLdouble> (aModViewMat, theCtx->RenderScaleInv(), theCtx->RenderScaleInv(), theCtx->RenderScaleInv());
+    }
+  }
+
+  if (myHasPlane && !myHasAnchorPoint)
+  {
+    OpenGl_Mat4d aCurrentWorldViewMat;
+    aCurrentWorldViewMat.Convert (theCtx->WorldViewState.Current());
+    theCtx->WorldViewState.SetCurrent<Standard_Real> (aCurrentWorldViewMat * aModViewMat);
+  }
+  else
+  {
+    theCtx->WorldViewState.SetCurrent<Standard_Real> (aModViewMat);
+  }
+  theCtx->ApplyWorldViewMatrix();
+
+  if (!myIs2d)
+  {
+    theCtx->ProjectionState.SetCurrent<Standard_Real> (aProjectMat);
+    theCtx->ApplyProjectionMatrix();
   }
+
+  // Upload updated state to shader program
+  theCtx->ShaderManager()->PushState (theCtx->ActiveProgram());
 }
 
 // =======================================================================
 // function : drawText
 // purpose  :
 // =======================================================================
-
-void OpenGl_Text::drawText (const Handle(OpenGl_PrinterContext)& ,
-                            const Handle(OpenGl_Context)&        theCtx,
-                          #ifdef HAVE_GL2PS
-                            const OpenGl_AspectText&             theTextAspect) const
-                          #else
-                            const OpenGl_AspectText&                          ) const
-                          #endif
+void OpenGl_Text::drawText (const Handle(OpenGl_Context)& theCtx,
+                            const OpenGl_Aspects& theTextAspect) const
 {
-#ifdef HAVE_GL2PS
-  if (theCtx->IsFeedback())
+  (void )theTextAspect;
+  if (myVertsVbo.Length() != myTextures.Length()
+   || myTextures.IsEmpty())
   {
-    // position of the text and alignment is calculated by transformation matrix
-    exportText (myString, myIs2d, theTextAspect, (Standard_Integer )myExportHeight);
     return;
   }
-#endif
 
-  if (myVertsVbo.Length() == myTextures.Length())
-  {
-    for (Standard_Integer anIter = 0; anIter < myTextures.Length(); ++anIter)
-    {
-      const GLuint aTexId = myTextures.Value (anIter);
-      const Handle(OpenGl_VertexBuffer)& aVerts = myVertsVbo.Value (anIter);
-      const Handle(OpenGl_VertexBuffer)& aTCrds = myTCrdsVbo.Value (anIter);
-      aVerts->BindFixed (theCtx, GL_VERTEX_ARRAY);
-      aTCrds->BindFixed (theCtx, GL_TEXTURE_COORD_ARRAY);
-      glBindTexture (GL_TEXTURE_2D, aTexId);
-
-      glDrawArrays (GL_TRIANGLES, 0, GLsizei(aVerts->GetElemsNb()));
-
-      glBindTexture (GL_TEXTURE_2D, 0);
-      aTCrds->UnbindFixed (theCtx, GL_TEXTURE_COORD_ARRAY);
-      aVerts->UnbindFixed (theCtx, GL_VERTEX_ARRAY);
-    }
-  }
-  else if (myVertsArray.Length() == myTextures.Length())
+  for (Standard_Integer anIter = 0; anIter < myTextures.Length(); ++anIter)
   {
-    glEnableClientState (GL_VERTEX_ARRAY);
-    glEnableClientState (GL_TEXTURE_COORD_ARRAY);
-    for (Standard_Integer anIter = 0; anIter < myTextures.Length(); ++anIter)
-    {
-      const GLuint aTexId = myTextures.Value (anIter);
-      const Handle(OpenGl_Vec2Array)& aVerts = myVertsArray.Value (anIter);
-      const Handle(OpenGl_Vec2Array)& aTCrds = myTCrdsArray.Value (anIter);
+    const GLuint aTexId = myTextures.Value (anIter);
+    glBindTexture (GL_TEXTURE_2D, aTexId);
 
-      glVertexPointer   (2, GL_FLOAT, 0, (GLfloat* )&aVerts->First());
-      glTexCoordPointer (2, GL_FLOAT, 0, (GLfloat* )&aTCrds->First());
-      glBindTexture (GL_TEXTURE_2D, aTexId);
+    const Handle(OpenGl_VertexBuffer)& aVerts = myVertsVbo.Value (anIter);
+    const Handle(OpenGl_VertexBuffer)& aTCrds = myTCrdsVbo.Value (anIter);
+    aVerts->BindAttribute (theCtx, Graphic3d_TOA_POS);
+    aTCrds->BindAttribute (theCtx, Graphic3d_TOA_UV);
 
-      glDrawArrays (GL_TRIANGLES, 0, aVerts->Length());
+    glDrawArrays (GL_TRIANGLES, 0, GLsizei(aVerts->GetElemsNb()));
 
-      glBindTexture (GL_TEXTURE_2D, 0);
-    }
-    glDisableClientState (GL_TEXTURE_COORD_ARRAY);
-    glDisableClientState (GL_VERTEX_ARRAY);
+    aTCrds->UnbindAttribute (theCtx, Graphic3d_TOA_UV);
+    aVerts->UnbindAttribute (theCtx, Graphic3d_TOA_POS);
   }
+  glBindTexture (GL_TEXTURE_2D, 0);
 }
 
 // =======================================================================
 // function : FontKey
 // purpose  :
 // =======================================================================
-TCollection_AsciiString OpenGl_Text::FontKey (const OpenGl_AspectText& theAspect,
-                                              const Standard_Integer   theHeight)
+TCollection_AsciiString OpenGl_Text::FontKey (const OpenGl_Aspects& theAspect,
+                                              Standard_Integer theHeight,
+                                              unsigned int theResolution)
 {
-  const Font_FontAspect anAspect = (theAspect.FontAspect() != Font_FA_Undefined) ? theAspect.FontAspect() : Font_FA_Regular;
-  return theAspect.FontName()
+  const Font_FontAspect anAspect = theAspect.Aspect()->TextFontAspect() != Font_FA_Undefined
+                                 ? theAspect.Aspect()->TextFontAspect()
+                                 : Font_FA_Regular;
+  const TCollection_AsciiString& aFont = !theAspect.Aspect()->TextFont().IsNull() ? theAspect.Aspect()->TextFont()->String() : THE_DEFAULT_FONT;
+  return aFont
        + TCollection_AsciiString(":") + Standard_Integer(anAspect)
+       + TCollection_AsciiString(":") + Standard_Integer(theResolution)
        + TCollection_AsciiString(":") + theHeight;
 }
 
@@ -575,9 +564,10 @@ TCollection_AsciiString OpenGl_Text::FontKey (const OpenGl_AspectText& theAspect
 // purpose  :
 // =======================================================================
 Handle(OpenGl_Font) OpenGl_Text::FindFont (const Handle(OpenGl_Context)& theCtx,
-                                           const OpenGl_AspectText&      theAspect,
-                                           const Standard_Integer        theHeight,
-                                           const TCollection_AsciiString theKey)
+                                           const OpenGl_Aspects& theAspect,
+                                           Standard_Integer theHeight,
+                                           unsigned int theResolution,
+                                           const TCollection_AsciiString& theKey)
 {
   Handle(OpenGl_Font) aFont;
   if (theHeight < 2)
@@ -588,84 +578,147 @@ Handle(OpenGl_Font) OpenGl_Text::FindFont (const Handle(OpenGl_Context)& theCtx,
   if (!theCtx->GetResource (theKey, aFont))
   {
     Handle(Font_FontMgr) aFontMgr = Font_FontMgr::GetInstance();
-    const Handle(TCollection_HAsciiString) aFontName = new TCollection_HAsciiString (theAspect.FontName());
-    const Font_FontAspect anAspect = (theAspect.FontAspect() != Font_FA_Undefined) ? theAspect.FontAspect() : Font_FA_Regular;
-    Handle(Font_SystemFont) aRequestedFont = aFontMgr->FindFont (aFontName, anAspect, theHeight);
-    if (aRequestedFont.IsNull())
+    const TCollection_AsciiString& aFontName = !theAspect.Aspect()->TextFont().IsNull()
+                                             ?  theAspect.Aspect()->TextFont()->String()
+                                             :  THE_DEFAULT_FONT;
+    Font_FontAspect anAspect = theAspect.Aspect()->TextFontAspect() != Font_FA_Undefined
+                             ? theAspect.Aspect()->TextFontAspect()
+                             : Font_FA_Regular;
+    Font_FTFontParams aParams;
+    aParams.PointSize  = theHeight;
+    aParams.Resolution = theResolution;
+    if (Handle(Font_FTFont) aFontFt = Font_FTFont::FindAndCreate (aFontName, anAspect, aParams, Font_StrictLevel_Any))
+    {
+      aFont = new OpenGl_Font (aFontFt, theKey);
+      if (!aFont->Init (theCtx))
+      {
+        theCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
+                              TCollection_AsciiString ("Font '") + aFontName + "' - initialization of GL resources has failed!");
+        aFontFt.Nullify();
+        aFont->Release (theCtx.get());
+        aFont = new OpenGl_Font (aFontFt, theKey);
+      }
+    }
+    else
     {
-      return aFont;
+      theCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
+                           TCollection_AsciiString ("Font '") + aFontName + "' is not found in the system!");
+      aFont = new OpenGl_Font (aFontFt, theKey);
     }
 
-    Handle(Font_FTFont) aFontFt = new Font_FTFont (NULL);
-    if (!aFontFt->Init (aRequestedFont->FontPath()->ToCString(), theHeight))
+    theCtx->ShareResource (theKey, aFont);
+  }
+  return aFont;
+}
+
+// =======================================================================
+// function : drawRect
+// purpose  :
+// =======================================================================
+void OpenGl_Text::drawRect (const Handle(OpenGl_Context)& theCtx,
+                            const OpenGl_Aspects& theTextAspect,
+                            const OpenGl_Vec4& theColorSubs) const
+{
+  Handle(OpenGl_ShaderProgram) aPrevProgram = theCtx->ActiveProgram();
+  if (myBndVertsVbo.IsNull())
+  {
+    OpenGl_Vec2 aQuad[4] =
+    {
+      OpenGl_Vec2(myBndBox.Right, myBndBox.Bottom),
+      OpenGl_Vec2(myBndBox.Right, myBndBox.Top),
+      OpenGl_Vec2(myBndBox.Left,  myBndBox.Bottom),
+      OpenGl_Vec2(myBndBox.Left,  myBndBox.Top)
+    };
+    if (theCtx->ToUseVbo())
     {
-      return aFont;
+      myBndVertsVbo = new OpenGl_VertexBuffer();
     }
-
-    Handle(OpenGl_Context) aCtx = theCtx;
-    glPushAttrib (GL_TEXTURE_BIT);
-    aFont = new OpenGl_Font (aFontFt, theKey);
-    if (!aFont->Init (aCtx))
+    else
     {
-      //glPopAttrib();
-      //return aFont; // out of resources?
+      myBndVertsVbo = new OpenGl_VertexBufferCompat();
     }
-    glPopAttrib(); // texture bit
+    myBndVertsVbo->Init (theCtx, 2, 4, aQuad[0].GetData());
+  }
+
+  // bind unlit program
+  theCtx->ShaderManager()->BindFaceProgram (Handle(OpenGl_TextureSet)(), Graphic3d_TOSM_UNLIT,
+                                            Graphic3d_AlphaMode_Opaque, Standard_False, Standard_False,
+                                            Handle(OpenGl_ShaderProgram)());
 
-    aCtx->ShareResource (theKey, aFont);
+#if !defined(GL_ES_VERSION_2_0)
+  if (theCtx->core11 != NULL
+   && theCtx->ActiveProgram().IsNull())
+  {
+    glBindTexture (GL_TEXTURE_2D, 0);
   }
-  return aFont;
+#endif
+  theCtx->SetColor4fv (theColorSubs);
+  setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (0.0f, 0.0f, 0.0f));
+  myBndVertsVbo->BindAttribute (theCtx, Graphic3d_TOA_POS);
+
+  theCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
+
+  myBndVertsVbo->UnbindAttribute (theCtx, Graphic3d_TOA_POS);
+  theCtx->BindProgram (aPrevProgram);
 }
 
 // =======================================================================
 // function : render
 // purpose  :
 // =======================================================================
-void OpenGl_Text::render (const Handle(OpenGl_PrinterContext)& thePrintCtx,
-                          const Handle(OpenGl_Context)&        theCtx,
-                          const OpenGl_AspectText&             theTextAspect,
-                          const TEL_COLOUR&                    theColorText,
-                          const TEL_COLOUR&                    theColorSubs) const
+void OpenGl_Text::render (const Handle(OpenGl_Context)& theCtx,
+                          const OpenGl_Aspects& theTextAspect,
+                          const OpenGl_Vec4& theColorText,
+                          const OpenGl_Vec4& theColorSubs,
+                          unsigned int theResolution) const
 {
   if (myString.IsEmpty())
   {
     return;
   }
 
-  const TCollection_AsciiString aFontKey = FontKey (theTextAspect, myParams.Height);
+  // Note that using difference resolution in different Views in same Viewer
+  // will lead to performance regression (for example, text will be recreated every time).
+  const TCollection_AsciiString aFontKey = FontKey (theTextAspect, myParams.Height, theResolution);
   if (!myFont.IsNull()
    && !myFont->ResourceKey().IsEqual (aFontKey))
   {
     // font changed
-    const_cast<OpenGl_Text* > (this)->Release (theCtx);
+    const_cast<OpenGl_Text* > (this)->Release (theCtx.operator->());
   }
 
   if (myFont.IsNull())
   {
-    myFont = FindFont (theCtx, theTextAspect, myParams.Height, aFontKey);
-    if (myFont.IsNull())
-    {
-      return;
-    }
+    myFont = FindFont (theCtx, theTextAspect, myParams.Height, theResolution, aFontKey);
+  }
+  if (!myFont->WasInitialized())
+  {
+    return;
   }
 
   if (myTextures.IsEmpty())
   {
-    OpenGl_TextFormatter aFormatter;
+    Font_TextFormatter aFormatter;
     aFormatter.SetupAlignment (myParams.HAlign, myParams.VAlign);
     aFormatter.Reset();
-    aFormatter.Append (theCtx, myString, *myFont.operator->());
+
+    aFormatter.Append (myString, *myFont->FTFont().operator->());
     aFormatter.Format();
 
-    if (!theCtx->caps->vboDisable && theCtx->core15 != NULL)
-    {
-      aFormatter.Result (theCtx, myTextures, myVertsVbo, myTCrdsVbo);
-    }
-    else
+    OpenGl_TextBuilder aBuilder;
+    aBuilder.Perform (aFormatter,
+                      theCtx,
+                      *myFont.operator->(),
+                      myTextures,
+                      myVertsVbo,
+                      myTCrdsVbo);
+
+    aFormatter.BndBox (myBndBox);
+    if (!myBndVertsVbo.IsNull())
     {
-      aFormatter.Result (theCtx, myTextures, myVertsArray, myTCrdsArray);
+      myBndVertsVbo->Release (theCtx.get());
+      myBndVertsVbo.Nullify();
     }
-    aFormatter.BndBox (myBndBox);
   }
 
   if (myTextures.IsEmpty())
@@ -676,109 +729,114 @@ void OpenGl_Text::render (const Handle(OpenGl_PrinterContext)& thePrintCtx,
   myExportHeight = 1.0f;
   myScaleHeight  = 1.0f;
 
-  glMatrixMode (GL_MODELVIEW);
-  glPushMatrix();
+  theCtx->WorldViewState.Push();
+  myModelMatrix.Convert (theCtx->WorldViewState.Current() * theCtx->ModelWorldState.Current());
+
+  const GLdouble aPointSize = (GLdouble )myFont->FTFont()->PointSize();
   if (!myIs2d)
   {
-    // retrieve active matrices for project/unproject calls
-    glGetDoublev  (GL_MODELVIEW_MATRIX,  myModelMatrix);
-    glGetDoublev  (GL_PROJECTION_MATRIX, myProjMatrix);
-    glGetIntegerv (GL_VIEWPORT,          myViewport);
-    gluProject (myPoint.x(), myPoint.y(), myPoint.z(),
-                myModelMatrix, myProjMatrix, myViewport,
-                &myWinX, &myWinY, &myWinZ);
+    Graphic3d_TransformUtils::Project<Standard_Real> (myPoint.x(), myPoint.y(), myPoint.z(),
+                                                      myModelMatrix, myProjMatrix, theCtx->Viewport(),
+                                                      myWinX, myWinY, myWinZ);
 
     // compute scale factor for constant text height
-    GLdouble x1, y1, z1;
-    gluUnProject (myWinX, myWinY, myWinZ,
-                  (GLdouble* )THE_IDENTITY_MATRIX, myProjMatrix, myViewport,
-                  &x1, &y1, &z1);
-
-    GLdouble x2, y2, z2;
-    const GLdouble h = (GLdouble )myFont->FTFont()->PointSize();
-    gluUnProject (myWinX, myWinY + h - 1.0, myWinZ,
-                  (GLdouble* )THE_IDENTITY_MATRIX, myProjMatrix, myViewport,
-                  &x2, &y2, &z2);
-
-    myScaleHeight = (y2 - y1) / h;
-    if (theTextAspect.IsZoomable())
+    if (theTextAspect.Aspect()->IsTextZoomable())
+    {
+      myExportHeight = aPointSize;
+    }
+    else
     {
-      myExportHeight = (float )h;
+      Graphic3d_Vec3d aPnt1, aPnt2;
+      Graphic3d_TransformUtils::UnProject<Standard_Real> (myWinX, myWinY, myWinZ,
+                                                          OpenGl_Mat4d::Map (THE_IDENTITY_MATRIX), myProjMatrix, theCtx->Viewport(),
+                                                          aPnt1.x(), aPnt1.y(), aPnt1.z());
+      Graphic3d_TransformUtils::UnProject<Standard_Real> (myWinX, myWinY + aPointSize, myWinZ,
+                                                          OpenGl_Mat4d::Map (THE_IDENTITY_MATRIX), myProjMatrix, theCtx->Viewport(),
+                                                          aPnt2.x(), aPnt2.y(), aPnt2.z());
+      myScaleHeight = (aPnt2.y() - aPnt1.y()) / aPointSize;
     }
   }
-  myExportHeight = (float )myFont->FTFont()->PointSize() / myExportHeight;
-
-  // push enabled flags to the stack
-  glPushAttrib (GL_ENABLE_BIT);
-  glDisable (GL_LIGHTING);
+  myExportHeight = aPointSize / myExportHeight;
 
-  // setup depth test
-  if (!myIs2d
-   && theTextAspect.StyleType() != Aspect_TOST_ANNOTATION)
+#if !defined(GL_ES_VERSION_2_0)
+  if (theCtx->core11 != NULL
+   && theCtx->caps->ffpEnable)
   {
-    glEnable (GL_DEPTH_TEST);
+    glDisable (GL_LIGHTING);
   }
-  else
+#endif
+
+  // setup depth test
+  const bool hasDepthTest = !myIs2d
+                         && theTextAspect.Aspect()->TextStyle() != Aspect_TOST_ANNOTATION;
+  if (!hasDepthTest)
   {
     glDisable (GL_DEPTH_TEST);
   }
 
-  // setup alpha test
+  if (theCtx->core15fwd != NULL)
+  {
+    theCtx->core15fwd->glActiveTexture (GL_TEXTURE0);
+  }
+#if !defined(GL_ES_VERSION_2_0)
+  // activate texture unit
   GLint aTexEnvParam = GL_REPLACE;
-  glGetTexEnviv (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &aTexEnvParam);
-  if (aTexEnvParam != GL_REPLACE)
+  if (theCtx->core11 != NULL)
   {
-    glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
+    glDisable (GL_TEXTURE_1D);
+    glEnable  (GL_TEXTURE_2D);
+    glGetTexEnviv (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &aTexEnvParam);
+    if (aTexEnvParam != GL_REPLACE)
+    {
+      glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
+    }
   }
-  glAlphaFunc (GL_GEQUAL, 0.285f);
-  glEnable (GL_ALPHA_TEST);
+#endif
 
   // setup blending
   glEnable (GL_BLEND);
-  glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // GL_ONE
+  glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
 
-  // activate texture unit
-  glDisable (GL_TEXTURE_1D);
-  glEnable  (GL_TEXTURE_2D);
-  if (theCtx->core15fwd != NULL)
-  {
-    theCtx->core15fwd->glActiveTexture (GL_TEXTURE0);
-  }
+  // alpha to coverage makes text too thin
+  theCtx->SetSampleAlphaToCoverage (false);
 
   // extra drawings
-  switch (theTextAspect.DisplayType())
+  switch (theTextAspect.Aspect()->TextDisplayType())
   {
     case Aspect_TODT_BLEND:
     {
+    #if !defined(GL_ES_VERSION_2_0)
       glEnable  (GL_COLOR_LOGIC_OP);
       glLogicOp (GL_XOR);
+    #endif
       break;
     }
     case Aspect_TODT_SUBTITLE:
     {
-      glColor3fv  (theColorSubs.rgb);
-      setupMatrix (thePrintCtx, theCtx, theTextAspect, OpenGl_Vec3 (0.0f, 0.0f, 0.00001f));
-
-      glBindTexture (GL_TEXTURE_2D, 0);
-      glBegin (GL_QUADS);
-      glVertex2f (myBndBox.Left,  myBndBox.Top);
-      glVertex2f (myBndBox.Right, myBndBox.Top);
-      glVertex2f (myBndBox.Right, myBndBox.Bottom);
-      glVertex2f (myBndBox.Left,  myBndBox.Bottom);
-      glEnd();
+      BackPolygonOffsetSentry aPolygonOffsetTmp (hasDepthTest ? theCtx : Handle(OpenGl_Context)());
+      drawRect (theCtx, theTextAspect, theColorSubs);
       break;
     }
     case Aspect_TODT_DEKALE:
     {
-      glColor3fv  (theColorSubs.rgb);
-      setupMatrix (thePrintCtx, theCtx, theTextAspect, OpenGl_Vec3 (+1.0f, +1.0f, 0.00001f));
-      drawText    (thePrintCtx, theCtx, theTextAspect);
-      setupMatrix (thePrintCtx, theCtx, theTextAspect, OpenGl_Vec3 (-1.0f, -1.0f, 0.00001f));
-      drawText    (thePrintCtx, theCtx, theTextAspect);
-      setupMatrix (thePrintCtx, theCtx, theTextAspect, OpenGl_Vec3 (-1.0f, +1.0f, 0.00001f));
-      drawText    (thePrintCtx, theCtx, theTextAspect);
-      setupMatrix (thePrintCtx, theCtx, theTextAspect, OpenGl_Vec3 (+1.0f, -1.0f, 0.00001f));
-      drawText    (thePrintCtx, theCtx, theTextAspect);
+      BackPolygonOffsetSentry aPolygonOffsetTmp (hasDepthTest ? theCtx : Handle(OpenGl_Context)());
+      theCtx->SetColor4fv (theColorSubs);
+      setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (+1.0f, +1.0f, 0.0f));
+      drawText    (theCtx, theTextAspect);
+      setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (-1.0f, -1.0f, 0.0f));
+      drawText    (theCtx, theTextAspect);
+      setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (-1.0f, +1.0f, 0.0f));
+      drawText    (theCtx, theTextAspect);
+      setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (+1.0f, -1.0f, 0.0f));
+      drawText    (theCtx, theTextAspect);
+      break;
+    }
+    case Aspect_TODT_SHADOW:
+    {
+      BackPolygonOffsetSentry aPolygonOffsetTmp (hasDepthTest ? theCtx : Handle(OpenGl_Context)());
+      theCtx->SetColor4fv (theColorSubs);
+      setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (+1.0f, -1.0f, 0.0f));
+      drawText    (theCtx, theTextAspect);
       break;
     }
     case Aspect_TODT_DIMENSION:
@@ -789,46 +847,58 @@ void OpenGl_Text::render (const Handle(OpenGl_PrinterContext)& thePrintCtx,
   }
 
   // main draw call
-  glColor3fv  (theColorText.rgb);
-  setupMatrix (thePrintCtx, theCtx, theTextAspect, OpenGl_Vec3 (0.0f, 0.0f, 0.0f));
-  drawText    (thePrintCtx, theCtx, theTextAspect);
+  theCtx->SetColor4fv (theColorText);
+  setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (0.0f, 0.0f, 0.0f));
+  drawText    (theCtx, theTextAspect);
 
-  glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, aTexEnvParam);
+  if (!myIs2d)
+  {
+    theCtx->ProjectionState.SetCurrent<Standard_Real> (myProjMatrix);
+    theCtx->ApplyProjectionMatrix();
+  }
 
-  if (theTextAspect.DisplayType() == Aspect_TODT_DIMENSION)
+#if !defined(GL_ES_VERSION_2_0)
+  if (theCtx->core11 != NULL)
   {
-    setupMatrix (thePrintCtx, theCtx, theTextAspect, OpenGl_Vec3 (0.0f, 0.0f, 0.00001f));
+    glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, aTexEnvParam);
+  }
+#endif
 
+  if (theTextAspect.Aspect()->TextDisplayType() == Aspect_TODT_DIMENSION)
+  {
     glDisable (GL_BLEND);
-    glDisable (GL_TEXTURE_2D);
-    glDisable (GL_ALPHA_TEST);
     if (!myIs2d)
     {
       glDisable (GL_DEPTH_TEST);
     }
-    glColorMask (GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
+  #if !defined(GL_ES_VERSION_2_0)
+    if (theCtx->core11 != NULL)
+    {
+      glDisable (GL_TEXTURE_2D);
+    }
+  #endif
+    const bool aColorMaskBack = theCtx->SetColorMask (false);
 
     glClear (GL_STENCIL_BUFFER_BIT);
     glEnable (GL_STENCIL_TEST);
     glStencilFunc (GL_ALWAYS, 1, 0xFF);
     glStencilOp (GL_KEEP, GL_KEEP, GL_REPLACE);
 
-    glBegin (GL_QUADS);
-    glVertex2f (myBndBox.Left,  myBndBox.Top);
-    glVertex2f (myBndBox.Right, myBndBox.Top);
-    glVertex2f (myBndBox.Right, myBndBox.Bottom);
-    glVertex2f (myBndBox.Left,  myBndBox.Bottom);
-    glEnd();
+    drawRect (theCtx, theTextAspect, OpenGl_Vec4 (1.0f, 1.0f, 1.0f, 1.0f));
 
     glStencilFunc (GL_ALWAYS, 0, 0xFF);
-    // glPopAttrib() will reset state for us
-    //glDisable (GL_STENCIL_TEST);
-    //if (!myIs2d) glEnable (GL_DEPTH_TEST);
 
-    glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+    theCtx->SetColorMask (aColorMaskBack);
   }
 
-  // revert OpenGL state
-  glPopAttrib(); // enable bit
-  glPopMatrix(); // model view matrix was modified
+  // reset OpenGL state
+  glDisable (GL_BLEND);
+  glDisable (GL_STENCIL_TEST);
+#if !defined(GL_ES_VERSION_2_0)
+  glDisable (GL_COLOR_LOGIC_OP);
+#endif
+
+  // model view matrix was modified
+  theCtx->WorldViewState.Pop();
+  theCtx->ApplyModelViewMatrix();
 }