KiCad PCB EDA Suite
opengl_gal.cpp
Go to the documentation of this file.
1 /*
2  * This program source code file is part of KICAD, a free EDA CAD application.
3  *
4  * Copyright (C) 2012 Torsten Hueter, torstenhtr <at> gmx.de
5  * Copyright (C) 2012-2018 Kicad Developers, see AUTHORS.txt for contributors.
6  * Copyright (C) 2013-2017 CERN
7  * @author Maciej Suminski <maciej.suminski@cern.ch>
8  *
9  * Graphics Abstraction Layer (GAL) for OpenGL
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License
13  * as published by the Free Software Foundation; either version 2
14  * of the License, or (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, you may find one here:
23  * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
24  * or you may search the http://www.gnu.org website for the version 2 license,
25  * or you may write to the Free Software Foundation, Inc.,
26  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
27  */
28 
29 #include <gal/opengl/opengl_gal.h>
30 #include <gal/opengl/utils.h>
31 #include <gal/definitions.h>
32 #include <gl_context_mgr.h>
34 #include <text_utils.h>
35 #include <bitmap_base.h>
36 
37 #include <macros.h>
38 
39 #ifdef __WXDEBUG__
40 #include <profile.h>
41 #include <wx/log.h>
42 #endif /* __WXDEBUG__ */
43 
44 #include <limits>
45 #include <functional>
46 using namespace std::placeholders;
47 
48 
49 using namespace KIGFX;
50 
51 
52 // The current font is "Ubuntu Mono" available under Ubuntu Font Licence 1.0
53 // (see ubuntu-font-licence-1.0.txt for details)
54 #include "gl_resources.h"
55 #include "gl_builtin_shaders.h"
56 using namespace KIGFX::BUILTIN_FONT;
57 
58 static void InitTesselatorCallbacks( GLUtesselator* aTesselator );
59 static const int glAttributes[] = { WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_DEPTH_SIZE, 8, 0 };
60 
61 wxGLContext* OPENGL_GAL::glMainContext = NULL;
62 int OPENGL_GAL::instanceCounter = 0;
63 GLuint OPENGL_GAL::fontTexture = 0;
64 bool OPENGL_GAL::isBitmapFontLoaded = false;
65 SHADER* OPENGL_GAL::shader = NULL;
66 
67 namespace KIGFX {
69 {
70 public:
72  {
73  }
74 
75  ~GL_BITMAP_CACHE();
76 
77  GLuint RequestBitmap( const BITMAP_BASE* aBitmap );
78 
79 private:
80 
82  {
83  GLuint id;
84  int w, h;
85  };
86 
87  GLuint cacheBitmap( const BITMAP_BASE* aBitmap );
88 
89  std::map<const BITMAP_BASE*, CACHED_BITMAP> m_bitmaps;
90 };
91 
92 };
93 
94 
95 GL_BITMAP_CACHE::~GL_BITMAP_CACHE()
96 {
97  for ( auto b = m_bitmaps.begin(); b != m_bitmaps.end(); ++b )
98  {
99  glDeleteTextures( 1, &b->second.id );
100  }
101 }
102 
103 
104 GLuint GL_BITMAP_CACHE::RequestBitmap( const BITMAP_BASE* aBitmap )
105 {
106  auto it = m_bitmaps.find( aBitmap) ;
107 
108  if ( it != m_bitmaps.end() )
109  {
110  return it->second.id;
111  }
112  else
113  {
114  return cacheBitmap( aBitmap );
115  }
116 }
117 
118 
119 GLuint GL_BITMAP_CACHE::cacheBitmap( const BITMAP_BASE* aBitmap )
120 {
121  CACHED_BITMAP bmp;
122 
123  bmp.w = aBitmap->GetSizePixels().x;
124  bmp.h = aBitmap->GetSizePixels().y;
125 
126  // There are draw issues (incorrect rendering) with some w values.
127  // It happens when the w value is not a multiple of 4
128  // so we use only a sub image with a modified width
129  bmp.w -= bmp.w % 4;
130 
131  GLuint textureID;
132  glGenTextures(1, &textureID);
133 
134  uint8_t *buf = new uint8_t [ bmp.w * bmp.h * 3];
135  auto imgData = const_cast<BITMAP_BASE*>( aBitmap )->GetImageData();
136 
137  for( int y = 0; y < bmp.h; y++ )
138  {
139  for( int x = 0; x < bmp.w; x++ )
140  {
141  uint8_t *p = buf + ( bmp.w * y + x ) * 3;
142 
143  p[0] = imgData->GetRed( x, y );
144  p[1] = imgData->GetGreen( x, y );
145  p[2] = imgData->GetBlue( x, y );
146  }
147  }
148 
149  glBindTexture( GL_TEXTURE_2D, textureID );
150 
151  glTexImage2D( GL_TEXTURE_2D, 0,GL_RGB, bmp.w, bmp.h, 0, GL_RGB, GL_UNSIGNED_BYTE, buf );
152 
153  glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
154  glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
155 
156  delete [] buf;
157 
158  bmp.id = textureID;
159 
160  m_bitmaps[ aBitmap ] = bmp;
161 
162  return textureID;
163 }
164 
165 OPENGL_GAL::OPENGL_GAL( GAL_DISPLAY_OPTIONS& aDisplayOptions, wxWindow* aParent,
166  wxEvtHandler* aMouseListener, wxEvtHandler* aPaintListener,
167  const wxString& aName ) :
168  GAL( aDisplayOptions ),
169  HIDPI_GL_CANVAS( aParent, wxID_ANY, (int*) glAttributes, wxDefaultPosition, wxDefaultSize,
170  wxEXPAND, aName ),
171  mouseListener( aMouseListener ),
172  paintListener( aPaintListener ),
173  currentManager( nullptr ),
174  cachedManager( nullptr ),
175  nonCachedManager( nullptr ),
176  overlayManager( nullptr ),
177  mainBuffer( 0 ),
178  overlayBuffer( 0 ),
179  isContextLocked( false ),
180  lockClientCookie( 0 )
181 {
182 // IsDisplayAttr() handles WX_GL_{MAJOR,MINOR}_VERSION correctly only in 3.0.4
183 // starting with 3.1.0 one should use wxGLContext::IsOk() (done by GL_CONTEXT_MANAGER)
184 #if wxCHECK_VERSION( 3, 0, 3 ) and !wxCHECK_VERSION( 3, 1, 0 )
185  const int attr[] = { WX_GL_MAJOR_VERSION, 2, WX_GL_MINOR_VERSION, 1, 0 };
186 
187  if( !IsDisplaySupported( attr ) )
188  throw std::runtime_error( "OpenGL 2.1 or higher is required!" );
189 #endif /* wxCHECK_VERSION( 3, 0, 3 ) */
190 
191  if( glMainContext == NULL )
192  {
194 
195  if( !glMainContext )
196  throw std::runtime_error( "Could not create the main OpenGL context" );
197 
199  shader = new SHADER();
200  }
201  else
202  {
204 
205  if( !glPrivContext )
206  throw std::runtime_error( "Could not create a private OpenGL context" );
207  }
208 
209  ++instanceCounter;
210 
211  bitmapCache.reset( new GL_BITMAP_CACHE );
212 
215 
216  // Initialize the flags
217  isFramebufferInitialized = false;
218  isBitmapFontInitialized = false;
219  isInitialized = false;
220  isGrouping = false;
221  groupCounter = 0;
222 
223  // Connecting the event handlers
224  Connect( wxEVT_PAINT, wxPaintEventHandler( OPENGL_GAL::onPaint ) );
225 
226  // Mouse events are skipped to the parent
227  Connect( wxEVT_MOTION, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
228  Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
229  Connect( wxEVT_LEFT_UP, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
230  Connect( wxEVT_LEFT_DCLICK, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
231  Connect( wxEVT_MIDDLE_DOWN, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
232  Connect( wxEVT_MIDDLE_UP, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
233  Connect( wxEVT_MIDDLE_DCLICK, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
234  Connect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
235  Connect( wxEVT_RIGHT_UP, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
236  Connect( wxEVT_RIGHT_DCLICK, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
237  Connect( wxEVT_MOUSEWHEEL, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
238 #if wxCHECK_VERSION( 3, 1, 0 ) || defined( USE_OSX_MAGNIFY_EVENT )
239  Connect( wxEVT_MAGNIFY, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
240 #endif
241 #if defined _WIN32 || defined _WIN64
242  Connect( wxEVT_ENTER_WINDOW, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
243 #endif
244 
245  SetSize( aParent->GetClientSize() );
246  screenSize = VECTOR2I( aParent->GetClientSize() );
247 
248  // Grid color settings are different in Cairo and OpenGL
249  SetGridColor( COLOR4D( 0.8, 0.8, 0.8, 0.1 ) );
250  SetAxesColor( COLOR4D( BLUE ) );
251 
252  // Tesselator initialization
253  tesselator = gluNewTess();
255 
256  if( tesselator == NULL )
257  throw std::runtime_error( "Could not create the tesselator" );
258 
259  gluTessProperty( tesselator, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_POSITIVE );
260 
262 }
263 
264 
266 {
268 
269  --instanceCounter;
270  glFlush();
271  gluDeleteTess( tesselator );
272  ClearCache();
273 
274  delete compositor;
275 
276  if( isInitialized )
277  {
278  delete cachedManager;
279  delete nonCachedManager;
280  delete overlayManager;
281  }
282 
284 
285  // If it was the main context, then it will be deleted
286  // when the last OpenGL GAL instance is destroyed (a few lines below)
289 
290  // Are we destroying the last GAL instance?
291  if( instanceCounter == 0 )
292  {
294 
295  if( isBitmapFontLoaded )
296  {
297  glDeleteTextures( 1, &fontTexture );
298  isBitmapFontLoaded = false;
299  }
300 
301  delete shader;
302 
305  glMainContext = NULL;
306  }
307 }
308 
309 
311 {
312  bool refresh = false;
313 
315  {
317  isFramebufferInitialized = false;
318  refresh = true;
319  }
320 
321  if( super::updatedGalDisplayOptions( aOptions ) || refresh )
322  {
323  Refresh();
324  refresh = true;
325  }
326 
327  return refresh;
328 }
329 
331 {
332  auto matrix = GetScreenWorldMatrix();
333  return std::min( std::abs( matrix.GetScale().x ), std::abs( matrix.GetScale().y ) );
334 }
335 
337 {
338 #ifdef __WXDEBUG__
339  PROF_COUNTER totalRealTime( "OPENGL_GAL::beginDrawing()", true );
340 #endif /* __WXDEBUG__ */
341 
342  wxASSERT_MSG( isContextLocked, "GAL_DRAWING_CONTEXT RAII object should have locked context. "
343  "Calling GAL::beginDrawing() directly is not allowed." );
344 
345  wxASSERT_MSG( IsVisible(), "GAL::beginDrawing() must not be entered when GAL is not visible. "
346  "Other drawing routines will expect everything to be initialized "
347  "which will not be the case." );
348 
349  if( !isInitialized )
350  init();
351 
352  // Set up the view port
353  glMatrixMode( GL_PROJECTION );
354  glLoadIdentity();
355 
356  // Create the screen transformation (Do the RH-LH conversion here)
357  glOrtho( 0, (GLint) screenSize.x, (GLsizei) screenSize.y, 0, -depthRange.x, -depthRange.y );
358 
360  {
361  // Prepare rendering target buffers
365 
367  }
368 
369  compositor->Begin();
370 
371  // Disable 2D Textures
372  glDisable( GL_TEXTURE_2D );
373 
374  glShadeModel( GL_FLAT );
375 
376  // Enable the depth buffer
377  glEnable( GL_DEPTH_TEST );
378  glDepthFunc( GL_LESS );
379 
380  // Setup blending, required for transparent objects
381  glEnable( GL_BLEND );
382  glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
383 
384  glMatrixMode( GL_MODELVIEW );
385 
386  // Set up the world <-> screen transformation
388  GLdouble matrixData[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
389  matrixData[0] = worldScreenMatrix.m_data[0][0];
390  matrixData[1] = worldScreenMatrix.m_data[1][0];
391  matrixData[2] = worldScreenMatrix.m_data[2][0];
392  matrixData[4] = worldScreenMatrix.m_data[0][1];
393  matrixData[5] = worldScreenMatrix.m_data[1][1];
394  matrixData[6] = worldScreenMatrix.m_data[2][1];
395  matrixData[12] = worldScreenMatrix.m_data[0][2];
396  matrixData[13] = worldScreenMatrix.m_data[1][2];
397  matrixData[14] = worldScreenMatrix.m_data[2][2];
398  glLoadMatrixd( matrixData );
399 
400  // Set defaults
403 
404  // Remove all previously stored items
407 
411 
413  {
414  // Keep bitmap font texture always bound to the second texturing unit
415  const GLint FONT_TEXTURE_UNIT = 2;
416 
417  // Either load the font atlas to video memory, or simply bind it to a texture unit
418  if( !isBitmapFontLoaded )
419  {
420  glActiveTexture( GL_TEXTURE0 + FONT_TEXTURE_UNIT );
421  glGenTextures( 1, &fontTexture );
422  glBindTexture( GL_TEXTURE_2D, fontTexture );
423  glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB8, font_image.width, font_image.height,
424  0, GL_RGB, GL_UNSIGNED_BYTE, font_image.pixels );
425  glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
426  glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
427  checkGlError( "loading bitmap font" );
428 
429  glActiveTexture( GL_TEXTURE0 );
430 
431  isBitmapFontLoaded = true;
432  }
433  else
434  {
435  glActiveTexture( GL_TEXTURE0 + FONT_TEXTURE_UNIT );
436  glBindTexture( GL_TEXTURE_2D, fontTexture );
437  glActiveTexture( GL_TEXTURE0 );
438  }
439 
440  // Set shader parameter
441  GLint ufm_fontTexture = shader->AddParameter( "fontTexture" );
442  GLint ufm_fontTextureWidth = shader->AddParameter( "fontTextureWidth" );
443  ufm_worldPixelSize = shader->AddParameter( "worldPixelSize" );
444 
445  shader->Use();
446  shader->SetParameter( ufm_fontTexture, (int) FONT_TEXTURE_UNIT );
447  shader->SetParameter( ufm_fontTextureWidth, (int) font_image.width );
448  shader->Deactivate();
449  checkGlError( "setting bitmap font sampler as shader parameter" );
450 
452  }
453 
454  shader->Use();
456  shader->Deactivate();
457 
458  // Something betreen BeginDrawing and EndDrawing seems to depend on
459  // this texture unit being active, but it does not assure it itself.
460  glActiveTexture( GL_TEXTURE0 );
461 
462  // Unbind buffers - set compositor for direct drawing
464 
465 #ifdef __WXDEBUG__
466  totalRealTime.Stop();
467  wxLogTrace( "GAL_PROFILE", wxT( "OPENGL_GAL::beginDrawing(): %.1f ms" ), totalRealTime.msecs() );
468 #endif /* __WXDEBUG__ */
469 }
470 
471 
473 {
474  wxASSERT_MSG( isContextLocked, "What happened to the context lock?" );
475 
476 #ifdef __WXDEBUG__
477  PROF_COUNTER totalRealTime( "OPENGL_GAL::endDrawing()", true );
478 #endif /* __WXDEBUG__ */
479 
480  // Cached & non-cached containers are rendered to the same buffer
484 
485  // Overlay container is rendered to a different buffer
488 
489  // Be sure that the framebuffer is not colorized (happens on specific GPU&drivers combinations)
490  glColor4d( 1.0, 1.0, 1.0, 1.0 );
491 
492  // Draw the remaining contents, blit the rendering targets to the screen, swap the buffers
495  compositor->Present();
496  blitCursor();
497 
498  SwapBuffers();
499 
500 #ifdef __WXDEBUG__
501  totalRealTime.Stop();
502  wxLogTrace( "GAL_PROFILE", wxT( "OPENGL_GAL::endDrawing(): %.1f ms" ), totalRealTime.msecs() );
503 #endif /* __WXDEBUG__ */
504 }
505 
506 
507 void OPENGL_GAL::lockContext( int aClientCookie )
508 {
509  wxASSERT_MSG( !isContextLocked, "Context already locked." );
510  isContextLocked = true;
511  lockClientCookie = aClientCookie;
512 
514 }
515 
516 
517 void OPENGL_GAL::unlockContext( int aClientCookie )
518 {
519  wxASSERT_MSG( isContextLocked, "Context not locked. A GAL_CONTEXT_LOCKER RAII object must "
520  "be stacked rather than making separate lock/unlock calls." );
521 
522  wxASSERT_MSG( lockClientCookie == aClientCookie, "Context was locked by a different client. "
523  "Should not be possible with RAII objects." );
524 
525  isContextLocked = false;
526 
528 }
529 
530 
532 {
533  wxASSERT_MSG( isContextLocked, "GAL_UPDATE_CONTEXT RAII object should have locked context. "
534  "Calling this from anywhere else is not allowed." );
535 
536  wxASSERT_MSG( IsVisible(), "GAL::beginUpdate() must not be entered when GAL is not visible. "
537  "Other update routines will expect everything to be initialized "
538  "which will not be the case." );
539 
540  if( !isInitialized )
541  init();
542 
543  cachedManager->Map();
544 }
545 
546 
548 {
549  if( !isInitialized )
550  return;
551 
552  cachedManager->Unmap();
553 }
554 
555 
556 void OPENGL_GAL::DrawLine( const VECTOR2D& aStartPoint, const VECTOR2D& aEndPoint )
557 {
559 
560  drawLineQuad( aStartPoint, aEndPoint );
561 }
562 
563 
564 void OPENGL_GAL::DrawSegment( const VECTOR2D& aStartPoint, const VECTOR2D& aEndPoint,
565  double aWidth )
566 {
567  if( aStartPoint == aEndPoint ) // 0 length segments are just a circle.
568  {
569  DrawCircle( aStartPoint, aWidth/2 );
570  return;
571  }
572 
573  if( isFillEnabled || aWidth == 1.0 )
574  {
576 
577  SetLineWidth( aWidth );
578  drawLineQuad( aStartPoint, aEndPoint );
579  }
580  else
581  {
582  auto startEndVector = aEndPoint - aStartPoint;
583  auto lineAngle = startEndVector.Angle();
584  // Outlined tracks
585  double lineLength = startEndVector.EuclideanNorm();
586 
588 
589  Save();
590 
591  currentManager->Translate( aStartPoint.x, aStartPoint.y, 0.0 );
592  currentManager->Rotate( lineAngle, 0.0f, 0.0f, 1.0f );
593 
594  drawLineQuad( VECTOR2D( 0.0, aWidth / 2.0 ),
595  VECTOR2D( lineLength, aWidth / 2.0 ) );
596 
597  drawLineQuad( VECTOR2D( 0.0, -aWidth / 2.0 ),
598  VECTOR2D( lineLength, -aWidth / 2.0 ) );
599 
600  // Draw line caps
601  drawStrokedSemiCircle( VECTOR2D( 0.0, 0.0 ), aWidth / 2, M_PI / 2 );
602  drawStrokedSemiCircle( VECTOR2D( lineLength, 0.0 ), aWidth / 2, -M_PI / 2 );
603 
604  Restore();
605  }
606 }
607 
608 
609 void OPENGL_GAL::DrawCircle( const VECTOR2D& aCenterPoint, double aRadius )
610 {
611  if( isFillEnabled )
612  {
613  currentManager->Reserve( 3 );
615 
616  /* Draw a triangle that contains the circle, then shade it leaving only the circle.
617  * Parameters given to Shader() are indices of the triangle's vertices
618  * (if you want to understand more, check the vertex shader source [shader.vert]).
619  * Shader uses this coordinates to determine if fragments are inside the circle or not.
620  * v2
621  * /\
622  * //\\
623  * v0 /_\/_\ v1
624  */
626  currentManager->Vertex( aCenterPoint.x - aRadius * sqrt( 3.0f ), // v0
627  aCenterPoint.y - aRadius, layerDepth );
628 
630  currentManager->Vertex( aCenterPoint.x + aRadius * sqrt( 3.0f), // v1
631  aCenterPoint.y - aRadius, layerDepth );
632 
634  currentManager->Vertex( aCenterPoint.x, aCenterPoint.y + aRadius * 2.0f, // v2
635  layerDepth );
636  }
637 
638  if( isStrokeEnabled )
639  {
640  currentManager->Reserve( 3 );
642 
643  /* Draw a triangle that contains the circle, then shade it leaving only the circle.
644  * Parameters given to Shader() are indices of the triangle's vertices
645  * (if you want to understand more, check the vertex shader source [shader.vert]).
646  * and the line width. Shader uses this coordinates to determine if fragments are
647  * inside the circle or not.
648  * v2
649  * /\
650  * //\\
651  * v0 /_\/_\ v1
652  */
653  double outerRadius = aRadius + ( lineWidth / 2 );
655  currentManager->Vertex( aCenterPoint.x - outerRadius * sqrt( 3.0f ), // v0
656  aCenterPoint.y - outerRadius, layerDepth );
657 
659  currentManager->Vertex( aCenterPoint.x + outerRadius * sqrt( 3.0f ), // v1
660  aCenterPoint.y - outerRadius, layerDepth );
661 
663  currentManager->Vertex( aCenterPoint.x, aCenterPoint.y + outerRadius * 2.0f, // v2
664  layerDepth );
665  }
666 }
667 
668 
669 void OPENGL_GAL::DrawArc( const VECTOR2D& aCenterPoint, double aRadius, double aStartAngle,
670  double aEndAngle )
671 {
672  if( aRadius <= 0 )
673  return;
674 
675  // Swap the angles, if start angle is greater than end angle
676  SWAP( aStartAngle, >, aEndAngle );
677 
678  const double alphaIncrement = calcAngleStep( aRadius );
679 
680  Save();
681  currentManager->Translate( aCenterPoint.x, aCenterPoint.y, 0.0 );
682 
683  if( isFillEnabled )
684  {
685  double alpha;
688 
689  // Triangle fan
690  for( alpha = aStartAngle; ( alpha + alphaIncrement ) < aEndAngle; )
691  {
692  currentManager->Reserve( 3 );
693  currentManager->Vertex( 0.0, 0.0, layerDepth );
694  currentManager->Vertex( cos( alpha ) * aRadius, sin( alpha ) * aRadius, layerDepth );
695  alpha += alphaIncrement;
696  currentManager->Vertex( cos( alpha ) * aRadius, sin( alpha ) * aRadius, layerDepth );
697  }
698 
699  // The last missing triangle
700  const VECTOR2D endPoint( cos( aEndAngle ) * aRadius, sin( aEndAngle ) * aRadius );
701 
702  currentManager->Reserve( 3 );
703  currentManager->Vertex( 0.0, 0.0, layerDepth );
704  currentManager->Vertex( cos( alpha ) * aRadius, sin( alpha ) * aRadius, layerDepth );
705  currentManager->Vertex( endPoint.x, endPoint.y, layerDepth );
706  }
707 
708  if( isStrokeEnabled )
709  {
711 
712  VECTOR2D p( cos( aStartAngle ) * aRadius, sin( aStartAngle ) * aRadius );
713  double alpha;
714 
715  for( alpha = aStartAngle + alphaIncrement; alpha <= aEndAngle; alpha += alphaIncrement )
716  {
717  VECTOR2D p_next( cos( alpha ) * aRadius, sin( alpha ) * aRadius );
718  DrawLine( p, p_next );
719 
720  p = p_next;
721  }
722 
723  // Draw the last missing part
724  if( alpha != aEndAngle )
725  {
726  VECTOR2D p_last( cos( aEndAngle ) * aRadius, sin( aEndAngle ) * aRadius );
727  DrawLine( p, p_last );
728  }
729  }
730 
731  Restore();
732 }
733 
734 
735 void OPENGL_GAL::DrawArcSegment( const VECTOR2D& aCenterPoint, double aRadius, double aStartAngle,
736  double aEndAngle, double aWidth )
737 {
738  if( aRadius <= 0 )
739  {
740  // Arcs of zero radius are a circle of aWidth diameter
741  if( aWidth > 0 )
742  DrawCircle( aCenterPoint, aWidth / 2.0 );
743 
744  return;
745  }
746 
747  // Swap the angles, if start angle is greater than end angle
748  SWAP( aStartAngle, >, aEndAngle );
749 
750  const double alphaIncrement = calcAngleStep( aRadius );
751 
752  Save();
753  currentManager->Translate( aCenterPoint.x, aCenterPoint.y, 0.0 );
754 
755  if( isStrokeEnabled )
756  {
758 
759  double width = aWidth / 2.0;
760  VECTOR2D startPoint( cos( aStartAngle ) * aRadius,
761  sin( aStartAngle ) * aRadius );
762  VECTOR2D endPoint( cos( aEndAngle ) * aRadius,
763  sin( aEndAngle ) * aRadius );
764 
765  drawStrokedSemiCircle( startPoint, width, aStartAngle + M_PI );
766  drawStrokedSemiCircle( endPoint, width, aEndAngle );
767 
768  VECTOR2D pOuter( cos( aStartAngle ) * ( aRadius + width ),
769  sin( aStartAngle ) * ( aRadius + width ) );
770 
771  VECTOR2D pInner( cos( aStartAngle ) * ( aRadius - width ),
772  sin( aStartAngle ) * ( aRadius - width ) );
773 
774  double alpha;
775 
776  for( alpha = aStartAngle + alphaIncrement; alpha <= aEndAngle; alpha += alphaIncrement )
777  {
778  VECTOR2D pNextOuter( cos( alpha ) * ( aRadius + width ),
779  sin( alpha ) * ( aRadius + width ) );
780  VECTOR2D pNextInner( cos( alpha ) * ( aRadius - width ),
781  sin( alpha ) * ( aRadius - width ) );
782 
783  DrawLine( pOuter, pNextOuter );
784  DrawLine( pInner, pNextInner );
785 
786  pOuter = pNextOuter;
787  pInner = pNextInner;
788  }
789 
790  // Draw the last missing part
791  if( alpha != aEndAngle )
792  {
793  VECTOR2D pLastOuter( cos( aEndAngle ) * ( aRadius + width ),
794  sin( aEndAngle ) * ( aRadius + width ) );
795  VECTOR2D pLastInner( cos( aEndAngle ) * ( aRadius - width ),
796  sin( aEndAngle ) * ( aRadius - width ) );
797 
798  DrawLine( pOuter, pLastOuter );
799  DrawLine( pInner, pLastInner );
800  }
801  }
802 
803  if( isFillEnabled )
804  {
806  SetLineWidth( aWidth );
807 
808  VECTOR2D p( cos( aStartAngle ) * aRadius, sin( aStartAngle ) * aRadius );
809  double alpha;
810 
811  for( alpha = aStartAngle + alphaIncrement; alpha <= aEndAngle; alpha += alphaIncrement )
812  {
813  VECTOR2D p_next( cos( alpha ) * aRadius, sin( alpha ) * aRadius );
814  DrawLine( p, p_next );
815 
816  p = p_next;
817  }
818 
819  // Draw the last missing part
820  if( alpha != aEndAngle )
821  {
822  VECTOR2D p_last( cos( aEndAngle ) * aRadius, sin( aEndAngle ) * aRadius );
823  DrawLine( p, p_last );
824  }
825  }
826 
827  Restore();
828 }
829 
830 
831 void OPENGL_GAL::DrawRectangle( const VECTOR2D& aStartPoint, const VECTOR2D& aEndPoint )
832 {
833  // Compute the diagonal points of the rectangle
834  VECTOR2D diagonalPointA( aEndPoint.x, aStartPoint.y );
835  VECTOR2D diagonalPointB( aStartPoint.x, aEndPoint.y );
836 
837  // Fill the rectangle
838  if( isFillEnabled )
839  {
840  currentManager->Reserve( 6 );
843 
844  currentManager->Vertex( aStartPoint.x, aStartPoint.y, layerDepth );
845  currentManager->Vertex( diagonalPointA.x, diagonalPointA.y, layerDepth );
846  currentManager->Vertex( aEndPoint.x, aEndPoint.y, layerDepth );
847 
848  currentManager->Vertex( aStartPoint.x, aStartPoint.y, layerDepth );
849  currentManager->Vertex( aEndPoint.x, aEndPoint.y, layerDepth );
850  currentManager->Vertex( diagonalPointB.x, diagonalPointB.y, layerDepth );
851  }
852 
853  // Stroke the outline
854  if( isStrokeEnabled )
855  {
857 
858  std::deque<VECTOR2D> pointList;
859  pointList.push_back( aStartPoint );
860  pointList.push_back( diagonalPointA );
861  pointList.push_back( aEndPoint );
862  pointList.push_back( diagonalPointB );
863  pointList.push_back( aStartPoint );
864  DrawPolyline( pointList );
865  }
866 }
867 
868 
869 void OPENGL_GAL::DrawPolyline( const std::deque<VECTOR2D>& aPointList )
870 {
871  drawPolyline( [&](int idx) { return aPointList[idx]; }, aPointList.size() );
872 }
873 
874 
875 void OPENGL_GAL::DrawPolyline( const VECTOR2D aPointList[], int aListSize )
876 {
877  drawPolyline( [&](int idx) { return aPointList[idx]; }, aListSize );
878 }
879 
880 
882 {
883  auto numPoints = aLineChain.PointCount();
884 
885  if( aLineChain.IsClosed() )
886  numPoints += 1;
887 
888  drawPolyline( [&](int idx) { return aLineChain.CPoint(idx); }, numPoints );
889 }
890 
891 
892 void OPENGL_GAL::DrawPolygon( const std::deque<VECTOR2D>& aPointList )
893 {
894  auto points = std::unique_ptr<GLdouble[]>( new GLdouble[3 * aPointList.size()] );
895  GLdouble* ptr = points.get();
896 
897  for( const VECTOR2D& p : aPointList )
898  {
899  *ptr++ = p.x;
900  *ptr++ = p.y;
901  *ptr++ = layerDepth;
902  }
903 
904  drawPolygon( points.get(), aPointList.size() );
905 }
906 
907 
908 void OPENGL_GAL::DrawPolygon( const VECTOR2D aPointList[], int aListSize )
909 {
910  auto points = std::unique_ptr<GLdouble[]>( new GLdouble[3 * aListSize] );
911  GLdouble* target = points.get();
912  const VECTOR2D* src = aPointList;
913 
914  for( int i = 0; i < aListSize; ++i )
915  {
916  *target++ = src->x;
917  *target++ = src->y;
918  *target++ = layerDepth;
919  ++src;
920  }
921 
922  drawPolygon( points.get(), aListSize );
923 }
924 
925 
927 {
930 
931  if( isFillEnabled )
932  {
933  for( unsigned int j = 0; j < aPolySet.TriangulatedPolyCount(); ++j )
934  {
935  auto triPoly = aPolySet.TriangulatedPolygon( j );
936 
937  for( size_t i = 0; i < triPoly->GetTriangleCount(); i++ )
938  {
939  VECTOR2I a, b, c;
940  triPoly->GetTriangle( i, a, b, c );
941  currentManager->Vertex( a.x, a.y, layerDepth );
942  currentManager->Vertex( b.x, b.y, layerDepth );
943  currentManager->Vertex( c.x, c.y, layerDepth );
944  }
945  }
946  }
947 
948  if( isStrokeEnabled )
949  {
950  for( int j = 0; j < aPolySet.OutlineCount(); ++j )
951  {
952  const auto& poly = aPolySet.Polygon( j );
953 
954  for( const auto& lc : poly )
955  {
956  DrawPolyline( lc );
957  }
958  }
959  }
960 }
961 
962 
964 {
965  if ( aPolySet.IsTriangulationUpToDate() )
966  {
967  drawTriangulatedPolyset( aPolySet );
968  return;
969  }
970 
971  for( int j = 0; j < aPolySet.OutlineCount(); ++j )
972  {
973  const SHAPE_LINE_CHAIN& outline = aPolySet.COutline( j );
974 
975  if( outline.SegmentCount() == 0 )
976  continue;
977 
978  const int pointCount = outline.SegmentCount() + 1;
979  std::unique_ptr<GLdouble[]> points( new GLdouble[3 * pointCount] );
980  GLdouble* ptr = points.get();
981 
982  for( int i = 0; i < pointCount; ++i )
983  {
984  const VECTOR2I& p = outline.CPoint( i );
985  *ptr++ = p.x;
986  *ptr++ = p.y;
987  *ptr++ = layerDepth;
988  }
989 
990  drawPolygon( points.get(), pointCount );
991  }
992 }
993 
994 
995 void OPENGL_GAL::DrawCurve( const VECTOR2D& aStartPoint, const VECTOR2D& aControlPointA,
996  const VECTOR2D& aControlPointB, const VECTOR2D& aEndPoint )
997 {
998  // FIXME The drawing quality needs to be improved
999  // FIXME Perhaps choose a quad/triangle strip instead?
1000  // FIXME Brute force method, use a better (recursive?) algorithm
1001 
1002  std::deque<VECTOR2D> pointList;
1003 
1004  double t = 0.0;
1005  double dt = 1.0 / (double) CURVE_POINTS;
1006 
1007  for( int i = 0; i <= CURVE_POINTS; i++ )
1008  {
1009  double omt = 1.0 - t;
1010  double omt2 = omt * omt;
1011  double omt3 = omt * omt2;
1012  double t2 = t * t;
1013  double t3 = t * t2;
1014 
1015  VECTOR2D vertex = omt3 * aStartPoint + 3.0 * t * omt2 * aControlPointA
1016  + 3.0 * t2 * omt * aControlPointB + t3 * aEndPoint;
1017 
1018  pointList.push_back( vertex );
1019 
1020  t += dt;
1021  }
1022 
1023  DrawPolyline( pointList );
1024 }
1025 
1026 
1027 void OPENGL_GAL::DrawBitmap( const BITMAP_BASE& aBitmap )
1028 {
1029  // We have to calculate the pixel size in users units to draw the image.
1030  // worldUnitLength is a factor used for converting IU to inches
1031  double scale = 1.0 / ( aBitmap.GetPPI() * worldUnitLength );
1032  double w = (double) aBitmap.GetSizePixels().x * scale;
1033  double h = (double) aBitmap.GetSizePixels().y * scale;
1034 
1035  auto xform = currentManager->GetTransformation();
1036 
1037  glm::vec4 v0 = xform * glm::vec4( -w/2, -h/2, 0.0, 0.0 );
1038  glm::vec4 v1 = xform * glm::vec4( w/2, h/2, 0.0, 0.0 );
1039  glm::vec4 trans = xform[3];
1040 
1041  auto id = bitmapCache->RequestBitmap( &aBitmap );
1042 
1043  auto oldTarget = GetTarget();
1044 
1045  glPushMatrix();
1046  glTranslated( trans.x, trans.y, trans.z );
1047 
1049  glEnable(GL_TEXTURE_2D);
1050  glActiveTexture( GL_TEXTURE0 );
1051  glBindTexture( GL_TEXTURE_2D, id );
1052 
1053  glBegin( GL_QUADS );
1054  glColor4f( 1.0, 1.0, 1.0, 1.0 );
1055  glTexCoord2f( 0.0, 0.0 );
1056  glVertex3f( v0.x, v0.y, layerDepth );
1057  glColor4f( 1.0, 1.0, 1.0, 1.0 );
1058  glTexCoord2f( 1.0, 0.0 );
1059  glVertex3f( v1.x, v0.y, layerDepth );
1060  glColor4f( 1.0, 1.0, 1.0, 1.0 );
1061  glTexCoord2f( 1.0, 1.0 );
1062  glVertex3f( v1.x, v1.y, layerDepth );
1063  glColor4f( 1.0, 1.0, 1.0, 1.0 );
1064  glTexCoord2f( 0.0, 1.0 );
1065  glVertex3f( v0.x, v1.y, layerDepth );
1066  glEnd();
1067 
1068  SetTarget( oldTarget );
1069  glBindTexture( GL_TEXTURE_2D, 0 );
1070 
1071  glPopMatrix();
1072 }
1073 
1074 
1075 void OPENGL_GAL::BitmapText( const wxString& aText, const VECTOR2D& aPosition,
1076  double aRotationAngle )
1077 {
1078  wxASSERT_MSG( !IsTextMirrored(), "No support for mirrored text using bitmap fonts." );
1079 
1080  auto processedText = ProcessOverbars( aText );
1081  const auto& text = processedText.first;
1082  const auto& overbars = processedText.second;
1083 
1084  // Compute text size, so it can be properly justified
1085  VECTOR2D textSize;
1086  float commonOffset;
1087  std::tie( textSize, commonOffset ) = computeBitmapTextSize( text );
1088 
1089  const double SCALE = 1.4 * GetGlyphSize().y / textSize.y;
1090  bool overbar = false;
1091 
1092  int overbarLength = 0;
1093  double overbarHeight = textSize.y;
1094 
1095  Save();
1096 
1098  currentManager->Translate( aPosition.x, aPosition.y, layerDepth );
1099  currentManager->Rotate( aRotationAngle, 0.0f, 0.0f, -1.0f );
1100 
1101  double sx = SCALE * ( globalFlipX ? -1.0 : 1.0 );
1102  double sy = SCALE * ( globalFlipY ? -1.0 : 1.0 );
1103 
1104  currentManager->Scale( sx, sy, 0 );
1105  currentManager->Translate( 0, -commonOffset, 0 );
1106 
1107  switch( GetHorizontalJustify() )
1108  {
1110  Translate( VECTOR2D( -textSize.x / 2.0, 0 ) );
1111  break;
1112 
1114  //if( !IsTextMirrored() )
1115  Translate( VECTOR2D( -textSize.x, 0 ) );
1116  break;
1117 
1118  case GR_TEXT_HJUSTIFY_LEFT:
1119  //if( IsTextMirrored() )
1120  //Translate( VECTOR2D( -textSize.x, 0 ) );
1121  break;
1122  }
1123 
1124  switch( GetVerticalJustify() )
1125  {
1126  case GR_TEXT_VJUSTIFY_TOP:
1127  Translate( VECTOR2D( 0, -textSize.y ) );
1128  overbarHeight = -textSize.y / 2.0;
1129  break;
1130 
1132  Translate( VECTOR2D( 0, -textSize.y / 2.0 ) );
1133  overbarHeight = 0;
1134  break;
1135 
1137  break;
1138  }
1139 
1140  int i = 0;
1141 
1142  for( UTF8::uni_iter chIt = text.ubegin(), end = text.uend(); chIt < end; ++chIt )
1143  {
1144  unsigned int c = *chIt;
1145  wxASSERT_MSG( c != '\n' && c != '\r', wxT( "No support for multiline bitmap text yet" ) );
1146 
1147  // Handle overbar
1148  if( overbars[i] && !overbar )
1149  {
1150  overbar = true; // beginning of an overbar
1151  }
1152  else if( overbar && !overbars[i] )
1153  {
1154  overbar = false; // end of an overbar
1155  drawBitmapOverbar( overbarLength, overbarHeight );
1156  overbarLength = 0;
1157  }
1158 
1159  if( overbar )
1160  overbarLength += drawBitmapChar( c );
1161  else
1162  drawBitmapChar( c );
1163 
1164  ++i;
1165  }
1166 
1167  // Handle the case when overbar is active till the end of the drawn text
1168  currentManager->Translate( 0, commonOffset, 0 );
1169 
1170  if( overbar && overbarLength > 0 )
1171  drawBitmapOverbar( overbarLength, overbarHeight );
1172 
1173  Restore();
1174 }
1175 
1176 
1178 {
1181 
1183 
1184  // sub-pixel lines all render the same
1185  float minorLineWidth = std::fmax( 1.0f, gridLineWidth ) * getWorldPixelSize();
1186  float majorLineWidth = minorLineWidth * 2.0f;
1187 
1188  // Draw the axis and grid
1189  // For the drawing the start points, end points and increments have
1190  // to be calculated in world coordinates
1191  VECTOR2D worldStartPoint = screenWorldMatrix * VECTOR2D( 0.0, 0.0 );
1192  VECTOR2D worldEndPoint = screenWorldMatrix * VECTOR2D( screenSize );
1193 
1194  // Draw axes if desired
1195  if( axesEnabled )
1196  {
1197  SetLineWidth( minorLineWidth );
1199 
1200  DrawLine( VECTOR2D( worldStartPoint.x, 0 ), VECTOR2D( worldEndPoint.x, 0 ) );
1201  DrawLine( VECTOR2D( 0, worldStartPoint.y ), VECTOR2D( 0, worldEndPoint.y ) );
1202  }
1203 
1204  // force flush
1206 
1207  if( !gridVisibility )
1208  return;
1209 
1210  int gridScreenSizeDense = KiROUND( gridSize.x * worldScale );
1211  int gridScreenSizeCoarse = KiROUND( gridSize.x * static_cast<double>( gridTick ) * worldScale );
1212 
1213  const double gridThreshold = computeMinGridSpacing();
1214 
1215  // Check if the grid would not be too dense
1216  if( std::max( gridScreenSizeDense, gridScreenSizeCoarse ) < gridThreshold )
1217  return;
1218 
1219  // Compute grid staring and ending indexes to draw grid points on the
1220  // visible screen area
1221  // Note: later any point coordinate will be offsetted by gridOrigin
1222  int gridStartX = KiROUND( ( worldStartPoint.x - gridOrigin.x ) / gridSize.x );
1223  int gridEndX = KiROUND( ( worldEndPoint.x - gridOrigin.x ) / gridSize.x );
1224  int gridStartY = KiROUND( ( worldStartPoint.y - gridOrigin.y ) / gridSize.y );
1225  int gridEndY = KiROUND( ( worldEndPoint.y - gridOrigin.y ) / gridSize.y );
1226 
1227  // Ensure start coordinate > end coordinate
1228  if( gridStartX > gridEndX )
1229  std::swap( gridStartX, gridEndX );
1230 
1231  if( gridStartY > gridEndY )
1232  std::swap( gridStartY, gridEndY );
1233 
1234  // Ensure the grid fills the screen
1235  --gridStartX; ++gridEndX;
1236  --gridStartY; ++gridEndY;
1237 
1238  glDisable( GL_DEPTH_TEST );
1239  glDisable( GL_TEXTURE_2D );
1240 
1241  if( gridStyle == GRID_STYLE::DOTS )
1242  {
1243  glEnable( GL_STENCIL_TEST );
1244  glStencilFunc( GL_ALWAYS, 1, 1 );
1245  glStencilOp( GL_KEEP, GL_KEEP, GL_INCR );
1246  glColor4d( 0.0, 0.0, 0.0, 0.0 );
1247  SetStrokeColor( COLOR4D( 0.0, 0.0, 0.0, 0.0 ) );
1248  }
1249  else
1250  {
1251  glColor4d( gridColor.r, gridColor.g, gridColor.b, gridColor.a );
1253  }
1254 
1256  {
1257  SetLineWidth( minorLineWidth );
1258 
1259  // calculate a line len = 2 minorLineWidth, in internal unit value
1260  // (in fact the size of cross is lineLen*2)
1261  int lineLen = KiROUND( minorLineWidth * 2.0 );
1262 
1263  // Vertical positions
1264  for( int j = gridStartY; j <= gridEndY; j++ )
1265  {
1266  if( ( j % gridTick == 0 && gridScreenSizeCoarse > gridThreshold )
1267  || gridScreenSizeDense > gridThreshold )
1268  {
1269  int posY = j * gridSize.y + gridOrigin.y;
1270 
1271  // Horizontal positions
1272  for( int i = gridStartX; i <= gridEndX; i++ )
1273  {
1274  if( ( i % gridTick == 0 && gridScreenSizeCoarse > gridThreshold )
1275  || gridScreenSizeDense > gridThreshold )
1276  {
1277  int posX = i * gridSize.x + gridOrigin.x;
1278 
1279  DrawLine( VECTOR2D( posX - lineLen, posY ), VECTOR2D( posX + lineLen, posY ) );
1280  DrawLine( VECTOR2D( posX, posY - lineLen ), VECTOR2D( posX, posY + lineLen ) );
1281  }
1282  }
1283  }
1284  }
1285 
1287  }
1288  else
1289  {
1290  // Vertical lines
1291  for( int j = gridStartY; j <= gridEndY; j++ )
1292  {
1293  const double y = j * gridSize.y + gridOrigin.y;
1294 
1295  // If axes are drawn, skip the lines that would cover them
1296  if( axesEnabled && y == 0 )
1297  continue;
1298 
1299  if( j % gridTick == 0 && gridScreenSizeDense > gridThreshold )
1300  SetLineWidth( majorLineWidth );
1301  else
1302  SetLineWidth( minorLineWidth );
1303 
1304  if( ( j % gridTick == 0 && gridScreenSizeCoarse > gridThreshold )
1305  || gridScreenSizeDense > gridThreshold )
1306  {
1307  VECTOR2D a ( gridStartX * gridSize.x + gridOrigin.x, y );
1308  VECTOR2D b ( gridEndX * gridSize.x + gridOrigin.x, y );
1309 
1310  DrawLine( a, b );
1311  }
1312  }
1313 
1315 
1316  if( gridStyle == GRID_STYLE::DOTS )
1317  {
1318  glStencilFunc( GL_NOTEQUAL, 0, 1 );
1319  glColor4d( gridColor.r, gridColor.g, gridColor.b, gridColor.a );
1321  }
1322 
1323  // Horizontal lines
1324  for( int i = gridStartX; i <= gridEndX; i++ )
1325  {
1326  const double x = i * gridSize.x + gridOrigin.x;
1327 
1328  // If axes are drawn, skip the lines that would cover them
1329  if( axesEnabled && x == 0 )
1330  continue;
1331 
1332  if( i % gridTick == 0 && gridScreenSizeDense > gridThreshold )
1333  SetLineWidth( majorLineWidth );
1334  else
1335  SetLineWidth( minorLineWidth );
1336 
1337  if( ( i % gridTick == 0 && gridScreenSizeCoarse > gridThreshold )
1338  || gridScreenSizeDense > gridThreshold )
1339  {
1340  VECTOR2D a ( x, gridStartY * gridSize.y + gridOrigin.y );
1341  VECTOR2D b ( x, gridEndY * gridSize.y + gridOrigin.y );
1342  DrawLine( a, b );
1343  }
1344  }
1345 
1347 
1348  if( gridStyle == GRID_STYLE::DOTS )
1349  glDisable( GL_STENCIL_TEST );
1350  }
1351 
1352  glEnable( GL_DEPTH_TEST );
1353  glEnable( GL_TEXTURE_2D );
1354 }
1355 
1356 
1357 void OPENGL_GAL::ResizeScreen( int aWidth, int aHeight )
1358 {
1359  screenSize = VECTOR2I( aWidth, aHeight );
1360 
1361  // Resize framebuffers
1362  const float scaleFactor = GetBackingScaleFactor();
1363  compositor->Resize( aWidth * scaleFactor, aHeight * scaleFactor );
1364  isFramebufferInitialized = false;
1365 
1366  wxGLCanvas::SetSize( aWidth, aHeight );
1367 }
1368 
1369 
1370 bool OPENGL_GAL::Show( bool aShow )
1371 {
1372  bool s = wxGLCanvas::Show( aShow );
1373 
1374  if( aShow )
1375  wxGLCanvas::Raise();
1376 
1377  return s;
1378 }
1379 
1380 
1382 {
1383  glFlush();
1384 }
1385 
1386 
1388 {
1389  // Clear screen
1391  // NOTE: Black used here instead of m_clearColor; it will be composited later
1392  glClearColor( 0, 0, 0, 1 );
1393  glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );
1394 }
1395 
1396 
1397 void OPENGL_GAL::Transform( const MATRIX3x3D& aTransformation )
1398 {
1399  GLdouble matrixData[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
1400 
1401  matrixData[0] = aTransformation.m_data[0][0];
1402  matrixData[1] = aTransformation.m_data[1][0];
1403  matrixData[2] = aTransformation.m_data[2][0];
1404  matrixData[4] = aTransformation.m_data[0][1];
1405  matrixData[5] = aTransformation.m_data[1][1];
1406  matrixData[6] = aTransformation.m_data[2][1];
1407  matrixData[12] = aTransformation.m_data[0][2];
1408  matrixData[13] = aTransformation.m_data[1][2];
1409  matrixData[14] = aTransformation.m_data[2][2];
1410 
1411  glMultMatrixd( matrixData );
1412 }
1413 
1414 
1415 void OPENGL_GAL::Rotate( double aAngle )
1416 {
1417  currentManager->Rotate( aAngle, 0.0f, 0.0f, 1.0f );
1418 }
1419 
1420 
1421 void OPENGL_GAL::Translate( const VECTOR2D& aVector )
1422 {
1423  currentManager->Translate( aVector.x, aVector.y, 0.0f );
1424 }
1425 
1426 
1427 void OPENGL_GAL::Scale( const VECTOR2D& aScale )
1428 {
1429  currentManager->Scale( aScale.x, aScale.y, 0.0f );
1430 }
1431 
1432 
1434 {
1436 }
1437 
1438 
1440 {
1442 }
1443 
1444 
1446 {
1447  isGrouping = true;
1448 
1449  std::shared_ptr<VERTEX_ITEM> newItem = std::make_shared<VERTEX_ITEM>( *cachedManager );
1450  int groupNumber = getNewGroupNumber();
1451  groups.insert( std::make_pair( groupNumber, newItem ) );
1452 
1453  return groupNumber;
1454 }
1455 
1456 
1458 {
1460  isGrouping = false;
1461 }
1462 
1463 
1464 void OPENGL_GAL::DrawGroup( int aGroupNumber )
1465 {
1466  if( groups[aGroupNumber] )
1467  cachedManager->DrawItem( *groups[aGroupNumber] );
1468 }
1469 
1470 
1471 void OPENGL_GAL::ChangeGroupColor( int aGroupNumber, const COLOR4D& aNewColor )
1472 {
1473  if( groups[aGroupNumber] )
1474  cachedManager->ChangeItemColor( *groups[aGroupNumber], aNewColor );
1475 }
1476 
1477 
1478 void OPENGL_GAL::ChangeGroupDepth( int aGroupNumber, int aDepth )
1479 {
1480  if( groups[aGroupNumber] )
1481  cachedManager->ChangeItemDepth( *groups[aGroupNumber], aDepth );
1482 }
1483 
1484 
1485 void OPENGL_GAL::DeleteGroup( int aGroupNumber )
1486 {
1487  // Frees memory in the container as well
1488  groups.erase( aGroupNumber );
1489 }
1490 
1491 
1493 {
1494  bitmapCache.reset( new GL_BITMAP_CACHE );
1495 
1496  groups.clear();
1497 
1498  if( isInitialized )
1499  cachedManager->Clear();
1500 }
1501 
1502 
1504 {
1505  wxASSERT_MSG( false, wxT( "Not implemented yet" ) );
1506 }
1507 
1508 
1510 {
1511  wxASSERT_MSG( false, wxT( "Not implemented yet" ) );
1512 }
1513 
1514 
1516 {
1517  switch( aTarget )
1518  {
1519  default:
1520  case TARGET_CACHED:
1522  break;
1523 
1524  case TARGET_NONCACHED:
1526  break;
1527 
1528  case TARGET_OVERLAY:
1530  break;
1531  }
1532 
1533  currentTarget = aTarget;
1534 }
1535 
1536 
1538 {
1539  return currentTarget;
1540 }
1541 
1542 
1544 {
1545  // Save the current state
1546  unsigned int oldTarget = compositor->GetBuffer();
1547 
1548  switch( aTarget )
1549  {
1550  // Cached and noncached items are rendered to the same buffer
1551  default:
1552  case TARGET_CACHED:
1553  case TARGET_NONCACHED:
1555  break;
1556 
1557  case TARGET_OVERLAY:
1559  break;
1560  }
1561 
1562 
1563  if( aTarget != TARGET_OVERLAY )
1565  else
1567 
1568  // Restore the previous state
1569  compositor->SetBuffer( oldTarget );
1570 }
1571 
1572 
1573 void OPENGL_GAL::DrawCursor( const VECTOR2D& aCursorPosition )
1574 {
1575  // Now we should only store the position of the mouse cursor
1576  // The real drawing routines are in blitCursor()
1577  //VECTOR2D screenCursor = worldScreenMatrix * aCursorPosition;
1578  //cursorPosition = screenWorldMatrix * VECTOR2D( screenCursor.x, screenCursor.y );
1579  cursorPosition = aCursorPosition;
1580 }
1581 
1582 
1583 void OPENGL_GAL::drawLineQuad( const VECTOR2D& aStartPoint, const VECTOR2D& aEndPoint )
1584 {
1585  /* Helper drawing: ____--- v3 ^
1586  * ____---- ... \ \
1587  * ____---- ... \ end \
1588  * v1 ____---- ... ____---- \ width
1589  * ---- ...___---- \ \
1590  * \ ___...-- \ v
1591  * \ ____----... ____---- v2
1592  * ---- ... ____----
1593  * start \ ... ____----
1594  * \... ____----
1595  * ----
1596  * v0
1597  * dots mark triangles' hypotenuses
1598  */
1599 
1600  auto v1 = currentManager->GetTransformation() * glm::vec4( aStartPoint.x, aStartPoint.y, 0.0, 0.0 );
1601  auto v2 = currentManager->GetTransformation() * glm::vec4( aEndPoint.x, aEndPoint.y, 0.0, 0.0 );
1602 
1603  VECTOR2D startEndVector( v2.x - v1.x, v2.y - v1.y );
1604 
1605  double lineLength = startEndVector.EuclideanNorm();
1606 
1607  VECTOR2D vs ( startEndVector );
1608  float aspect;
1609 
1610  if ( lineWidth == 0.0 ) // pixel-width line
1611  {
1612  vs = vs.Resize( 0.5 );
1613  aspect = ( lineLength + 1.0 );
1614  }
1615  else
1616  {
1617  vs = vs.Resize( 0.5 * lineWidth );
1618  aspect = ( lineLength + lineWidth ) / lineWidth;
1619  }
1620 
1621  currentManager->Reserve( 6 );
1622 
1623  // Line width is maintained by the vertex shader
1624  currentManager->Shader( SHADER_LINE_A, aspect, vs.x, vs.y );
1625  currentManager->Vertex( aStartPoint, layerDepth );
1626 
1627  currentManager->Shader( SHADER_LINE_B, aspect, vs.x, vs.y );
1628  currentManager->Vertex( aStartPoint, layerDepth );
1629 
1630  currentManager->Shader( SHADER_LINE_C, aspect, vs.x, vs.y );
1631  currentManager->Vertex( aEndPoint, layerDepth );
1632 
1633  currentManager->Shader( SHADER_LINE_D, aspect, vs.x, vs.y );
1634  currentManager->Vertex( aEndPoint, layerDepth );
1635 
1636  currentManager->Shader( SHADER_LINE_E, aspect, vs.x, vs.y );
1637  currentManager->Vertex( aEndPoint, layerDepth );
1638 
1639  currentManager->Shader( SHADER_LINE_F, aspect, vs.x, vs.y );
1640  currentManager->Vertex( aStartPoint, layerDepth );
1641 }
1642 
1643 
1644 void OPENGL_GAL::drawSemiCircle( const VECTOR2D& aCenterPoint, double aRadius, double aAngle )
1645 {
1646  if( isFillEnabled )
1647  {
1649  drawFilledSemiCircle( aCenterPoint, aRadius, aAngle );
1650  }
1651 
1652  if( isStrokeEnabled )
1653  {
1655  drawStrokedSemiCircle( aCenterPoint, aRadius, aAngle );
1656  }
1657 }
1658 
1659 
1660 void OPENGL_GAL::drawFilledSemiCircle( const VECTOR2D& aCenterPoint, double aRadius,
1661  double aAngle )
1662 {
1663  Save();
1664 
1665  currentManager->Reserve( 3 );
1666  currentManager->Translate( aCenterPoint.x, aCenterPoint.y, 0.0f );
1667  currentManager->Rotate( aAngle, 0.0f, 0.0f, 1.0f );
1668 
1669  /* Draw a triangle that contains the semicircle, then shade it to leave only
1670  * the semicircle. Parameters given to Shader() are indices of the triangle's vertices
1671  * (if you want to understand more, check the vertex shader source [shader.vert]).
1672  * Shader uses these coordinates to determine if fragments are inside the semicircle or not.
1673  * v2
1674  * /\
1675  * /__\
1676  * v0 //__\\ v1
1677  */
1679  currentManager->Vertex( -aRadius * 3.0f / sqrt( 3.0f ), 0.0f, layerDepth ); // v0
1680 
1682  currentManager->Vertex( aRadius * 3.0f / sqrt( 3.0f ), 0.0f, layerDepth ); // v1
1683 
1685  currentManager->Vertex( 0.0f, aRadius * 2.0f, layerDepth ); // v2
1686 
1687  Restore();
1688 }
1689 
1690 
1691 void OPENGL_GAL::drawStrokedSemiCircle( const VECTOR2D& aCenterPoint, double aRadius,
1692  double aAngle )
1693 {
1694  double outerRadius = aRadius + ( lineWidth / 2 );
1695 
1696  Save();
1697 
1698  currentManager->Reserve( 3 );
1699  currentManager->Translate( aCenterPoint.x, aCenterPoint.y, 0.0f );
1700  currentManager->Rotate( aAngle, 0.0f, 0.0f, 1.0f );
1701 
1702  /* Draw a triangle that contains the semicircle, then shade it to leave only
1703  * the semicircle. Parameters given to Shader() are indices of the triangle's vertices
1704  * (if you want to understand more, check the vertex shader source [shader.vert]), the
1705  * radius and the line width. Shader uses these coordinates to determine if fragments are
1706  * inside the semicircle or not.
1707  * v2
1708  * /\
1709  * /__\
1710  * v0 //__\\ v1
1711  */
1713  currentManager->Vertex( -outerRadius * 3.0f / sqrt( 3.0f ), 0.0f, layerDepth ); // v0
1714 
1716  currentManager->Vertex( outerRadius * 3.0f / sqrt( 3.0f ), 0.0f, layerDepth ); // v1
1717 
1719  currentManager->Vertex( 0.0f, outerRadius * 2.0f, layerDepth ); // v2
1720 
1721  Restore();
1722 }
1723 
1724 
1725 void OPENGL_GAL::drawPolygon( GLdouble* aPoints, int aPointCount )
1726 {
1727  if( isFillEnabled )
1728  {
1731 
1732  // Any non convex polygon needs to be tesselated
1733  // for this purpose the GLU standard functions are used
1735  gluTessBeginPolygon( tesselator, &params );
1736  gluTessBeginContour( tesselator );
1737 
1738  GLdouble* point = aPoints;
1739 
1740  for( int i = 0; i < aPointCount; ++i )
1741  {
1742  gluTessVertex( tesselator, point, point );
1743  point += 3; // 3 coordinates
1744  }
1745 
1746  gluTessEndContour( tesselator );
1747  gluTessEndPolygon( tesselator );
1748 
1749  // Free allocated intersecting points
1750  tessIntersects.clear();
1751  }
1752 
1753  if( isStrokeEnabled )
1754  {
1755  drawPolyline( [&](int idx) { return VECTOR2D( aPoints[idx * 3], aPoints[idx * 3 + 1] ); },
1756  aPointCount );
1757  }
1758 }
1759 
1760 
1761 void OPENGL_GAL::drawPolyline( const std::function<VECTOR2D (int)>& aPointGetter, int aPointCount )
1762 {
1763  if( aPointCount < 2 )
1764  return;
1765 
1767  int i;
1768 
1769  for( i = 1; i < aPointCount; ++i )
1770  {
1771  auto start = aPointGetter( i - 1 );
1772  auto end = aPointGetter( i );
1773  const VECTOR2D startEndVector = ( end - start );
1774  double lineAngle = startEndVector.Angle();
1775 
1776  drawLineQuad( start, end );
1777 
1778  // There is no need to draw line caps on both ends of polyline's segments
1779  drawFilledSemiCircle( start, lineWidth / 2, lineAngle + M_PI / 2 );
1780  }
1781 
1782  // ..and now - draw the ending cap
1783  auto start = aPointGetter( i - 2 );
1784  auto end = aPointGetter( i - 1 );
1785  const VECTOR2D startEndVector = ( end - start );
1786  double lineAngle = startEndVector.Angle();
1787  drawFilledSemiCircle( end, lineWidth / 2, lineAngle - M_PI / 2 );
1788 }
1789 
1790 
1791 int OPENGL_GAL::drawBitmapChar( unsigned long aChar )
1792 {
1793  const float TEX_X = font_image.width;
1794  const float TEX_Y = font_image.height;
1795 
1796  // handle space
1797  if( aChar == ' ' )
1798  {
1799  const FONT_GLYPH_TYPE* g = LookupGlyph( 'x' );
1800  wxASSERT( g );
1801  Translate( VECTOR2D( g->advance, 0 ) );
1802  return g->advance;
1803  }
1804 
1805  const FONT_GLYPH_TYPE* glyph = LookupGlyph( aChar );
1806 
1807  // If the glyph is not found (happens for many esotheric unicode chars)
1808  // shows a '?' instead.
1809  if( !glyph )
1810  glyph = LookupGlyph( '?' );
1811 
1812  if( !glyph ) // Should not happen.
1813  return 0;
1814 
1815  const float X = glyph->atlas_x + font_information.smooth_pixels;
1816  const float Y = glyph->atlas_y + font_information.smooth_pixels;
1817  const float XOFF = glyph->minx;
1818 
1819  // adjust for height rounding
1820  const float round_adjust = ( glyph->maxy - glyph->miny )
1821  - float( glyph->atlas_h - font_information.smooth_pixels * 2 );
1822  const float top_adjust = font_information.max_y - glyph->maxy;
1823  const float YOFF = round_adjust + top_adjust;
1824  const float W = glyph->atlas_w - font_information.smooth_pixels *2;
1825  const float H = glyph->atlas_h - font_information.smooth_pixels *2;
1826  const float B = 0;
1827 
1828  currentManager->Reserve( 6 );
1829  Translate( VECTOR2D( XOFF, YOFF ) );
1830  /* Glyph:
1831  * v0 v1
1832  * +--+
1833  * | /|
1834  * |/ |
1835  * +--+
1836  * v2 v3
1837  */
1838  currentManager->Shader( SHADER_FONT, X / TEX_X, ( Y + H ) / TEX_Y );
1839  currentManager->Vertex( -B, -B, 0 ); // v0
1840 
1841  currentManager->Shader( SHADER_FONT, ( X + W ) / TEX_X, ( Y + H ) / TEX_Y );
1842  currentManager->Vertex( W + B, -B, 0 ); // v1
1843 
1844  currentManager->Shader( SHADER_FONT, X / TEX_X, Y / TEX_Y );
1845  currentManager->Vertex( -B, H + B, 0 ); // v2
1846 
1847 
1848  currentManager->Shader( SHADER_FONT, ( X + W ) / TEX_X, ( Y + H ) / TEX_Y );
1849  currentManager->Vertex( W + B, -B, 0 ); // v1
1850 
1851  currentManager->Shader( SHADER_FONT, X / TEX_X, Y / TEX_Y );
1852  currentManager->Vertex( -B, H + B, 0 ); // v2
1853 
1854  currentManager->Shader( SHADER_FONT, ( X + W ) / TEX_X, Y / TEX_Y );
1855  currentManager->Vertex( W + B, H + B, 0 ); // v3
1856 
1857  Translate( VECTOR2D( -XOFF + glyph->advance, -YOFF ) );
1858 
1859  return glyph->advance;
1860 }
1861 
1862 
1863 void OPENGL_GAL::drawBitmapOverbar( double aLength, double aHeight )
1864 {
1865  // To draw an overbar, simply draw an overbar
1866  const FONT_GLYPH_TYPE* glyph = LookupGlyph( '_' );
1867  wxCHECK( glyph, /* void */ );
1868 
1869  const float H = glyph->maxy - glyph->miny;
1870 
1871  Save();
1872 
1873  Translate( VECTOR2D( -aLength, -aHeight-1.5*H ) );
1874 
1875  currentManager->Reserve( 6 );
1877 
1878  currentManager->Shader( 0 );
1879 
1880  currentManager->Vertex( 0, 0, 0 ); // v0
1881  currentManager->Vertex( aLength, 0, 0 ); // v1
1882  currentManager->Vertex( 0, H, 0 ); // v2
1883 
1884  currentManager->Vertex( aLength, 0, 0 ); // v1
1885  currentManager->Vertex( 0, H, 0 ); // v2
1886  currentManager->Vertex( aLength, H, 0 ); // v3
1887 
1888  Restore();
1889 }
1890 
1891 
1892 std::pair<VECTOR2D, float> OPENGL_GAL::computeBitmapTextSize( const UTF8& aText ) const
1893 {
1894  VECTOR2D textSize( 0, 0 );
1895  float commonOffset = std::numeric_limits<float>::max();
1896  static const auto defaultGlyph = LookupGlyph( '(' ); // for strange chars
1897 
1898  for( UTF8::uni_iter chIt = aText.ubegin(), end = aText.uend(); chIt < end; ++chIt )
1899  {
1900  unsigned int c = *chIt;
1901 
1902  const FONT_GLYPH_TYPE* glyph = LookupGlyph( c );
1903  // Debug: show not coded char in the atlas
1904  // Be carefull before allowing the assert: it usually crash kicad
1905  // when the assert is made during a paint event.
1906  // wxASSERT_MSG( glyph, wxString::Format( "missing char in font: code 0x%x <%c>", c, c ) );
1907 
1908  if( !glyph || // Not coded in font
1909  c == '-' || c == '_' ) // Strange size of these 2 chars
1910  {
1911  glyph = defaultGlyph;
1912  }
1913 
1914  if( glyph )
1915  {
1916  textSize.x += glyph->advance;
1917  }
1918  }
1919 
1920  textSize.y = std::max<float>( textSize.y, font_information.max_y - defaultGlyph->miny );
1921  commonOffset = std::min<float>( font_information.max_y - defaultGlyph->maxy, commonOffset );
1922  textSize.y -= commonOffset;
1923 
1924  return std::make_pair( textSize, commonOffset );
1925 }
1926 
1927 
1928 void OPENGL_GAL::onPaint( wxPaintEvent& WXUNUSED( aEvent ) )
1929 {
1930  PostPaint();
1931 }
1932 
1933 
1934 void OPENGL_GAL::skipMouseEvent( wxMouseEvent& aEvent )
1935 {
1936  // Post the mouse event to the event listener registered in constructor, if any
1937  if( mouseListener )
1938  wxPostEvent( mouseListener, aEvent );
1939 }
1940 
1941 
1943 {
1944  if( !IsCursorEnabled() )
1945  return;
1946 
1948 
1949  const int cursorSize = fullscreenCursor ? 8000 : 80;
1950 
1951  VECTOR2D cursorBegin = cursorPosition - cursorSize / ( 2 * worldScale );
1952  VECTOR2D cursorEnd = cursorPosition + cursorSize / ( 2 * worldScale );
1953  VECTOR2D cursorCenter = ( cursorBegin + cursorEnd ) / 2;
1954 
1955  const COLOR4D cColor = getCursorColor();
1956  const COLOR4D color( cColor.r * cColor.a, cColor.g * cColor.a,
1957  cColor.b * cColor.a, 1.0 );
1958 
1959  glActiveTexture( GL_TEXTURE0 );
1960  glDisable( GL_TEXTURE_2D );
1961  glLineWidth( 1.0 );
1962  glColor4d( color.r, color.g, color.b, color.a );
1963 
1964  glBegin( GL_LINES );
1965  glVertex2d( cursorCenter.x, cursorBegin.y );
1966  glVertex2d( cursorCenter.x, cursorEnd.y );
1967 
1968  glVertex2d( cursorBegin.x, cursorCenter.y );
1969  glVertex2d( cursorEnd.x, cursorCenter.y );
1970  glEnd();
1971 }
1972 
1973 
1975 {
1976  wxASSERT_MSG( groups.size() < std::numeric_limits<unsigned int>::max(),
1977  wxT( "There are no free slots to store a group" ) );
1978 
1979  while( groups.find( groupCounter ) != groups.end() )
1980  {
1981  groupCounter++;
1982  }
1983 
1984  return groupCounter++;
1985 }
1986 
1987 
1989 {
1990  wxASSERT( IsShownOnScreen() );
1991 
1992  wxASSERT_MSG( isContextLocked, "This should only be called from within a locked context." );
1993 
1994  GLenum err = glewInit();
1995 
1996  if( GLEW_OK != err )
1997  throw std::runtime_error( (const char*) glewGetErrorString( err ) );
1998 
1999  // Check the OpenGL version (minimum 2.1 is required)
2000  if( !GLEW_VERSION_2_1 )
2001  throw std::runtime_error( "OpenGL 2.1 or higher is required!" );
2002 
2003 #if defined (__LINUX__) // calling enableGlDebug crashes opengl on some OS (OSX and some Windows)
2004 #ifdef DEBUG
2005  if( GLEW_ARB_debug_output )
2006  enableGlDebug( true );
2007 #endif
2008 #endif
2009 
2010  // Framebuffers have to be supported
2011  if( !GLEW_EXT_framebuffer_object )
2012  throw std::runtime_error( "Framebuffer objects are not supported!" );
2013 
2014  // Vertex buffer has to be supported
2015  if( !GLEW_ARB_vertex_buffer_object )
2016  throw std::runtime_error( "Vertex buffer objects are not supported!" );
2017 
2018  // Prepare shaders
2020  throw std::runtime_error( "Cannot compile vertex shader!" );
2021 
2023  throw std::runtime_error( "Cannot compile fragment shader!" );
2024 
2025  if( !shader->IsLinked() && !shader->Link() )
2026  throw std::runtime_error( "Cannot link the shaders!" );
2027 
2028  // Check if video card supports textures big enough to fit the font atlas
2029  int maxTextureSize;
2030  glGetIntegerv( GL_MAX_TEXTURE_SIZE, &maxTextureSize );
2031 
2032  if( maxTextureSize < (int) font_image.width || maxTextureSize < (int)font_image.height )
2033  {
2034  // TODO implement software texture scaling
2035  // for bitmap fonts and use a higher resolution texture?
2036  throw std::runtime_error( "Requested texture size is not supported" );
2037  }
2038 
2039  cachedManager = new VERTEX_MANAGER( true );
2040  nonCachedManager = new VERTEX_MANAGER( false );
2041  overlayManager = new VERTEX_MANAGER( false );
2042 
2043  // Make VBOs use shaders
2047 
2048  isInitialized = true;
2049 }
2050 
2051 
2052 // ------------------------------------- // Callback functions for the tesselator // ------------------------------------- // Compare Redbook Chapter 11
2053 void CALLBACK VertexCallback( GLvoid* aVertexPtr, void* aData )
2054 {
2055  GLdouble* vertex = static_cast<GLdouble*>( aVertexPtr );
2056  OPENGL_GAL::TessParams* param = static_cast<OPENGL_GAL::TessParams*>( aData );
2057  VERTEX_MANAGER* vboManager = param->vboManager;
2058 
2059  assert( vboManager );
2060  vboManager->Vertex( vertex[0], vertex[1], vertex[2] );
2061 }
2062 
2063 
2064 void CALLBACK CombineCallback( GLdouble coords[3],
2065  GLdouble* vertex_data[4],
2066  GLfloat weight[4], GLdouble** dataOut, void* aData )
2067 {
2068  GLdouble* vertex = new GLdouble[3];
2069  OPENGL_GAL::TessParams* param = static_cast<OPENGL_GAL::TessParams*>( aData );
2070 
2071  // Save the pointer so we can delete it later
2072  param->intersectPoints.push_back( boost::shared_array<GLdouble>( vertex ) );
2073 
2074  memcpy( vertex, coords, 3 * sizeof(GLdouble) );
2075 
2076  *dataOut = vertex;
2077 }
2078 
2079 
2080 void CALLBACK EdgeCallback( GLboolean aEdgeFlag )
2081 {
2082  // This callback is needed to force GLU tesselator to use triangles only
2083 }
2084 
2085 
2086 void CALLBACK ErrorCallback( GLenum aErrorCode )
2087 {
2088  //throw std::runtime_error( std::string( "Tessellation error: " ) +
2089  //std::string( (const char*) gluErrorString( aErrorCode ) );
2090 }
2091 
2092 
2093 static void InitTesselatorCallbacks( GLUtesselator* aTesselator )
2094 {
2095  gluTessCallback( aTesselator, GLU_TESS_VERTEX_DATA, ( void (CALLBACK*)() )VertexCallback );
2096  gluTessCallback( aTesselator, GLU_TESS_COMBINE_DATA, ( void (CALLBACK*)() )CombineCallback );
2097  gluTessCallback( aTesselator, GLU_TESS_EDGE_FLAG, ( void (CALLBACK*)() )EdgeCallback );
2098  gluTessCallback( aTesselator, GLU_TESS_ERROR, ( void (CALLBACK*)() )ErrorCallback );
2099 }
2100 
2101 void OPENGL_GAL::EnableDepthTest( bool aEnabled )
2102 {
2103  cachedManager->EnableDepthTest( aEnabled );
2104  nonCachedManager->EnableDepthTest( aEnabled );
2105  overlayManager->EnableDepthTest( aEnabled );
2106 }
Definition: colors.h:57
double computeMinGridSpacing() const
compute minimum grid spacing from the grid settings
bool IsCursorEnabled() const
Returns information about cursor visibility.
void Stop()
save the time when this function was called, and set the counter stane to stop
Definition: profile.h:82
int gridTick
Every tick line gets the double width.
virtual void SetFillColor(const COLOR4D &aColor)
Set the fill color.
Class UTF8 is an 8 bit string that is assuredly encoded in UTF8, and supplies special conversion supp...
Definition: utf8.h:73
double getWorldPixelSize() const
Definition: opengl_gal.cpp:330
VERTEX_MANAGER * currentManager
Currently used VERTEX_MANAGER (for storing VERTEX_ITEMs)
Definition: opengl_gal.h:298
EDA_TEXT_HJUSTIFY_T GetHorizontalJustify() const
Returns current text horizontal justification setting.
virtual void beginUpdate() override
Definition: opengl_gal.cpp:531
VECTOR2D cursorPosition
Current cursor position (world coordinates)
static SHADER * shader
There is only one shader used for different objects.
Definition: opengl_gal.h:310
bool axesEnabled
Should the axes be drawn.
virtual void DrawBitmap(const BITMAP_BASE &aBitmap) override
Draw a bitmap image.
bool IsLinked() const
Returns true if shaders are linked correctly.
Definition: shader.h:122
EDA_TEXT_VJUSTIFY_T GetVerticalJustify() const
Returns current text vertical justification setting.
virtual void DrawBuffer(unsigned int aBufferHandle) override
Function DrawBuffer() draws the selected buffer to the output buffer.
static wxGLContext * glMainContext
Parent OpenGL context.
Definition: opengl_gal.h:286
void Clear() const
Function Clear() removes all the stored vertices from the container.
double calcAngleStep(double aRadius) const
Compute the angle step when drawing arcs/circles approximated with lines.
Definition: opengl_gal.h:469
std::pair< UTF8, std::vector< bool > > ProcessOverbars(const UTF8 &aText)
Processes a text to extract the raw text and overbar flags.
Definition: text_utils.cpp:27
double layerDepth
The actual layer depth.
void ChangeItemDepth(const VERTEX_ITEM &aItem, GLfloat aDepth) const
Function ChangeItemDepth() changes the depth of all vertices owned by an item.
Class CAIRO_GAL is the cairo implementation of the graphics abstraction layer.
Definition: class_module.h:58
static int KiROUND(double v)
Round a floating point number to an integer using "round halfway cases away from zero".
Definition: common.h:120
void PushMatrix()
Function PushMatrix() pushes the current transformation matrix stack.
unsigned int overlayBuffer
Auxiliary rendering target (for menus etc.)
Definition: opengl_gal.h:306
std::deque< boost::shared_array< GLdouble > > & intersectPoints
Intersect points, that have to be freed after tessellation.
Definition: opengl_gal.h:276
virtual void Scale(const VECTOR2D &aScale) override
Scale the context.
virtual void ClearTarget(RENDER_TARGET aTarget) override
Clears the target for rendering.
virtual void Translate(const VECTOR2D &aTranslation) override
Translate the context.
virtual void Begin() override
Function Begin() Call this at the beginning of each frame.
bool Reserve(unsigned int aSize)
Function Reserve() allocates space for vertices, so it will be used with subsequent Vertex() calls...
VECTOR2< T > Resize(T aNewLength) const
Function Resize returns a vector of the same direction, but length specified in aNewLength.
Definition: vector2d.h:385
RENDER_TARGET currentTarget
Current rendering target.
Definition: opengl_gal.h:307
int PointCount() const
Function PointCount()
bool isBitmapFontInitialized
Is the shader set to use bitmap fonts?
Definition: opengl_gal.h:315
void Use()
Use the shader.
Definition: shader.h:130
void drawPolygon(GLdouble *aPoints, int aPointCount)
Draws a filled polygon.
void SetParameter(int aParameterNumber, float aValue) const
Set a parameter of the shader.
Definition: shader.cpp:138
static GLuint fontTexture
Bitmap font texture handle (shared)
Definition: opengl_gal.h:292
GRID_STYLE gridStyle
Grid display style.
bool LoadShaderFromStrings(SHADER_TYPE aShaderType, Args &&...aArgs)
Add a shader and compile the shader sources.
Definition: shader.h:97
void drawLineQuad(const VECTOR2D &aStartPoint, const VECTOR2D &aEndPoint)
Draw a quad for the line.
VERTEX_MANAGER * overlayManager
Container for storing overlaid VERTEX_ITEMs.
Definition: opengl_gal.h:301
GAL_DISPLAY_OPTIONS & options
int color
Definition: DXF_plotter.cpp:62
virtual void Restore() override
Restore the context.
void CALLBACK EdgeCallback(GLboolean aEdgeFlag)
virtual void ChangeGroupDepth(int aGroupNumber, int aDepth) override
Changes the depth (Z-axis position) of the group.
const MATRIX3x3D & GetScreenWorldMatrix() const
Get the screen <-> world transformation matrix.
std::unique_ptr< GL_BITMAP_CACHE > bitmapCache
Definition: opengl_gal.h:323
virtual void EnableDepthTest(bool aEnabled=false) override
Parameters passed to the GLU tesselator.
bool Vertex(const VERTEX &aVertex)
Function Vertex() adds a vertex with the given coordinates to the currently set item.
static const COLOR4D BLACK
Definition: color4d.h:297
wxGLCanvas wrapper for HiDPI/Retina support.
virtual int BeginGroup() override
Begin a group.
static void InitTesselatorCallbacks(GLUtesselator *aTesselator)
virtual void DrawPolygon(const std::deque< VECTOR2D > &aPointList) override
Draw a polygon.
Definition: opengl_gal.cpp:892
void Rotate(GLfloat aAngle, GLfloat aX, GLfloat aY, GLfloat aZ)
Function Rotate() multiplies the current matrix by a rotation matrix, so the newly vertices will be r...
bool isContextLocked
Used for assertion checking.
Definition: opengl_gal.h:319
double g
Green component.
Definition: color4d.h:288
Fragment shader.
Definition: shader.h:45
bool Link()
Link the shaders.
Definition: shader.cpp:97
COLOR4D fillColor
The fill color.
VECTOR2D depthRange
Range of the depth.
bool IsTriangulationUpToDate() const
int checkGlError(const std::string &aInfo, bool aThrow)
Checks if one of recent OpenGL operations has failed.
Definition: utils.cpp:30
int OutlineCount() const
Returns the number of outlines in the set
MATRIX3x3D screenWorldMatrix
Screen transformation.
bool globalFlipX
Flag for X axis flipping.
const FONT_GLYPH_TYPE * LookupGlyph(unsigned int aCodepoint)
VECTOR2< int > VECTOR2I
Definition: vector2d.h:587
static const unsigned int DIRECT_RENDERING
bool isGrouping
Was a group started?
Definition: opengl_gal.h:318
virtual void ComputeWorldScreenMatrix()
Compute the world <-> screen transformation matrix.
The class PROF_COUNTER is a small class to help profiling.
Definition: profile.h:45
OPENGL_ANTIALIASING_MODE gl_antialiasing_mode
#define abs(a)
Definition: auxiliary.h:84
void UnlockCtx(wxGLContext *aContext)
Function UnlockCtx allows other canvases to bind an OpenGL context.
void enableGlDebug(bool aEnable)
Enables/disables OpenGL driver messages output.
Definition: utils.cpp:140
virtual void ResizeScreen(int aWidth, int aHeight) override
Resizes the canvas.
void unlockContext(int aClientCookie) override
Definition: opengl_gal.cpp:517
void CALLBACK VertexCallback(GLvoid *aVertexPtr, void *aData)
virtual void Transform(const MATRIX3x3D &aTransformation) override
Transform the context.
uni_iter ubegin() const
Function ubegin returns a uni_iter initialized to the start of "this" UTF8 byte sequence.
Definition: utf8.h:285
virtual void SetLineWidth(float aLineWidth)
Set the line width.
VERTEX_MANAGER * nonCachedManager
Container for storing non-cached VERTEX_ITEMs.
Definition: opengl_gal.h:300
double b
Blue component.
Definition: color4d.h:289
Auxiliary rendering target (noncached)
Definition: definitions.h:42
static int instanceCounter
GL GAL instance counter.
Definition: opengl_gal.h:288
This file contains miscellaneous commonly used macros and functions.
VERTEX_MANAGER * vboManager
Manager used for storing new vertices.
Definition: opengl_gal.h:273
T m_data[3][3]
Definition: matrix3x3.h:64
void SetAntialiasingMode(OPENGL_ANTIALIASING_MODE aMode)
virtual void DrawArcSegment(const VECTOR2D &aCenterPoint, double aRadius, double aStartAngle, double aEndAngle, double aWidth) override
Draw an arc segment.
Definition: opengl_gal.cpp:735
virtual RENDER_TARGET GetTarget() const override
Gets the currently used target for rendering.
static const int CURVE_POINTS
The number of points for curve approximation.
Definition: opengl_gal.h:284
This class handle bitmap images in KiCad.
Definition: bitmap_base.h:46
virtual void endUpdate() override
Definition: opengl_gal.cpp:547
static GL_CONTEXT_MANAGER & Get()
Function Get returns the GL_CONTEXT_MANAGER instance (singleton).
double Angle() const
Function Angle computes the angle of the vector.
Definition: vector2d.h:306
void SetGridColor(const COLOR4D &aGridColor)
Set the grid color.
virtual void Save() override
Save the context.
void init()
Basic OpenGL initialization.
double a
Alpha component.
Definition: color4d.h:290
void Unmap()
Function Unmap() unmaps vertex buffer.
OPENGL_COMPOSITOR * compositor
Handles multiple rendering targets.
Definition: opengl_gal.h:304
bool fullscreenCursor
Shape of the cursor (fullscreen or small cross)
T EuclideanNorm() const
Destructor.
Definition: vector2d.h:292
bool isStrokeEnabled
Are the outlines stroked ?
VECTOR2< double > VECTOR2D
Definition: vector2d.h:586
COLOR4D getCursorColor() const
Gets the actual cursor color to draw.
void Refresh()
Update the board display after modifying it by a python script (note: it is automatically called by a...
GROUPS_MAP groups
Stores informations about VBO objects (groups)
Definition: opengl_gal.h:296
virtual void Present() override
Function Present() Call this to present the output buffer to the screen.
std::pair< VECTOR2D, float > computeBitmapTextSize(const UTF8 &aText) const
Computes a size of text drawn using bitmap font with current text setting applied.
virtual void RestoreScreen() override
Restore the screen contents.
unsigned int mainBuffer
Main rendering target.
Definition: opengl_gal.h:305
virtual bool Show(bool aShow) override
Shows/hides the GAL canvas.
virtual void ClearBuffer(const COLOR4D &aColor) override
Function ClearBuffer() clears the selected buffer (set by the SetBuffer() function).
Class SHAPE_POLY_SET.
virtual void EndGroup() override
End the group.
COLOR4D axesColor
Color of the axes.
virtual void DeleteGroup(int aGroupNumber) override
Delete the group from the memory.
wxEvtHandler * mouseListener
Definition: opengl_gal.h:289
void SetAxesColor(const COLOR4D &aAxesColor)
Set the axes color.
void EndDrawing() const
Function EndDrawing() finishes drawing operations.
bool updatedGalDisplayOptions(const GAL_DISPLAY_OPTIONS &aOptions) override
Function updatedGalDisplayOptions.
Definition: opengl_gal.cpp:310
virtual void DrawGrid() override
>
COLOR4D strokeColor
The color of the outlines.
float gridLineWidth
Line width of the grid.
void Translate(GLfloat aX, GLfloat aY, GLfloat aZ)
Function Translate() multiplies the current matrix by a translation matrix, so newly vertices will be...
static const int glAttributes[]
Definition: opengl_gal.cpp:59
virtual void DrawLine(const VECTOR2D &aStartPoint, const VECTOR2D &aEndPoint) override
Draw a line.
Definition: opengl_gal.cpp:556
double worldUnitLength
The unit length of the world coordinates [inch].
const TRIANGULATED_POLYGON * TriangulatedPolygon(int aIndex) const
Items that may change while the view stays the same (noncached)
Definition: definitions.h:43
void Map()
Function Map() maps vertex buffer.
void onPaint(wxPaintEvent &aEvent)
This is the OnPaint event handler.
int AddParameter(const std::string &aParameterName)
Add a parameter to the parameter queue.
Definition: shader.cpp:125
const SHAPE_LINE_CHAIN & COutline(int aIndex) const
virtual void endDrawing() override
Definition: opengl_gal.cpp:472
const VECTOR2D & GetGlyphSize() const
virtual void DrawGroup(int aGroupNumber) override
Draw the stored group.
void Deactivate()
Deactivate the shader and use the default OpenGL program.
Definition: shader.h:139
bool isFramebufferInitialized
Are the framebuffers initialized?
Definition: opengl_gal.h:313
virtual void Resize(unsigned int aWidth, unsigned int aHeight) override
Function Resize() clears the state of COMPOSITOR, so it has to be reinitialized again with the new di...
VECTOR2D gridOrigin
The grid origin.
wxSize GetSizePixels() const
Function GetSizePixels.
Definition: bitmap_base.h:133
virtual void ClearCache() override
Delete all data created during caching of graphic items.
FONT_IMAGE_TYPE font_image
Definition: gl_resources.cpp:4
unsigned char pixels[1024 *1024 *3]
Definition: gl_resources.h:38
void drawTriangulatedPolyset(const SHAPE_POLY_SET &aPoly)
Draws a set of polygons with a cached triangulation.
Definition: opengl_gal.cpp:926
OPENGL_ANTIALIASING_MODE GetAntialiasingMode() const
FONT_INFO_TYPE font_information
Definition: gl_resources.cpp:3
MATRIX3x3D worldScreenMatrix
World transformation.
Vertex shader.
Definition: shader.h:44
virtual void SetBuffer(unsigned int aBufferHandle) override
Function SetBuffer() sets the selected buffer as the rendering target.
Class SHADER provides the access to the OpenGL shaders.
Definition: shader.h:74
string & err
Definition: json11.cpp:598
void lockContext(int aClientCookie) override
Private: use GAL_CONTEXT_LOCKER RAII object.
Definition: opengl_gal.cpp:507
void BeginDrawing() const
Function BeginDrawing() prepares buffers and items to start drawing.
void Color(const COLOR4D &aColor)
Function Color() changes currently used color that will be applied to newly added vertices...
GLUtesselator * tesselator
The tessellator.
Definition: opengl_gal.h:346
Use dots for the grid.
Use small cross instead of dots for the grid.
std::map< const BITMAP_BASE *, CACHED_BITMAP > m_bitmaps
Definition: opengl_gal.cpp:89
virtual void Rotate(double aAngle) override
Rotate the context.
virtual bool updatedGalDisplayOptions(const GAL_DISPLAY_OPTIONS &aOptions)
Function updatedGalDisplayOptions.
void LockCtx(wxGLContext *aContext, wxGLCanvas *aCanvas)
Function LockCtx sets a context as current and prevents other canvases from switching it...
void drawStrokedSemiCircle(const VECTOR2D &aCenterPoint, double aRadius, double aAngle)
Draw a stroked semicircle.
#define H(x, y, z)
Definition: md5_hash.cpp:17
void PopMatrix()
Function PopMatrix() pops the current transformation matrix stack.
float lineWidth
The line width.
bool isFillEnabled
Is filling of graphic objects enabled ?
void blitCursor()
Blits cursor into the current screen.
VERTEX_MANAGER * cachedManager
Container for storing cached VERTEX_ITEMs.
Definition: opengl_gal.h:299
class uni_iter is a non-mutating iterator that walks through unicode code points in the UTF8 encoded ...
Definition: utf8.h:207
virtual void Initialize() override
Function Reset() performs primary initialiation, necessary to use the object.
virtual void DrawPolyline(const std::deque< VECTOR2D > &aPointList) override
Draw a polyline.
Definition: opengl_gal.cpp:869
virtual void DrawSegment(const VECTOR2D &aStartPoint, const VECTOR2D &aEndPoint, double aWidth) override
Draw a rounded segment.
Definition: opengl_gal.cpp:564
GLint ufm_worldPixelSize
Definition: opengl_gal.h:321
std::deque< boost::shared_array< GLdouble > > tessIntersects
Storage for intersecting points.
Definition: opengl_gal.h:348
virtual void DrawArc(const VECTOR2D &aCenterPoint, double aRadius, double aStartAngle, double aEndAngle) override
Draw an arc.
Definition: opengl_gal.cpp:669
void CALLBACK ErrorCallback(GLenum aErrorCode)
virtual void SaveScreen() override
Save the screen contents.
double msecs() const
Definition: profile.h:124
virtual void SetTarget(RENDER_TARGET aTarget) override
Sets the target for rendering.
virtual void SetStrokeColor(const COLOR4D &aColor)
Set the stroke color.
uni_iter uend() const
Function uend returns a uni_iter initialized to the end of "this" UTF8 byte sequence.
Definition: utf8.h:294
bool isInitialized
Basic initialization flag, has to be done when the window is visible.
Definition: opengl_gal.h:316
COLOR4D gridColor
Color of the grid.
const int scale
void ChangeItemColor(const VERTEX_ITEM &aItem, const COLOR4D &aColor) const
Function ChangeItemColor() changes the color of all vertices owned by an item.
int GetPPI() const
Definition: bitmap_base.h:145
void PostPaint()
Function PostPaint posts an event to m_paint_listener.
Definition: opengl_gal.h:248
bool gridVisibility
Should the grid be shown.
void drawSemiCircle(const VECTOR2D &aCenterPoint, double aRadius, double aAngle)
Draw a semicircle.
Main rendering target (cached)
Definition: definitions.h:41
void EnableDepthTest(bool aEnabled)
Function EnableDepthTest() Enables/disables Z buffer depth test.
unsigned int TriangulatedPolyCount() const
Returns the number of triangulated polygons
#define max(a, b)
Definition: auxiliary.h:86
bool globalFlipY
Flag for Y axis flipping.
Class SHAPE_LINE_CHAIN.
unsigned int groupCounter
Counter used for generating keys for groups.
Definition: opengl_gal.h:297
double worldScale
The scale factor world->screen.
int drawBitmapChar(unsigned long aChar)
Draws a single character using bitmap font.
void FinishItem() const
Function FinishItem() does the cleaning after adding an item.
VECTOR2D gridSize
The grid size.
virtual float GetBackingScaleFactor() const
size_t i
Definition: json11.cpp:597
const glm::mat4 & GetTransformation() const
void Scale(GLfloat aX, GLfloat aY, GLfloat aZ)
Function Scale() multiplies the current matrix by a scaling matrix, so the newly vertices will be sca...
virtual void ClearScreen() override
Clear the screen.
VECTOR2I screenSize
Screen size in screen coordinates.
#define SWAP(varA, condition, varB)
Swap the variables if a condition is met.
Definition: definitions.h:31
unsigned int getNewGroupNumber()
Returns a valid key that can be used as a new group number.
wxGLContext * glPrivContext
Canvas-specific OpenGL context.
Definition: opengl_gal.h:287
virtual void DrawRectangle(const VECTOR2D &aStartPoint, const VECTOR2D &aEndPoint) override
Draw a rectangle.
Definition: opengl_gal.cpp:831
virtual void Flush() override
Force all remaining objects to be drawn.
bool IsClosed() const
Function IsClosed()
virtual unsigned int GetBuffer() const override
Function GetBuffer() returns currently used buffer handle.
virtual void DrawCursor(const VECTOR2D &aCursorPosition) override
Draw the cursor.
virtual unsigned int CreateBuffer() override
Function CreateBuffer() prepares a new buffer that may be used as a rendering target.
void drawPolyline(const std::function< VECTOR2D(int)> &aPointGetter, int aPointCount)
Generic way of drawing a polyline stored in different containers.
void DestroyCtx(wxGLContext *aContext)
Function DestroyCtx destroys a managed OpenGL context.
void CALLBACK CombineCallback(GLdouble coords[3], GLdouble *vertex_data[4], GLfloat weight[4], GLdouble **dataOut, void *aData)
void Shader(GLfloat aShaderType, GLfloat aParam1=0.0f, GLfloat aParam2=0.0f, GLfloat aParam3=0.0f)
Function Shader() changes currently used shader and its parameters that will be applied to newly adde...
double r
Red component.
Definition: color4d.h:287
POLYGON & Polygon(int aIndex)
Returns the aIndex-th subpolygon in the set
RENDER_TARGET
RENDER_TARGET: Possible rendering targets.
Definition: definitions.h:39
wxGLContext * CreateCtx(wxGLCanvas *aCanvas, const wxGLContext *aOther=NULL)
Function CreateCtx creates a managed OpenGL context.
virtual void BitmapText(const wxString &aText, const VECTOR2D &aPosition, double aRotationAngle) override
Draws a text using a bitmap font.
bool IsTextMirrored() const
Returns true if text should displayed mirrored.
#define CALLBACK
Definition: opengl_gal.h:48
virtual ~OPENGL_GAL()
Definition: opengl_gal.cpp:265
bool IsVisible() const override
>
Definition: opengl_gal.h:97
void DrawItem(const VERTEX_ITEM &aItem) const
Function DrawItem() draws an item to the buffer.
const VECTOR2I & CPoint(int aIndex) const
Function CPoint()
virtual void beginDrawing() override
Definition: opengl_gal.cpp:336
virtual void DrawCircle(const VECTOR2D &aCenterPoint, double aRadius) override
Draw a circle using world coordinates.
Definition: opengl_gal.cpp:609
static bool isBitmapFontLoaded
Is the bitmap font texture loaded?
Definition: opengl_gal.h:314
int SegmentCount() const
Function SegmentCount()
virtual void DrawCurve(const VECTOR2D &startPoint, const VECTOR2D &controlPointA, const VECTOR2D &controlPointB, const VECTOR2D &endPoint) override
Draw a cubic bezier spline.
Definition: opengl_gal.cpp:995
void skipMouseEvent(wxMouseEvent &aEvent)
Skip the mouse event to the parent.
void drawFilledSemiCircle(const VECTOR2D &aCenterPoint, double aRadius, double aAngle)
Draw a filled semicircle.
virtual void ChangeGroupColor(int aGroupNumber, const COLOR4D &aNewColor) override
Changes the color used to draw the group.
#define min(a, b)
Definition: auxiliary.h:85
Class GAL is the abstract interface for drawing on a 2D-surface.
void SetShader(SHADER &aShader) const
Function SetShader() sets a shader program that is going to be used during rendering.
Class COLOR4D is the color representation with 4 components: red, green, blue, alpha.
Definition: color4d.h:39
void drawBitmapOverbar(double aLength, double aHeight)
Draws an overbar over the currently drawn text.