0031394: Visualization, TKOpenGl - define OpenGl_Element::EstimatedDataSize() interface
[occt.git] / src / OpenGl / OpenGl_Text.cxx
1 // Created on: 2011-07-13
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2013 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16 #include <OpenGl_Aspects.hxx>
17 #include <OpenGl_GlCore11.hxx>
18 #include <OpenGl_GraphicDriver.hxx>
19 #include <OpenGl_ShaderManager.hxx>
20 #include <OpenGl_ShaderProgram.hxx>
21 #include <OpenGl_ShaderStates.hxx>
22 #include <OpenGl_Text.hxx>
23 #include <OpenGl_Workspace.hxx>
24 #include <OpenGl_View.hxx>
25 #include <OpenGl_VertexBufferCompat.hxx>
26
27 #include <Font_FontMgr.hxx>
28 #include <Font_FTFont.hxx>
29 #include <Graphic3d_TransformUtils.hxx>
30 #include <TCollection_HAsciiString.hxx>
31
32 namespace
33 {
34   static const OpenGl_Mat4d THE_IDENTITY_MATRIX;
35
36   static const TCollection_AsciiString THE_DEFAULT_FONT (Font_NOF_ASCII_MONO);
37
38   //! Auxiliary tool for setting polygon offset temporarily.
39   struct BackPolygonOffsetSentry
40   {
41     BackPolygonOffsetSentry (OpenGl_Context* theCtx)
42     : myCtx (theCtx)
43     {
44       if (theCtx != NULL)
45       {
46         myOffsetBack = theCtx->PolygonOffset();
47         Graphic3d_PolygonOffset aPolyOffset = myOffsetBack;
48         aPolyOffset.Mode = Aspect_POM_Fill;
49         aPolyOffset.Units += 1.0f;
50         theCtx->SetPolygonOffset (aPolyOffset);
51       }
52     }
53
54     ~BackPolygonOffsetSentry()
55     {
56       if (myCtx != NULL)
57       {
58         myCtx->SetPolygonOffset (myOffsetBack);
59       }
60     }
61
62   private:
63     BackPolygonOffsetSentry (const BackPolygonOffsetSentry& );
64     BackPolygonOffsetSentry& operator= (const BackPolygonOffsetSentry& );
65   private:
66     OpenGl_Context* myCtx;
67     Graphic3d_PolygonOffset myOffsetBack;
68   };
69
70 } // anonymous namespace
71
72 // =======================================================================
73 // function : OpenGl_Text
74 // purpose  :
75 // =======================================================================
76 OpenGl_Text::OpenGl_Text()
77 : myScaleHeight (1.0f),
78   myIs2d        (Standard_False)
79 {
80   myText = new Graphic3d_Text (10.);
81 }
82
83
84 // =======================================================================
85 // function : OpenGl_Text
86 // purpose  :
87 // =======================================================================
88 OpenGl_Text::OpenGl_Text (const Handle(Graphic3d_Text)& theTextParams)
89 : myText        (theTextParams),
90   myScaleHeight (1.0f),
91   myIs2d        (Standard_False)
92 {
93 }
94
95 // =======================================================================
96 // function : SetPosition
97 // purpose  :
98 // =======================================================================
99 void OpenGl_Text::SetPosition (const OpenGl_Vec3& thePoint)
100 {
101   myText->SetPosition (gp_Pnt (thePoint.x(), thePoint.y(), thePoint.z()));
102 }
103
104 // =======================================================================
105 // function : SetFontSize
106 // purpose  :
107 // =======================================================================
108 void OpenGl_Text::SetFontSize (const Handle(OpenGl_Context)& theCtx,
109                                const Standard_Integer        theFontSize)
110 {
111   if (myText->Height() != theFontSize)
112   {
113     Release (theCtx.operator->());
114   }
115   myText->SetHeight ((Standard_ShortReal)theFontSize);
116 }
117
118 // =======================================================================
119 // function : Reset
120 // purpose  :
121 // =======================================================================
122 void OpenGl_Text::Reset (const Handle(OpenGl_Context)& theCtx)
123 {
124   if (!myFont.IsNull() && myFont->FTFont()->PointSize() != myText->Height())
125   {
126     Release (theCtx.operator->());
127   }
128   else
129   {
130     releaseVbos (theCtx.operator->());
131   }
132 }
133
134 // =======================================================================
135 // function : Init
136 // purpose  :
137 // =======================================================================
138 void OpenGl_Text::Init (const Handle(OpenGl_Context)& theCtx,
139                         const Standard_Utf8Char*      theText,
140                         const OpenGl_Vec3&            thePoint)
141 {
142   Reset (theCtx);
143   Set2D (Standard_False);
144
145   NCollection_String aText;
146   aText.FromUnicode (theText);
147   myText->SetText (aText);
148   myText->SetPosition (gp_Pnt (thePoint.x(), thePoint.y(), thePoint.z()));
149 }
150
151 // =======================================================================
152 // function : ~OpenGl_Text
153 // purpose  :
154 // =======================================================================
155 OpenGl_Text::~OpenGl_Text()
156 {
157   //
158 }
159
160 // =======================================================================
161 // function : releaseVbos
162 // purpose  :
163 // =======================================================================
164 void OpenGl_Text::releaseVbos (OpenGl_Context* theCtx)
165 {
166   for (Standard_Integer anIter = 0; anIter < myVertsVbo.Length(); ++anIter)
167   {
168     Handle(OpenGl_VertexBuffer)& aVerts = myVertsVbo.ChangeValue (anIter);
169     Handle(OpenGl_VertexBuffer)& aTCrds = myTCrdsVbo.ChangeValue (anIter);
170
171     if (theCtx != NULL)
172     {
173       theCtx->DelayedRelease (aVerts);
174       theCtx->DelayedRelease (aTCrds);
175     }
176     aVerts.Nullify();
177     aTCrds.Nullify();
178   }
179   if (theCtx != NULL
180   && !myBndVertsVbo.IsNull())
181   {
182     theCtx->DelayedRelease (myBndVertsVbo);
183   }
184
185   myTextures.Clear();
186   myVertsVbo.Clear();
187   myTCrdsVbo.Clear();
188   myBndVertsVbo.Nullify();
189 }
190
191 // =======================================================================
192 // function : Release
193 // purpose  :
194 // =======================================================================
195 void OpenGl_Text::Release (OpenGl_Context* theCtx)
196 {
197   releaseVbos (theCtx);
198   if (!myFont.IsNull())
199   {
200     const TCollection_AsciiString aKey = myFont->ResourceKey();
201     myFont.Nullify();
202     if (theCtx != NULL)
203     {
204       theCtx->ReleaseResource (aKey, Standard_True);
205     }
206   }
207 }
208
209 // =======================================================================
210 // function : EstimatedDataSize
211 // purpose  :
212 // =======================================================================
213 Standard_Size OpenGl_Text::EstimatedDataSize() const
214 {
215   Standard_Size aSize = 0;
216   for (Standard_Integer anIter = myVertsVbo.Lower(); anIter <= myVertsVbo.Upper(); ++anIter)
217   {
218     if (const Handle(OpenGl_VertexBuffer)& aVerts = myVertsVbo.Value (anIter))
219     {
220       aSize += aVerts->EstimatedDataSize();
221     }
222     if (const Handle(OpenGl_VertexBuffer)& aTCrds = myTCrdsVbo.Value (anIter))
223     {
224       aSize += aTCrds->EstimatedDataSize();
225     }
226   }
227   if (!myBndVertsVbo.IsNull())
228   {
229     aSize += myBndVertsVbo->EstimatedDataSize();
230   }
231   return aSize;
232 }
233
234 // =======================================================================
235 // function : StringSize
236 // purpose  :
237 // =======================================================================
238 void OpenGl_Text::StringSize (const Handle(OpenGl_Context)& theCtx,
239                               const NCollection_String&     theText,
240                               const OpenGl_Aspects&         theTextAspect,
241                               const Standard_ShortReal      theHeight,
242                               const unsigned int            theResolution,
243                               Standard_ShortReal&           theWidth,
244                               Standard_ShortReal&           theAscent,
245                               Standard_ShortReal&           theDescent)
246 {
247   theWidth   = 0.0f;
248   theAscent  = 0.0f;
249   theDescent = 0.0f;
250   const TCollection_AsciiString aFontKey = FontKey (theTextAspect, (Standard_Integer)theHeight, theResolution);
251   Handle(OpenGl_Font) aFont = FindFont (theCtx, theTextAspect, (Standard_Integer)theHeight, theResolution, aFontKey);
252   if (aFont.IsNull() || !aFont->IsValid())
253   {
254     return;
255   }
256
257   theAscent  = aFont->Ascender();
258   theDescent = aFont->Descender();
259
260   GLfloat aWidth = 0.0f;
261   for (NCollection_Utf8Iter anIter = theText.Iterator(); *anIter != 0;)
262   {
263     const Standard_Utf32Char aCharThis =   *anIter;
264     const Standard_Utf32Char aCharNext = *++anIter;
265
266     if (aCharThis == '\x0D' // CR  (carriage return)
267      || aCharThis == '\a'   // BEL (alarm)
268      || aCharThis == '\f'   // FF  (form feed) NP (new page)
269      || aCharThis == '\b'   // BS  (backspace)
270      || aCharThis == '\v')  // VT  (vertical tab)
271     {
272       continue; // skip unsupported carriage control codes
273     }
274     else if (aCharThis == '\x0A') // LF (line feed, new line)
275     {
276       theWidth = Max (theWidth, aWidth);
277       aWidth   = 0.0f;
278       continue;
279     }
280     else if (aCharThis == ' ')
281     {
282       aWidth += aFont->FTFont()->AdvanceX (aCharThis, aCharNext);
283       continue;
284     }
285     else if (aCharThis == '\t')
286     {
287       aWidth += aFont->FTFont()->AdvanceX (' ', aCharNext) * 8.0f;
288       continue;
289     }
290
291     aWidth += aFont->FTFont()->AdvanceX (aCharThis, aCharNext);
292   }
293   theWidth = Max (theWidth, aWidth);
294
295   Handle(OpenGl_Context) aCtx = theCtx;
296   aFont.Nullify();
297   aCtx->ReleaseResource (aFontKey, Standard_True);
298 }
299
300 // =======================================================================
301 // function : Render
302 // purpose  :
303 // =======================================================================
304 void OpenGl_Text::Render (const Handle(OpenGl_Workspace)& theWorkspace) const
305 {
306   const OpenGl_Aspects* aTextAspect = theWorkspace->ApplyAspects (false); // do not bind textures as they will be disabled anyway
307   const Handle(OpenGl_Context)& aCtx = theWorkspace->GetGlContext();
308
309   // Bind custom shader program or generate default version
310   aCtx->ShaderManager()->BindFontProgram (aTextAspect->ShaderProgramRes (aCtx));
311   const Handle(OpenGl_TextureSet) aPrevTexture = aCtx->BindTextures (Handle(OpenGl_TextureSet)(), Handle(OpenGl_ShaderProgram)());
312
313   if (myText->HasPlane() && myText->HasOwnAnchorPoint())
314   {
315     myOrientationMatrix = theWorkspace->View()->Camera()->OrientationMatrix();
316     // reset translation part
317     myOrientationMatrix.ChangeValue (0, 3) = 0.0;
318     myOrientationMatrix.ChangeValue (1, 3) = 0.0;
319     myOrientationMatrix.ChangeValue (2, 3) = 0.0;
320   }
321
322   myProjMatrix.Convert (aCtx->ProjectionState.Current());
323
324   // use highlight color or colors from aspect
325   render (aCtx,
326           *aTextAspect,
327           theWorkspace->TextColor(),
328           theWorkspace->TextSubtitleColor(),
329           aCtx->Resolution());
330
331   // restore aspects
332   if (!aPrevTexture.IsNull())
333   {
334     aCtx->BindTextures (aPrevTexture, Handle(OpenGl_ShaderProgram)());
335   }
336
337   // restore Z buffer settings
338   if (theWorkspace->UseZBuffer())
339   {
340     glEnable (GL_DEPTH_TEST);
341   }
342 }
343
344 // =======================================================================
345 // function : Render
346 // purpose  :
347 // =======================================================================
348 void OpenGl_Text::Render (const Handle(OpenGl_Context)& theCtx,
349                           const OpenGl_Aspects& theTextAspect,
350                           unsigned int theResolution) const
351 {
352 #if !defined(GL_ES_VERSION_2_0)
353   const Standard_Integer aPrevPolygonMode  = theCtx->SetPolygonMode (GL_FILL);
354   const bool             aPrevHatchingMode = theCtx->SetPolygonHatchEnabled (false);
355 #endif
356
357   render (theCtx, theTextAspect,
358           theTextAspect.Aspect()->ColorRGBA(),
359           theTextAspect.Aspect()->ColorSubTitleRGBA(),
360           theResolution);
361
362 #if !defined(GL_ES_VERSION_2_0)
363   theCtx->SetPolygonMode         (aPrevPolygonMode);
364   theCtx->SetPolygonHatchEnabled (aPrevHatchingMode);
365 #endif
366 }
367
368 // =======================================================================
369 // function : setupMatrix
370 // purpose  :
371 // =======================================================================
372 void OpenGl_Text::setupMatrix (const Handle(OpenGl_Context)& theCtx,
373                                const OpenGl_Aspects& theTextAspect,
374                                const OpenGl_Vec3& theDVec) const
375 {
376   OpenGl_Mat4d aModViewMat, aProjectMat;
377   if (myText->HasPlane() && myText->HasOwnAnchorPoint())
378   {
379     aProjectMat = myProjMatrix * myOrientationMatrix;
380   }
381   else
382   {
383     aProjectMat = myProjMatrix;
384   }
385
386   if (myIs2d)
387   {
388     const gp_Pnt& aPoint = myText->Position();
389     Graphic3d_TransformUtils::Translate<GLdouble> (aModViewMat, aPoint.X() + theDVec.x(), aPoint.Y() + theDVec.y(), 0.f);
390     Graphic3d_TransformUtils::Scale<GLdouble> (aModViewMat, 1.f, -1.f, 1.f);
391     Graphic3d_TransformUtils::Rotate<GLdouble> (aModViewMat, theTextAspect.Aspect()->TextAngle(), 0.f, 0.f, 1.f);
392   }
393   else
394   {
395     OpenGl_Vec3d anObjXYZ;
396     OpenGl_Vec3d aWinXYZ = myWinXYZ + OpenGl_Vec3d (theDVec);
397     if (!myText->HasPlane() && !theTextAspect.Aspect()->IsTextZoomable())
398     {
399       // Align coordinates to the nearest integer to avoid extra interpolation issues.
400       // Note that for better readability we could also try aligning freely rotated in 3D text (myHasPlane),
401       // when camera orientation co-aligned with horizontal text orientation,
402       // but this might look awkward while rotating camera.
403       aWinXYZ.x() = Floor (aWinXYZ.x());
404       aWinXYZ.y() = Floor (aWinXYZ.y());
405     }
406     Graphic3d_TransformUtils::UnProject<Standard_Real> (aWinXYZ.x(), aWinXYZ.y(), aWinXYZ.z(),
407                                                         THE_IDENTITY_MATRIX, aProjectMat, theCtx->Viewport(),
408                                                         anObjXYZ.x(), anObjXYZ.y(), anObjXYZ.z());
409
410     if (myText->HasPlane())
411     {
412       const gp_Ax2& anOrientation = myText->Orientation();
413       const gp_Dir& aVectorDir   = anOrientation.XDirection();
414       const gp_Dir& aVectorUp    = anOrientation.Direction();
415       const gp_Dir& aVectorRight = anOrientation.YDirection();
416
417       aModViewMat.SetColumn (2, OpenGl_Vec3d (aVectorUp.X(), aVectorUp.Y(), aVectorUp.Z()));
418       aModViewMat.SetColumn (1, OpenGl_Vec3d (aVectorRight.X(), aVectorRight.Y(), aVectorRight.Z()));
419       aModViewMat.SetColumn (0, OpenGl_Vec3d (aVectorDir.X(), aVectorDir.Y(), aVectorDir.Z()));
420
421       if (!myText->HasOwnAnchorPoint())
422       {
423         OpenGl_Mat4d aPosMat;
424         const gp_Pnt& aPoint = myText->Position();
425         aPosMat.SetColumn (3, OpenGl_Vec3d (aPoint.X(), aPoint.Y(), aPoint.Z()));
426         aPosMat *= aModViewMat;
427         aModViewMat.SetColumn (3, aPosMat.GetColumn (3));
428       }
429       else
430       {
431         aModViewMat.SetColumn (3, anObjXYZ);
432       }
433     }
434     else
435     {
436       Graphic3d_TransformUtils::Translate<GLdouble> (aModViewMat, anObjXYZ.x(), anObjXYZ.y(), anObjXYZ.z());
437       Graphic3d_TransformUtils::Rotate<GLdouble> (aModViewMat, theTextAspect.Aspect()->TextAngle(), 0.0, 0.0, 1.0);
438     }
439
440     if (!theTextAspect.Aspect()->IsTextZoomable())
441     {
442       Graphic3d_TransformUtils::Scale<GLdouble> (aModViewMat, myScaleHeight, myScaleHeight, myScaleHeight);
443     }
444     else if (theCtx->HasRenderScale())
445     {
446       Graphic3d_TransformUtils::Scale<GLdouble> (aModViewMat, theCtx->RenderScaleInv(), theCtx->RenderScaleInv(), theCtx->RenderScaleInv());
447     }
448   }
449
450   if (myText->HasPlane() && !myText->HasOwnAnchorPoint())
451   {
452     OpenGl_Mat4d aCurrentWorldViewMat;
453     aCurrentWorldViewMat.Convert (theCtx->WorldViewState.Current());
454     theCtx->WorldViewState.SetCurrent<Standard_Real> (aCurrentWorldViewMat * aModViewMat);
455   }
456   else
457   {
458     theCtx->WorldViewState.SetCurrent<Standard_Real> (aModViewMat);
459   }
460   theCtx->ApplyWorldViewMatrix();
461
462   if (!myIs2d)
463   {
464     theCtx->ProjectionState.SetCurrent<Standard_Real> (aProjectMat);
465     theCtx->ApplyProjectionMatrix();
466   }
467
468   // Upload updated state to shader program
469   theCtx->ShaderManager()->PushState (theCtx->ActiveProgram());
470 }
471
472 // =======================================================================
473 // function : drawText
474 // purpose  :
475 // =======================================================================
476 void OpenGl_Text::drawText (const Handle(OpenGl_Context)& theCtx,
477                             const OpenGl_Aspects& theTextAspect) const
478 {
479   (void )theTextAspect;
480   if (myVertsVbo.Length() != myTextures.Length()
481    || myTextures.IsEmpty())
482   {
483     return;
484   }
485
486   for (Standard_Integer anIter = 0; anIter < myTextures.Length(); ++anIter)
487   {
488     const GLuint aTexId = myTextures.Value (anIter);
489     glBindTexture (GL_TEXTURE_2D, aTexId);
490
491     const Handle(OpenGl_VertexBuffer)& aVerts = myVertsVbo.Value (anIter);
492     const Handle(OpenGl_VertexBuffer)& aTCrds = myTCrdsVbo.Value (anIter);
493     aVerts->BindAttribute (theCtx, Graphic3d_TOA_POS);
494     aTCrds->BindAttribute (theCtx, Graphic3d_TOA_UV);
495
496     glDrawArrays (GL_TRIANGLES, 0, GLsizei(aVerts->GetElemsNb()));
497
498     aTCrds->UnbindAttribute (theCtx, Graphic3d_TOA_UV);
499     aVerts->UnbindAttribute (theCtx, Graphic3d_TOA_POS);
500   }
501   glBindTexture (GL_TEXTURE_2D, 0);
502 }
503
504 // =======================================================================
505 // function : FontKey
506 // purpose  :
507 // =======================================================================
508 TCollection_AsciiString OpenGl_Text::FontKey (const OpenGl_Aspects& theAspect,
509                                               Standard_Integer theHeight,
510                                               unsigned int theResolution)
511 {
512   const Font_FontAspect anAspect = theAspect.Aspect()->TextFontAspect() != Font_FA_Undefined
513                                  ? theAspect.Aspect()->TextFontAspect()
514                                  : Font_FA_Regular;
515   const TCollection_AsciiString& aFont = !theAspect.Aspect()->TextFont().IsNull() ? theAspect.Aspect()->TextFont()->String() : THE_DEFAULT_FONT;
516   return aFont
517        + TCollection_AsciiString(":") + Standard_Integer(anAspect)
518        + TCollection_AsciiString(":") + Standard_Integer(theResolution)
519        + TCollection_AsciiString(":") + theHeight;
520 }
521
522 // =======================================================================
523 // function : FindFont
524 // purpose  :
525 // =======================================================================
526 Handle(OpenGl_Font) OpenGl_Text::FindFont (const Handle(OpenGl_Context)& theCtx,
527                                            const OpenGl_Aspects& theAspect,
528                                            Standard_Integer theHeight,
529                                            unsigned int theResolution,
530                                            const TCollection_AsciiString& theKey)
531 {
532   Handle(OpenGl_Font) aFont;
533   if (theHeight < 2)
534   {
535     return aFont; // invalid parameters
536   }
537
538   if (!theCtx->GetResource (theKey, aFont))
539   {
540     Handle(Font_FontMgr) aFontMgr = Font_FontMgr::GetInstance();
541     const TCollection_AsciiString& aFontName = !theAspect.Aspect()->TextFont().IsNull()
542                                              ?  theAspect.Aspect()->TextFont()->String()
543                                              :  THE_DEFAULT_FONT;
544     Font_FontAspect anAspect = theAspect.Aspect()->TextFontAspect() != Font_FA_Undefined
545                              ? theAspect.Aspect()->TextFontAspect()
546                              : Font_FA_Regular;
547     Font_FTFontParams aParams;
548     aParams.PointSize  = theHeight;
549     aParams.Resolution = theResolution;
550     if (Handle(Font_FTFont) aFontFt = Font_FTFont::FindAndCreate (aFontName, anAspect, aParams, Font_StrictLevel_Any))
551     {
552       aFont = new OpenGl_Font (aFontFt, theKey);
553       if (!aFont->Init (theCtx))
554       {
555         theCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
556                               TCollection_AsciiString ("Font '") + aFontName + "' - initialization of GL resources has failed!");
557         aFontFt.Nullify();
558         aFont->Release (theCtx.get());
559         aFont = new OpenGl_Font (aFontFt, theKey);
560       }
561     }
562     else
563     {
564       theCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
565                            TCollection_AsciiString ("Font '") + aFontName + "' is not found in the system!");
566       aFont = new OpenGl_Font (aFontFt, theKey);
567     }
568
569     theCtx->ShareResource (theKey, aFont);
570   }
571   return aFont;
572 }
573
574 // =======================================================================
575 // function : drawRect
576 // purpose  :
577 // =======================================================================
578 void OpenGl_Text::drawRect (const Handle(OpenGl_Context)& theCtx,
579                             const OpenGl_Aspects& theTextAspect,
580                             const OpenGl_Vec4& theColorSubs) const
581 {
582   Handle(OpenGl_ShaderProgram) aPrevProgram = theCtx->ActiveProgram();
583   if (myBndVertsVbo.IsNull())
584   {
585     OpenGl_Vec2 aQuad[4] =
586     {
587       OpenGl_Vec2(myBndBox.Right, myBndBox.Bottom),
588       OpenGl_Vec2(myBndBox.Right, myBndBox.Top),
589       OpenGl_Vec2(myBndBox.Left,  myBndBox.Bottom),
590       OpenGl_Vec2(myBndBox.Left,  myBndBox.Top)
591     };
592     if (theCtx->ToUseVbo())
593     {
594       myBndVertsVbo = new OpenGl_VertexBuffer();
595     }
596     else
597     {
598       myBndVertsVbo = new OpenGl_VertexBufferCompat();
599     }
600     myBndVertsVbo->Init (theCtx, 2, 4, aQuad[0].GetData());
601   }
602
603   // bind unlit program
604   theCtx->ShaderManager()->BindFaceProgram (Handle(OpenGl_TextureSet)(), Graphic3d_TOSM_UNLIT,
605                                             Graphic3d_AlphaMode_Opaque, Standard_False, Standard_False,
606                                             Handle(OpenGl_ShaderProgram)());
607
608 #if !defined(GL_ES_VERSION_2_0)
609   if (theCtx->core11 != NULL
610    && theCtx->ActiveProgram().IsNull())
611   {
612     glBindTexture (GL_TEXTURE_2D, 0);
613   }
614 #endif
615   theCtx->SetColor4fv (theColorSubs);
616   setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (0.0f, 0.0f, 0.0f));
617   myBndVertsVbo->BindAttribute (theCtx, Graphic3d_TOA_POS);
618
619   theCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
620
621   myBndVertsVbo->UnbindAttribute (theCtx, Graphic3d_TOA_POS);
622   theCtx->BindProgram (aPrevProgram);
623 }
624
625 // =======================================================================
626 // function : render
627 // purpose  :
628 // =======================================================================
629 void OpenGl_Text::render (const Handle(OpenGl_Context)& theCtx,
630                           const OpenGl_Aspects& theTextAspect,
631                           const OpenGl_Vec4& theColorText,
632                           const OpenGl_Vec4& theColorSubs,
633                           unsigned int theResolution) const
634 {
635   if (myText->Text().IsEmpty())
636   {
637     return;
638   }
639
640   // Note that using difference resolution in different Views in same Viewer
641   // will lead to performance regression (for example, text will be recreated every time).
642   const TCollection_AsciiString aFontKey = FontKey (theTextAspect, (Standard_Integer)myText->Height(), theResolution);
643   if (!myFont.IsNull()
644    && !myFont->ResourceKey().IsEqual (aFontKey))
645   {
646     // font changed
647     const_cast<OpenGl_Text* > (this)->Release (theCtx.operator->());
648   }
649
650   if (myFont.IsNull())
651   {
652     myFont = FindFont (theCtx, theTextAspect, (Standard_Integer)myText->Height(), theResolution, aFontKey);
653   }
654   if (!myFont->WasInitialized())
655   {
656     return;
657   }
658
659   if (myTextures.IsEmpty())
660   {
661     Font_TextFormatter aFormatter;
662
663     aFormatter.SetupAlignment (myText->HorizontalAlignment(), myText->VerticalAlignment());
664     aFormatter.Reset();
665
666     aFormatter.Append (myText->Text(), *myFont->FTFont());
667     aFormatter.Format();
668
669     OpenGl_TextBuilder aBuilder;
670     aBuilder.Perform (aFormatter,
671                       theCtx,
672                       *myFont.operator->(),
673                       myTextures,
674                       myVertsVbo,
675                       myTCrdsVbo);
676
677     aFormatter.BndBox (myBndBox);
678     if (!myBndVertsVbo.IsNull())
679     {
680       myBndVertsVbo->Release (theCtx.get());
681       myBndVertsVbo.Nullify();
682     }
683   }
684
685   if (myTextures.IsEmpty())
686   {
687     return;
688   }
689
690   myScaleHeight  = 1.0f;
691
692   theCtx->WorldViewState.Push();
693   myModelMatrix.Convert (theCtx->WorldViewState.Current() * theCtx->ModelWorldState.Current());
694
695   const GLdouble aPointSize = (GLdouble )myFont->FTFont()->PointSize();
696   if (!myIs2d)
697   {
698     const gp_Pnt& aPoint = myText->Position();
699     Graphic3d_TransformUtils::Project<Standard_Real> (aPoint.X(), aPoint.Y(), aPoint.Z(),
700                                                       myModelMatrix, myProjMatrix, theCtx->Viewport(),
701                                                       myWinXYZ.x(), myWinXYZ.y(), myWinXYZ.z());
702
703     // compute scale factor for constant text height
704     if (!theTextAspect.Aspect()->IsTextZoomable())
705     {
706       Graphic3d_Vec3d aPnt1, aPnt2;
707       Graphic3d_TransformUtils::UnProject<Standard_Real> (myWinXYZ.x(), myWinXYZ.y(), myWinXYZ.z(),
708                                                           THE_IDENTITY_MATRIX, myProjMatrix, theCtx->Viewport(),
709                                                           aPnt1.x(), aPnt1.y(), aPnt1.z());
710       Graphic3d_TransformUtils::UnProject<Standard_Real> (myWinXYZ.x(), myWinXYZ.y() + aPointSize, myWinXYZ.z(),
711                                                           THE_IDENTITY_MATRIX, myProjMatrix, theCtx->Viewport(),
712                                                           aPnt2.x(), aPnt2.y(), aPnt2.z());
713       myScaleHeight = (aPnt2.y() - aPnt1.y()) / aPointSize;
714     }
715   }
716
717 #if !defined(GL_ES_VERSION_2_0)
718   if (theCtx->core11 != NULL
719    && theCtx->caps->ffpEnable)
720   {
721     glDisable (GL_LIGHTING);
722   }
723 #endif
724
725   // setup depth test
726   const bool hasDepthTest = !myIs2d
727                          && theTextAspect.Aspect()->TextStyle() != Aspect_TOST_ANNOTATION;
728   if (!hasDepthTest)
729   {
730     glDisable (GL_DEPTH_TEST);
731   }
732
733   if (theCtx->core15fwd != NULL)
734   {
735     theCtx->core15fwd->glActiveTexture (GL_TEXTURE0);
736   }
737 #if !defined(GL_ES_VERSION_2_0)
738   // activate texture unit
739   GLint aTexEnvParam = GL_REPLACE;
740   if (theCtx->core11 != NULL)
741   {
742     glDisable (GL_TEXTURE_1D);
743     glEnable  (GL_TEXTURE_2D);
744     glGetTexEnviv (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &aTexEnvParam);
745     if (aTexEnvParam != GL_REPLACE)
746     {
747       glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
748     }
749   }
750 #endif
751
752   // setup blending
753   glEnable (GL_BLEND);
754   glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
755
756   // alpha to coverage makes text too thin
757   theCtx->SetSampleAlphaToCoverage (false);
758
759   // extra drawings
760   switch (theTextAspect.Aspect()->TextDisplayType())
761   {
762     case Aspect_TODT_BLEND:
763     {
764     #if !defined(GL_ES_VERSION_2_0)
765       glEnable  (GL_COLOR_LOGIC_OP);
766       glLogicOp (GL_XOR);
767     #endif
768       break;
769     }
770     case Aspect_TODT_SUBTITLE:
771     {
772       BackPolygonOffsetSentry aPolygonOffsetTmp (hasDepthTest ? theCtx.get() : NULL);
773       drawRect (theCtx, theTextAspect, theColorSubs);
774       break;
775     }
776     case Aspect_TODT_DEKALE:
777     {
778       BackPolygonOffsetSentry aPolygonOffsetTmp (hasDepthTest ? theCtx.get() : NULL);
779       theCtx->SetColor4fv (theColorSubs);
780       setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (+1.0f, +1.0f, 0.0f));
781       drawText    (theCtx, theTextAspect);
782       setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (-1.0f, -1.0f, 0.0f));
783       drawText    (theCtx, theTextAspect);
784       setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (-1.0f, +1.0f, 0.0f));
785       drawText    (theCtx, theTextAspect);
786       setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (+1.0f, -1.0f, 0.0f));
787       drawText    (theCtx, theTextAspect);
788       break;
789     }
790     case Aspect_TODT_SHADOW:
791     {
792       BackPolygonOffsetSentry aPolygonOffsetTmp (hasDepthTest ? theCtx.get() : NULL);
793       theCtx->SetColor4fv (theColorSubs);
794       setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (+1.0f, -1.0f, 0.0f));
795       drawText    (theCtx, theTextAspect);
796       break;
797     }
798     case Aspect_TODT_DIMENSION:
799     case Aspect_TODT_NORMAL:
800     {
801       break;
802     }
803   }
804
805   // main draw call
806   theCtx->SetColor4fv (theColorText);
807   setupMatrix (theCtx, theTextAspect, OpenGl_Vec3 (0.0f, 0.0f, 0.0f));
808   drawText    (theCtx, theTextAspect);
809
810   if (!myIs2d)
811   {
812     theCtx->ProjectionState.SetCurrent<Standard_Real> (myProjMatrix);
813     theCtx->ApplyProjectionMatrix();
814   }
815
816 #if !defined(GL_ES_VERSION_2_0)
817   if (theCtx->core11 != NULL)
818   {
819     glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, aTexEnvParam);
820   }
821 #endif
822
823   if (theTextAspect.Aspect()->TextDisplayType() == Aspect_TODT_DIMENSION)
824   {
825     glDisable (GL_BLEND);
826     if (!myIs2d)
827     {
828       glDisable (GL_DEPTH_TEST);
829     }
830   #if !defined(GL_ES_VERSION_2_0)
831     if (theCtx->core11 != NULL)
832     {
833       glDisable (GL_TEXTURE_2D);
834     }
835   #endif
836     const bool aColorMaskBack = theCtx->SetColorMask (false);
837
838     glClear (GL_STENCIL_BUFFER_BIT);
839     glEnable (GL_STENCIL_TEST);
840     glStencilFunc (GL_ALWAYS, 1, 0xFF);
841     glStencilOp (GL_KEEP, GL_KEEP, GL_REPLACE);
842
843     drawRect (theCtx, theTextAspect, OpenGl_Vec4 (1.0f, 1.0f, 1.0f, 1.0f));
844
845     glStencilFunc (GL_ALWAYS, 0, 0xFF);
846
847     theCtx->SetColorMask (aColorMaskBack);
848   }
849
850   // reset OpenGL state
851   glDisable (GL_BLEND);
852   glDisable (GL_STENCIL_TEST);
853 #if !defined(GL_ES_VERSION_2_0)
854   glDisable (GL_COLOR_LOGIC_OP);
855 #endif
856
857   // model view matrix was modified
858   theCtx->WorldViewState.Pop();
859   theCtx->ApplyModelViewMatrix();
860 }
861
862 // =======================================================================
863 // function : DumpJson
864 // purpose  :
865 // =======================================================================
866 void OpenGl_Text::DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth) const
867 {
868   OCCT_DUMP_CLASS_BEGIN (theOStream, OpenGl_Text)
869   OCCT_DUMP_BASE_CLASS (theOStream, theDepth, OpenGl_Element)
870
871   OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myTextures.Size())
872
873   for (NCollection_Vector<Handle(OpenGl_VertexBuffer)>::Iterator aCrdsIt (myTCrdsVbo); aCrdsIt.More(); aCrdsIt.Next())
874   {
875     const Handle(OpenGl_VertexBuffer)& aVertexBuffer = aCrdsIt.Value();
876     OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, aVertexBuffer.get())
877   }
878
879   OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, &myBndBox)
880 }