Geant4 Cross Reference

Cross-Referencing   Geant4
Geant4/visualization/OpenGL/src/G4OpenGLViewer.cc

Version: [ ReleaseNotes ] [ 1.0 ] [ 1.1 ] [ 2.0 ] [ 3.0 ] [ 3.1 ] [ 3.2 ] [ 4.0 ] [ 4.0.p1 ] [ 4.0.p2 ] [ 4.1 ] [ 4.1.p1 ] [ 5.0 ] [ 5.0.p1 ] [ 5.1 ] [ 5.1.p1 ] [ 5.2 ] [ 5.2.p1 ] [ 5.2.p2 ] [ 6.0 ] [ 6.0.p1 ] [ 6.1 ] [ 6.2 ] [ 6.2.p1 ] [ 6.2.p2 ] [ 7.0 ] [ 7.0.p1 ] [ 7.1 ] [ 7.1.p1 ] [ 8.0 ] [ 8.0.p1 ] [ 8.1 ] [ 8.1.p1 ] [ 8.1.p2 ] [ 8.2 ] [ 8.2.p1 ] [ 8.3 ] [ 8.3.p1 ] [ 8.3.p2 ] [ 9.0 ] [ 9.0.p1 ] [ 9.0.p2 ] [ 9.1 ] [ 9.1.p1 ] [ 9.1.p2 ] [ 9.1.p3 ] [ 9.2 ] [ 9.2.p1 ] [ 9.2.p2 ] [ 9.2.p3 ] [ 9.2.p4 ] [ 9.3 ] [ 9.3.p1 ] [ 9.3.p2 ] [ 9.4 ] [ 9.4.p1 ] [ 9.4.p2 ] [ 9.4.p3 ] [ 9.4.p4 ] [ 9.5 ] [ 9.5.p1 ] [ 9.5.p2 ] [ 9.6 ] [ 9.6.p1 ] [ 9.6.p2 ] [ 9.6.p3 ] [ 9.6.p4 ] [ 10.0 ] [ 10.0.p1 ] [ 10.0.p2 ] [ 10.0.p3 ] [ 10.0.p4 ] [ 10.1 ] [ 10.1.p1 ] [ 10.1.p2 ] [ 10.1.p3 ] [ 10.2 ] [ 10.2.p1 ] [ 10.2.p2 ] [ 10.2.p3 ] [ 10.3 ] [ 10.3.p1 ] [ 10.3.p2 ] [ 10.3.p3 ] [ 10.4 ] [ 10.4.p1 ] [ 10.4.p2 ] [ 10.4.p3 ] [ 10.5 ] [ 10.5.p1 ] [ 10.6 ] [ 10.6.p1 ] [ 10.6.p2 ] [ 10.6.p3 ] [ 10.7 ] [ 10.7.p1 ] [ 10.7.p2 ] [ 10.7.p3 ] [ 10.7.p4 ] [ 11.0 ] [ 11.0.p1 ] [ 11.0.p2 ] [ 11.0.p3, ] [ 11.0.p4 ] [ 11.1 ] [ 11.1.1 ] [ 11.1.2 ] [ 11.1.3 ] [ 11.2 ] [ 11.2.1 ] [ 11.2.2 ] [ 11.3.0 ]

Diff markup

Differences between /visualization/OpenGL/src/G4OpenGLViewer.cc (Version 11.3.0) and /visualization/OpenGL/src/G4OpenGLViewer.cc (Version 10.4.p2)


  1 //                                                  1 //
  2 // *******************************************      2 // ********************************************************************
  3 // * License and Disclaimer                         3 // * License and Disclaimer                                           *
  4 // *                                                4 // *                                                                  *
  5 // * The  Geant4 software  is  copyright of th      5 // * The  Geant4 software  is  copyright of the Copyright Holders  of *
  6 // * the Geant4 Collaboration.  It is provided      6 // * the Geant4 Collaboration.  It is provided  under  the terms  and *
  7 // * conditions of the Geant4 Software License      7 // * conditions of the Geant4 Software License,  included in the file *
  8 // * LICENSE and available at  http://cern.ch/      8 // * LICENSE and available at  http://cern.ch/geant4/license .  These *
  9 // * include a list of copyright holders.           9 // * include a list of copyright holders.                             *
 10 // *                                               10 // *                                                                  *
 11 // * Neither the authors of this software syst     11 // * Neither the authors of this software system, nor their employing *
 12 // * institutes,nor the agencies providing fin     12 // * institutes,nor the agencies providing financial support for this *
 13 // * work  make  any representation or  warran     13 // * work  make  any representation or  warranty, express or implied, *
 14 // * regarding  this  software system or assum     14 // * regarding  this  software system or assume any liability for its *
 15 // * use.  Please see the license in the file      15 // * use.  Please see the license in the file  LICENSE  and URL above *
 16 // * for the full disclaimer and the limitatio     16 // * for the full disclaimer and the limitation of liability.         *
 17 // *                                               17 // *                                                                  *
 18 // * This  code  implementation is the result      18 // * This  code  implementation is the result of  the  scientific and *
 19 // * technical work of the GEANT4 collaboratio     19 // * technical work of the GEANT4 collaboration.                      *
 20 // * By using,  copying,  modifying or  distri     20 // * By using,  copying,  modifying or  distributing the software (or *
 21 // * any work based  on the software)  you  ag     21 // * any work based  on the software)  you  agree  to acknowledge its *
 22 // * use  in  resulting  scientific  publicati     22 // * use  in  resulting  scientific  publications,  and indicate your *
 23 // * acceptance of all terms of the Geant4 Sof     23 // * acceptance of all terms of the Geant4 Software license.          *
 24 // *******************************************     24 // ********************************************************************
 25 //                                                 25 //
 26 //                                                 26 //
                                                   >>  27 // $Id: G4OpenGLViewer.cc 107329 2017-11-08 16:41:26Z gcosmo $
 27 //                                                 28 //
 28 //                                                 29 // 
 29 // Andrew Walkden  27th March 1996                 30 // Andrew Walkden  27th March 1996
 30 // OpenGL view - opens window, hard copy, etc.     31 // OpenGL view - opens window, hard copy, etc.
 31                                                    32 
                                                   >>  33 #ifdef G4VIS_BUILD_OPENGL_DRIVER
                                                   >>  34 
 32 #include "G4ios.hh"                                35 #include "G4ios.hh"
 33 #include <CLHEP/Units/SystemOfUnits.h>         <<  36 #include "G4SystemOfUnits.hh"
 34 #include "G4OpenGLViewer.hh"                       37 #include "G4OpenGLViewer.hh"
 35 #include "G4OpenGLSceneHandler.hh"                 38 #include "G4OpenGLSceneHandler.hh"
 36 #include "G4OpenGLTransform3D.hh"                  39 #include "G4OpenGLTransform3D.hh"
 37                                                <<  40 #include "G4OpenGL2PSAction.hh"
 38 #include "G4gl2ps.hh"                          << 
 39 #define GL2PS_TEXT_B  TOOLS_GL2PS_TEXT_B       << 
 40 #define GL2PS_TEXT_BL TOOLS_GL2PS_TEXT_BL      << 
 41 #define GL2PS_TEXT_BR TOOLS_GL2PS_TEXT_BR      << 
 42                                                    41 
 43 #include "G4Scene.hh"                              42 #include "G4Scene.hh"
 44 #include "G4VisExtent.hh"                          43 #include "G4VisExtent.hh"
 45 #include "G4LogicalVolume.hh"                      44 #include "G4LogicalVolume.hh"
 46 #include "G4VSolid.hh"                             45 #include "G4VSolid.hh"
 47 #include "G4Point3D.hh"                            46 #include "G4Point3D.hh"
 48 #include "G4Normal3D.hh"                           47 #include "G4Normal3D.hh"
 49 #include "G4Plane3D.hh"                            48 #include "G4Plane3D.hh"
 50 #include "G4AttHolder.hh"                          49 #include "G4AttHolder.hh"
 51 #include "G4AttCheck.hh"                           50 #include "G4AttCheck.hh"
 52 #include "G4Text.hh"                               51 #include "G4Text.hh"
 53                                                    52 
                                                   >>  53 #ifdef G4OPENGL_VERSION_2
                                                   >>  54 // We need to have a Wt gl drawer because we will draw inside the WtGL component (ImmediateWtViewer)
                                                   >>  55 #include "G4OpenGLVboDrawer.hh"
                                                   >>  56 #endif
                                                   >>  57 
                                                   >>  58 // GL2PS
                                                   >>  59 #include "Geant4_gl2ps.h"
                                                   >>  60 
 54 #include <sstream>                                 61 #include <sstream>
 55 #include <string>                                  62 #include <string>
 56 #include <iomanip>                                 63 #include <iomanip>
 57                                                    64 
 58 G4OpenGLViewer::G4OpenGLViewer (G4OpenGLSceneH     65 G4OpenGLViewer::G4OpenGLViewer (G4OpenGLSceneHandler& scene):
 59 G4VViewer (scene, -1),                             66 G4VViewer (scene, -1),
                                                   >>  67 #ifdef G4OPENGL_VERSION_2
                                                   >>  68 fVboDrawer(NULL),
                                                   >>  69 #endif
 60 fPrintColour (true),                               70 fPrintColour (true),
 61 fVectoredPs (true),                                71 fVectoredPs (true),
 62 fOpenGLSceneHandler(scene),                        72 fOpenGLSceneHandler(scene),
 63 background (G4Colour(0.,0.,0.)),                   73 background (G4Colour(0.,0.,0.)),
 64 transparency_enabled (true),                       74 transparency_enabled (true),
 65 antialiasing_enabled (false),                      75 antialiasing_enabled (false),
 66 haloing_enabled (false),                           76 haloing_enabled (false),
                                                   >>  77 fStartTime(-DBL_MAX),
                                                   >>  78 fEndTime(DBL_MAX),
                                                   >>  79 fFadeFactor(0.),
                                                   >>  80 fDisplayHeadTime(false),
                                                   >>  81 fDisplayHeadTimeX(-0.9),
                                                   >>  82 fDisplayHeadTimeY(-0.9),
                                                   >>  83 fDisplayHeadTimeSize(24.),
                                                   >>  84 fDisplayHeadTimeRed(0.),
                                                   >>  85 fDisplayHeadTimeGreen(1.),
                                                   >>  86 fDisplayHeadTimeBlue(1.),
                                                   >>  87 fDisplayLightFront(false),
                                                   >>  88 fDisplayLightFrontX(0.),
                                                   >>  89 fDisplayLightFrontY(0.),
                                                   >>  90 fDisplayLightFrontZ(0.),
                                                   >>  91 fDisplayLightFrontT(0.),
                                                   >>  92 fDisplayLightFrontRed(0.),
                                                   >>  93 fDisplayLightFrontGreen(1.),
                                                   >>  94 fDisplayLightFrontBlue(0.),
 67 fRot_sens(1.),                                     95 fRot_sens(1.),
 68 fPan_sens(0.01),                                   96 fPan_sens(0.01),
 69 fWinSize_x(0),                                     97 fWinSize_x(0),
 70 fWinSize_y(0),                                     98 fWinSize_y(0),
 71 fDefaultExportImageFormat("pdf"),                  99 fDefaultExportImageFormat("pdf"),
 72 fExportImageFormat("pdf"),                        100 fExportImageFormat("pdf"),
 73 fExportFilenameIndex(0),                          101 fExportFilenameIndex(0),
 74 fPrintSizeX(-1),                                  102 fPrintSizeX(-1),
 75 fPrintSizeY(-1),                                  103 fPrintSizeY(-1),
 76 fPointSize (0),                                   104 fPointSize (0),
 77 fDefaultExportFilename("G4OpenGL"),               105 fDefaultExportFilename("G4OpenGL"),
 78 fSizeHasChanged(0),                               106 fSizeHasChanged(0),
 79 fGl2psDefaultLineWith(1),                         107 fGl2psDefaultLineWith(1),
 80 fGl2psDefaultPointSize(2),                        108 fGl2psDefaultPointSize(2),
 81 fGlViewInitialized(false),                        109 fGlViewInitialized(false),
 82 fIsGettingPickInfos(false)                        110 fIsGettingPickInfos(false)
                                                   >> 111 #ifdef G4OPENGL_VERSION_2
                                                   >> 112 ,fShaderProgram(0)
                                                   >> 113 ,fVertexPositionAttribute(0)
                                                   >> 114 ,fVertexNormalAttribute(0)
                                                   >> 115 ,fpMatrixUniform(0)
                                                   >> 116 ,fcMatrixUniform(0)
                                                   >> 117 ,fmvMatrixUniform(0)
                                                   >> 118 ,fnMatrixUniform(0)
                                                   >> 119 #endif
 83 {                                                 120 {
 84   // Make changes to view parameters for OpenG    121   // Make changes to view parameters for OpenGL...
 85   fVP.SetAutoRefresh(true);                       122   fVP.SetAutoRefresh(true);
 86   fDefaultVP.SetAutoRefresh(true);                123   fDefaultVP.SetAutoRefresh(true);
 87   fGL2PSAction = new G4gl2ps();                << 124 
 88   tools_gl2ps_gl_funcs_t _funcs = {            << 125   fGL2PSAction = new G4OpenGL2PSAction();
 89     (tools_glIsEnabled_func)glIsEnabled,       << 126 
 90     (tools_glBegin_func)glBegin,               << 
 91     (tools_glEnd_func)glEnd,                   << 
 92     (tools_glGetFloatv_func)glGetFloatv,       << 
 93     (tools_glVertex3f_func)glVertex3f,         << 
 94     (tools_glGetBooleanv_func)glGetBooleanv,   << 
 95     (tools_glGetIntegerv_func)glGetIntegerv,   << 
 96     (tools_glRenderMode_func)glRenderMode,     << 
 97     (tools_glFeedbackBuffer_func)glFeedbackBuf << 
 98     (tools_glPassThrough_func)glPassThrough    << 
 99   };                                           << 
100   fGL2PSAction->setOpenGLFunctions(&_funcs);   << 
101                                                << 
102   // add supported export image format            127   // add supported export image format
103   addExportImageFormat("eps");                    128   addExportImageFormat("eps");
104   addExportImageFormat("ps");                     129   addExportImageFormat("ps");
105   addExportImageFormat("pdf");                    130   addExportImageFormat("pdf");
106   addExportImageFormat("svg");                    131   addExportImageFormat("svg");
107                                                   132 
108   // Change the default name                      133   // Change the default name
109   fExportFilename += fDefaultExportFilename +     134   fExportFilename += fDefaultExportFilename + "_" + GetShortName().data();
110                                                   135   
111   //  glClearColor (0.0, 0.0, 0.0, 0.0);          136   //  glClearColor (0.0, 0.0, 0.0, 0.0);
112   //  glClearDepth (1.0);                         137   //  glClearDepth (1.0);
113   //  glDisable (GL_BLEND);                       138   //  glDisable (GL_BLEND);
114   //  glDisable (GL_LINE_SMOOTH);                 139   //  glDisable (GL_LINE_SMOOTH);
115   //  glDisable (GL_POLYGON_SMOOTH);              140   //  glDisable (GL_POLYGON_SMOOTH);
116                                                   141 
117 }                                                 142 }
118                                                   143 
119 G4OpenGLViewer::~G4OpenGLViewer ()                144 G4OpenGLViewer::~G4OpenGLViewer ()
120 {                                                 145 {
121   delete fGL2PSAction;                            146   delete fGL2PSAction;
122 }                                                 147 }
123                                                   148 
124 void G4OpenGLViewer::InitializeGLView ()          149 void G4OpenGLViewer::InitializeGLView () 
125 {                                                 150 {
                                                   >> 151 #ifdef G4OPENGL_VERSION_2
                                                   >> 152   if (fVboDrawer) {
                                                   >> 153     
                                                   >> 154     // First, load a simple shader
                                                   >> 155     fShaderProgram = glCreateProgram();
                                                   >> 156     Shader vertexShader = glCreateShader(GL_VERTEX_SHADER);
                                                   >> 157     const char * vSrc = fVboDrawer->getVertexShaderSrc();
                                                   >> 158     glShaderSource(vertexShader, 1, &vSrc, NULL);
                                                   >> 159     glCompileShader(vertexShader);
                                                   >> 160     glAttachShader(fShaderProgram, vertexShader);
                                                   >> 161     
                                                   >> 162     Shader fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
                                                   >> 163     const char * fSrc = fVboDrawer->getFragmentShaderSrc();
                                                   >> 164     glShaderSource(fragmentShader, 1, &fSrc, NULL);
                                                   >> 165     glCompileShader(fragmentShader);
                                                   >> 166     
                                                   >> 167     glAttachShader(fShaderProgram, fragmentShader);
                                                   >> 168     glLinkProgram(fShaderProgram);
                                                   >> 169     glUseProgram(fShaderProgram);
                                                   >> 170     
                                                   >> 171     //   UniformLocation uColor = getUniformLocation(fShaderProgram, "uColor");
                                                   >> 172     //   uniform4fv(uColor, [0.0, 0.3, 0.0, 1.0]);
                                                   >> 173     
                                                   >> 174     // Extract the references to the attributes from the shader.
                                                   >> 175     
                                                   >> 176     fVertexPositionAttribute =
                                                   >> 177     glGetAttribLocation(fShaderProgram, "aVertexPosition");
                                                   >> 178     
                                                   >> 179     
                                                   >> 180     glEnableVertexAttribArray(fVertexPositionAttribute);
                                                   >> 181     
                                                   >> 182     // Extract the references the uniforms from the shader
                                                   >> 183     fpMatrixUniform  = glGetUniformLocation(fShaderProgram, "uPMatrix");
                                                   >> 184     fcMatrixUniform  = glGetUniformLocation(fShaderProgram, "uCMatrix");
                                                   >> 185     fmvMatrixUniform = glGetUniformLocation(fShaderProgram, "uMVMatrix");
                                                   >> 186     fnMatrixUniform  = glGetUniformLocation(fShaderProgram, "uNMatrix");
                                                   >> 187     ftMatrixUniform  = glGetUniformLocation(fShaderProgram, "uTMatrix");
                                                   >> 188     
                                                   >> 189     /*    glUniformMatrix4fv(fcMatrixUniform, 1, 0, identity);
                                                   >> 190      glUniformMatrix4fv(fpMatrixUniform, 1, 0, identity);
                                                   >> 191      glUniformMatrix4fv(ftMatrixUniform, 1, 0, identity);
                                                   >> 192      glUniformMatrix4fv(fmvMatrixUniform, 1, 0, identity);
                                                   >> 193      */
                                                   >> 194     // We have to set that in order to avoid calls on opengl commands before all is ready
                                                   >> 195     fGlViewInitialized = true;
                                                   >> 196   }
                                                   >> 197 #endif
                                                   >> 198   
126   if (fWinSize_x == 0) {                          199   if (fWinSize_x == 0) {
127     fWinSize_x = fVP.GetWindowSizeHintX();        200     fWinSize_x = fVP.GetWindowSizeHintX();
128   }                                               201   }
129   if (fWinSize_y == 0) {                          202   if (fWinSize_y == 0) {
130     fWinSize_y = fVP.GetWindowSizeHintY();        203     fWinSize_y = fVP.GetWindowSizeHintY();
131   }                                               204   }
132                                                   205 
133   glClearColor (0.0, 0.0, 0.0, 0.0);              206   glClearColor (0.0, 0.0, 0.0, 0.0);
134   glClearDepth (1.0);                             207   glClearDepth (1.0);
                                                   >> 208 #ifndef G4OPENGL_VERSION_2
135   glDisable (GL_LINE_SMOOTH);                     209   glDisable (GL_LINE_SMOOTH);
136   glDisable (GL_POLYGON_SMOOTH);                  210   glDisable (GL_POLYGON_SMOOTH);
                                                   >> 211 #endif
137                                                   212 
138 // clear the buffers and window?                  213 // clear the buffers and window?
139   ClearView ();                                   214   ClearView ();
140   FinishView ();                                  215   FinishView ();
141                                                   216   
142   glDepthFunc (GL_LEQUAL);                        217   glDepthFunc (GL_LEQUAL);
143   glDepthMask (GL_TRUE);                          218   glDepthMask (GL_TRUE);
144                                                   219   
145   glEnable (GL_BLEND);                            220   glEnable (GL_BLEND);
146   glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_    221   glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
147                                                   222   
148 }                                                 223 }
149                                                   224 
150 void G4OpenGLViewer::ClearView () {               225 void G4OpenGLViewer::ClearView () {
151   ClearViewWithoutFlush();                        226   ClearViewWithoutFlush();
152                                                   227 
153   if(!isFramebufferReady()) {                     228   if(!isFramebufferReady()) {
154     return;                                       229     return;
155   }                                               230   }
156                                                   231 
157   glFlush();                                      232   glFlush();
158 }                                                 233 }
159                                                   234 
160                                                   235 
161 void G4OpenGLViewer::ClearViewWithoutFlush ()     236 void G4OpenGLViewer::ClearViewWithoutFlush () {
162   // Ready for clear ?                            237   // Ready for clear ?
163   // See : http://lists.apple.com/archives/mac    238   // See : http://lists.apple.com/archives/mac-opengl/2012/Jul/msg00038.html
164   if(!isFramebufferReady()) {                     239   if(!isFramebufferReady()) {
165     return;                                       240     return;
166   }                                               241   }
167                                                   242   
168   glClearColor (background.GetRed(),              243   glClearColor (background.GetRed(),
169                 background.GetGreen(),            244                 background.GetGreen(),
170                 background.GetBlue(),             245                 background.GetBlue(),
171                 1.);                              246                 1.);
172   glClearDepth (1.0);                             247   glClearDepth (1.0);
173   //Below line does not compile with Mesa incl    248   //Below line does not compile with Mesa includes.
174   //glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BU    249   //glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
175   glClear (GL_COLOR_BUFFER_BIT);                  250   glClear (GL_COLOR_BUFFER_BIT);
176   glClear (GL_DEPTH_BUFFER_BIT);                  251   glClear (GL_DEPTH_BUFFER_BIT);
177   glClear (GL_STENCIL_BUFFER_BIT);                252   glClear (GL_STENCIL_BUFFER_BIT);
178 }                                                 253 }
179                                                   254 
180                                                   255 
181 void G4OpenGLViewer::ResizeWindow(unsigned int    256 void G4OpenGLViewer::ResizeWindow(unsigned int aWidth, unsigned int aHeight) {
182   if ((fWinSize_x != aWidth) || (fWinSize_y !=    257   if ((fWinSize_x != aWidth) || (fWinSize_y != aHeight)) {
183     fWinSize_x = aWidth;                          258     fWinSize_x = aWidth;
184     fWinSize_y = aHeight;                         259     fWinSize_y = aHeight;
185     fSizeHasChanged = true;                       260     fSizeHasChanged = true;
186   } else {                                        261   } else {
187     fSizeHasChanged = false;                      262     fSizeHasChanged = false;
188   }                                               263   }
189 }                                                 264 }
190                                                   265 
191 /**                                               266 /**
192  * Set the viewport of the scene                  267  * Set the viewport of the scene
193  * MAXIMUM SIZE is :                              268  * MAXIMUM SIZE is :
194  * GLint dims[2];                                 269  * GLint dims[2];
195  * glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);     270  * glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);
196  */                                               271  */
197 void G4OpenGLViewer::ResizeGLView()               272 void G4OpenGLViewer::ResizeGLView()
198 {                                                 273 {
199   // Check size                                   274   // Check size
200   GLint dims[2];                                  275   GLint dims[2];
201   dims[0] = 0;                                    276   dims[0] = 0;
202   dims[1] = 0;                                    277   dims[1] = 0;
203                                                   278 
204   glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);      279   glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);
205                                                   280 
206   if ((dims[0] !=0 ) && (dims[1] !=0)) {          281   if ((dims[0] !=0 ) && (dims[1] !=0)) {
207                                                   282 
208     if (fWinSize_x > (unsigned)dims[0]) {         283     if (fWinSize_x > (unsigned)dims[0]) {
209       G4cerr << "Try to resize view greater th    284       G4cerr << "Try to resize view greater than max X viewport dimension. Desired size "<<fWinSize_x <<" is resize to "<<  dims[0] << G4endl;
210       fWinSize_x = dims[0];                       285       fWinSize_x = dims[0];
211     }                                             286     }
212     if (fWinSize_y > (unsigned)dims[1]) {         287     if (fWinSize_y > (unsigned)dims[1]) {
213       G4cerr << "Try to resize view greater th    288       G4cerr << "Try to resize view greater than max Y viewport dimension. Desired size "<<fWinSize_y <<" is resize to "<<  dims[1] << G4endl;
214       fWinSize_y = dims[1];                       289       fWinSize_y = dims[1];
215     }                                             290     }
216   }                                               291   }
217                                                   292     
218   glViewport(0, 0, fWinSize_x,fWinSize_y);        293   glViewport(0, 0, fWinSize_x,fWinSize_y);   
219                                                   294 
220                                                   295 
221 }                                                 296 }
222                                                   297 
223                                                   298 
224 void G4OpenGLViewer::SetView () {                 299 void G4OpenGLViewer::SetView () {
225   // if getting pick infos, should not resize     300   // if getting pick infos, should not resize the view.
226   if (fIsGettingPickInfos) return;                301   if (fIsGettingPickInfos) return;
227                                                   302   
228   if (!fSceneHandler.GetScene()) {                303   if (!fSceneHandler.GetScene()) {
229     return;                                       304     return;
230   }                                               305   }
231   // Calculates view representation based on e    306   // Calculates view representation based on extent of object being
232   // viewed and (initial) viewpoint.  (Note: i    307   // viewed and (initial) viewpoint.  (Note: it can change later due
233   // to user interaction via visualization sys    308   // to user interaction via visualization system's GUI.)
234                                                   309   
235   // Lighting.                                    310   // Lighting.
236   GLfloat lightPosition [4];                      311   GLfloat lightPosition [4];
237   lightPosition [0] = fVP.GetActualLightpointD    312   lightPosition [0] = fVP.GetActualLightpointDirection().x();
238   lightPosition [1] = fVP.GetActualLightpointD    313   lightPosition [1] = fVP.GetActualLightpointDirection().y();
239   lightPosition [2] = fVP.GetActualLightpointD    314   lightPosition [2] = fVP.GetActualLightpointDirection().z();
240   lightPosition [3] = 0.;                         315   lightPosition [3] = 0.;
241   // Light position is "true" light direction,    316   // Light position is "true" light direction, so must come after gluLookAt.
242   GLfloat ambient [] = { 0.2f, 0.2f, 0.2f, 1.f    317   GLfloat ambient [] = { 0.2f, 0.2f, 0.2f, 1.f};
243   GLfloat diffuse [] = { 0.8f, 0.8f, 0.8f, 1.f    318   GLfloat diffuse [] = { 0.8f, 0.8f, 0.8f, 1.f};
244   glEnable (GL_LIGHT0);                           319   glEnable (GL_LIGHT0);
245   glLightfv (GL_LIGHT0, GL_AMBIENT, ambient);     320   glLightfv (GL_LIGHT0, GL_AMBIENT, ambient);
246   glLightfv (GL_LIGHT0, GL_DIFFUSE, diffuse);     321   glLightfv (GL_LIGHT0, GL_DIFFUSE, diffuse);
247                                                   322   
248   G4double ratioX = 1;                            323   G4double ratioX = 1;
249   G4double ratioY = 1;                            324   G4double ratioY = 1;
250   if (fWinSize_y > fWinSize_x) {                  325   if (fWinSize_y > fWinSize_x) {
251     ratioX = ((G4double)fWinSize_y) / ((G4doub    326     ratioX = ((G4double)fWinSize_y) / ((G4double)fWinSize_x);
252   }                                               327   }
253   if (fWinSize_x > fWinSize_y) {                  328   if (fWinSize_x > fWinSize_y) {
254     ratioY = ((G4double)fWinSize_x) / ((G4doub    329     ratioY = ((G4double)fWinSize_x) / ((G4double)fWinSize_y);
255   }                                               330   }
256                                                   331   
257   // Get radius of scene, etc.                    332   // Get radius of scene, etc.
258   // Note that this procedure properly takes i    333   // Note that this procedure properly takes into account zoom, dolly and pan.
259   const G4Point3D targetPoint                     334   const G4Point3D targetPoint
260     = fSceneHandler.GetScene()->GetStandardTar    335     = fSceneHandler.GetScene()->GetStandardTargetPoint()
261     + fVP.GetCurrentTargetPoint ();               336     + fVP.GetCurrentTargetPoint ();
262   G4double radius = fSceneHandler.GetScene()->    337   G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
263   if(radius<=0.) radius = 1.;                     338   if(radius<=0.) radius = 1.;
264   const G4double cameraDistance = fVP.GetCamer    339   const G4double cameraDistance = fVP.GetCameraDistance (radius);
265   const G4Point3D cameraPosition =                340   const G4Point3D cameraPosition =
266     targetPoint + cameraDistance * fVP.GetView    341     targetPoint + cameraDistance * fVP.GetViewpointDirection().unit();
267   const GLdouble pnear  = fVP.GetNearDistance     342   const GLdouble pnear  = fVP.GetNearDistance (cameraDistance, radius);
268   const GLdouble pfar   = fVP.GetFarDistance      343   const GLdouble pfar   = fVP.GetFarDistance  (cameraDistance, pnear, radius);
269   const GLdouble right  = fVP.GetFrontHalfHeig    344   const GLdouble right  = fVP.GetFrontHalfHeight (pnear, radius) * ratioY;
270   const GLdouble left   = -right;                 345   const GLdouble left   = -right;
271   const GLdouble top    = fVP.GetFrontHalfHeig    346   const GLdouble top    = fVP.GetFrontHalfHeight (pnear, radius) * ratioX;
272   const GLdouble bottom = -top;                   347   const GLdouble bottom = -top;
273                                                   348   
274   // FIXME                                        349   // FIXME
275   ResizeGLView();                                 350   ResizeGLView();
276   //SHOULD SetWindowsSizeHint()...                351   //SHOULD SetWindowsSizeHint()...
277                                                   352 
278   glMatrixMode (GL_PROJECTION); // set up Frus    353   glMatrixMode (GL_PROJECTION); // set up Frustum.
279   glLoadIdentity();                               354   glLoadIdentity();
280                                                   355 
281   const G4Vector3D scaleFactor = fVP.GetScaleF    356   const G4Vector3D scaleFactor = fVP.GetScaleFactor();
282   glScaled(scaleFactor.x(),scaleFactor.y(),sca    357   glScaled(scaleFactor.x(),scaleFactor.y(),scaleFactor.z());
283                                                   358   
284   if (fVP.GetFieldHalfAngle() == 0.) {            359   if (fVP.GetFieldHalfAngle() == 0.) {
285     g4GlOrtho (left, right, bottom, top, pnear    360     g4GlOrtho (left, right, bottom, top, pnear, pfar);
286   }                                               361   }
287   else {                                          362   else {
288     g4GlFrustum (left, right, bottom, top, pne    363     g4GlFrustum (left, right, bottom, top, pnear, pfar);
289   }                                               364   }  
290                                                   365 
291   glMatrixMode (GL_MODELVIEW); // apply furthe    366   glMatrixMode (GL_MODELVIEW); // apply further transformations to scene.
292   glLoadIdentity();                               367   glLoadIdentity();
293                                                   368   
294   const G4Normal3D& upVector = fVP.GetUpVector    369   const G4Normal3D& upVector = fVP.GetUpVector ();  
295   G4Point3D gltarget;                             370   G4Point3D gltarget;
296   if (cameraDistance > 1.e-6 * radius) {          371   if (cameraDistance > 1.e-6 * radius) {
297     gltarget = targetPoint;                       372     gltarget = targetPoint;
298   }                                               373   }
299   else {                                          374   else {
300     gltarget = targetPoint - radius * fVP.GetV    375     gltarget = targetPoint - radius * fVP.GetViewpointDirection().unit();
301   }                                               376   }
302                                                   377 
303   const G4Point3D& pCamera = cameraPosition;      378   const G4Point3D& pCamera = cameraPosition;  // An alias for brevity.
304                                                   379 
305   g4GluLookAt (pCamera.x(),  pCamera.y(),  pCa    380   g4GluLookAt (pCamera.x(),  pCamera.y(),  pCamera.z(),       // Viewpoint.
306              gltarget.x(), gltarget.y(), gltar    381              gltarget.x(), gltarget.y(), gltarget.z(),      // Target point.
307              upVector.x(), upVector.y(), upVec    382              upVector.x(), upVector.y(), upVector.z());     // Up vector.
308   // Light position is "true" light direction,    383   // Light position is "true" light direction, so must come after gluLookAt.
309   glLightfv (GL_LIGHT0, GL_POSITION, lightPosi    384   glLightfv (GL_LIGHT0, GL_POSITION, lightPosition);
310                                                   385 
311   // The idea is to use back-to-back clipping     386   // The idea is to use back-to-back clipping planes.  This can cut an object
312   // down to just a few pixels, which can make    387   // down to just a few pixels, which can make it difficult to see.  So, for
313   // now, comment this out and use the generic    388   // now, comment this out and use the generic (Boolean) method, via
314   // G4VSolid* G4OpenGLSceneHandler::CreateSec    389   // G4VSolid* G4OpenGLSceneHandler::CreateSectionSolid ()
315   // { return G4VSceneHandler::CreateSectionSo    390   // { return G4VSceneHandler::CreateSectionSolid(); }
316 //  if (fVP.IsSection () ) {  // pair of back     391 //  if (fVP.IsSection () ) {  // pair of back to back clip planes.
317 //    const G4Plane3D& sp = fVP.GetSectionPlan    392 //    const G4Plane3D& sp = fVP.GetSectionPlane ();
318 //    double sArray[4];                           393 //    double sArray[4];
319 //    sArray[0] = sp.a();                         394 //    sArray[0] = sp.a();
320 //    sArray[1] = sp.b();                         395 //    sArray[1] = sp.b();
321 //    sArray[2] = sp.c();                         396 //    sArray[2] = sp.c();
322 //    sArray[3] = sp.d() + radius * 1.e-05;       397 //    sArray[3] = sp.d() + radius * 1.e-05;
323 //    glClipPlane (GL_CLIP_PLANE0, sArray);       398 //    glClipPlane (GL_CLIP_PLANE0, sArray);
324 //    glEnable (GL_CLIP_PLANE0);                  399 //    glEnable (GL_CLIP_PLANE0);
325 //    sArray[0] = -sp.a();                        400 //    sArray[0] = -sp.a();
326 //    sArray[1] = -sp.b();                        401 //    sArray[1] = -sp.b();
327 //    sArray[2] = -sp.c();                        402 //    sArray[2] = -sp.c();
328 //    sArray[3] = -sp.d() + radius * 1.e-05;      403 //    sArray[3] = -sp.d() + radius * 1.e-05;
329 //    glClipPlane (GL_CLIP_PLANE1, sArray);       404 //    glClipPlane (GL_CLIP_PLANE1, sArray);
330 //    glEnable (GL_CLIP_PLANE1);                  405 //    glEnable (GL_CLIP_PLANE1);
331 //  } else {                                      406 //  } else {
332 //    glDisable (GL_CLIP_PLANE0);                 407 //    glDisable (GL_CLIP_PLANE0);
333 //    glDisable (GL_CLIP_PLANE1);                 408 //    glDisable (GL_CLIP_PLANE1);
334 //  }                                             409 //  }
335                                                   410 
336   // What we call intersection of cutaways is     411   // What we call intersection of cutaways is easy in OpenGL.  You
337   // just keep cutting.  Unions are more trick    412   // just keep cutting.  Unions are more tricky - you have to have
338   // multiple passes and this is handled in       413   // multiple passes and this is handled in
339   // G4OpenGLImmediate/StoredViewer::ProcessVi    414   // G4OpenGLImmediate/StoredViewer::ProcessView.
340   const G4Planes& cutaways = fVP.GetCutawayPla    415   const G4Planes& cutaways = fVP.GetCutawayPlanes();
341   size_t nPlanes = cutaways.size();               416   size_t nPlanes = cutaways.size();
342   if (fVP.IsCutaway() &&                          417   if (fVP.IsCutaway() &&
343       fVP.GetCutawayMode() == G4ViewParameters << 418       fVP.GetCutawayMode() == G4ViewParameters::cutawayIntersection &&
                                                   >> 419       nPlanes > 0) {
344     double a[4];                                  420     double a[4];
345     a[0] = cutaways[0].a();                       421     a[0] = cutaways[0].a();
346     a[1] = cutaways[0].b();                       422     a[1] = cutaways[0].b();
347     a[2] = cutaways[0].c();                       423     a[2] = cutaways[0].c();
348     a[3] = cutaways[0].d();                       424     a[3] = cutaways[0].d();
349     glClipPlane (GL_CLIP_PLANE2, a);              425     glClipPlane (GL_CLIP_PLANE2, a);
350     glEnable (GL_CLIP_PLANE2);                    426     glEnable (GL_CLIP_PLANE2);
351     if (nPlanes > 1) {                            427     if (nPlanes > 1) {
352       a[0] = cutaways[1].a();                     428       a[0] = cutaways[1].a();
353       a[1] = cutaways[1].b();                     429       a[1] = cutaways[1].b();
354       a[2] = cutaways[1].c();                     430       a[2] = cutaways[1].c();
355       a[3] = cutaways[1].d();                     431       a[3] = cutaways[1].d();
356       glClipPlane (GL_CLIP_PLANE3, a);            432       glClipPlane (GL_CLIP_PLANE3, a);
357       glEnable (GL_CLIP_PLANE3);                  433       glEnable (GL_CLIP_PLANE3);
358     }                                             434     }
359     if (nPlanes > 2) {                            435     if (nPlanes > 2) {
360       a[0] = cutaways[2].a();                     436       a[0] = cutaways[2].a();
361       a[1] = cutaways[2].b();                     437       a[1] = cutaways[2].b();
362       a[2] = cutaways[2].c();                     438       a[2] = cutaways[2].c();
363       a[3] = cutaways[2].d();                     439       a[3] = cutaways[2].d();
364       glClipPlane (GL_CLIP_PLANE4, a);            440       glClipPlane (GL_CLIP_PLANE4, a);
365       glEnable (GL_CLIP_PLANE4);                  441       glEnable (GL_CLIP_PLANE4);
366     }                                             442     }
367   } else {                                        443   } else {
368     glDisable (GL_CLIP_PLANE2);                   444     glDisable (GL_CLIP_PLANE2);
369     glDisable (GL_CLIP_PLANE3);                   445     glDisable (GL_CLIP_PLANE3);
370     glDisable (GL_CLIP_PLANE4);                   446     glDisable (GL_CLIP_PLANE4);
371   }                                               447   }
372                                                   448 
373   // Background.                                  449   // Background.
374   background = fVP.GetBackgroundColour ();        450   background = fVP.GetBackgroundColour ();
375                                                   451 
376 }                                                 452 }
377                                                   453 
378                                                   454 
379                                                   455 
380 void G4OpenGLViewer::ResetView () {               456 void G4OpenGLViewer::ResetView () {
381   G4VViewer::ResetView();                         457   G4VViewer::ResetView();
382   fRot_sens = 1;                                  458   fRot_sens = 1;
383   fPan_sens = 0.01;                               459   fPan_sens = 0.01;
384 }                                                 460 }
385                                                   461 
386                                                   462 
387 void G4OpenGLViewer::HaloingFirstPass () {        463 void G4OpenGLViewer::HaloingFirstPass () {
388                                                   464   
389   //To perform haloing, first Draw all informa    465   //To perform haloing, first Draw all information to the depth buffer
390   //alone, using a chunky line width, and then    466   //alone, using a chunky line width, and then Draw all info again, to
391   //the colour buffer, setting a thinner line     467   //the colour buffer, setting a thinner line width an the depth testing 
392   //function to less than or equal, so if two     468   //function to less than or equal, so if two lines cross, the one 
393   //passing behind the other will not pass the    469   //passing behind the other will not pass the depth test, and so not
394   //get rendered either side of the infront li    470   //get rendered either side of the infront line for a short distance.
395                                                   471 
396   //First, disable writing to the colo(u)r buf    472   //First, disable writing to the colo(u)r buffer...
397   glColorMask (GL_FALSE, GL_FALSE, GL_FALSE, G    473   glColorMask (GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
398                                                   474 
399   //Now enable writing to the depth buffer...     475   //Now enable writing to the depth buffer...
400   glDepthMask (GL_TRUE);                          476   glDepthMask (GL_TRUE);
401   glDepthFunc (GL_LESS);                          477   glDepthFunc (GL_LESS);
402   glClearDepth (1.0);                             478   glClearDepth (1.0);
403                                                   479 
404   //Finally, set the line width to something w    480   //Finally, set the line width to something wide...
405   ChangeLineWidth(3.0);                           481   ChangeLineWidth(3.0);
406                                                   482 
407 }                                                 483 }
408                                                   484 
409 void G4OpenGLViewer::HaloingSecondPass () {       485 void G4OpenGLViewer::HaloingSecondPass () {
410                                                   486 
411   //And finally, turn the colour buffer back o    487   //And finally, turn the colour buffer back on with a sesible line width...
412   glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_T    488   glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
413   glDepthFunc (GL_LEQUAL);                        489   glDepthFunc (GL_LEQUAL);
414   ChangeLineWidth(1.0);                           490   ChangeLineWidth(1.0);
415                                                   491 
416 }                                                 492 }
417                                                   493 
418 G4String G4OpenGLViewer::Pick(GLdouble x, GLdo    494 G4String G4OpenGLViewer::Pick(GLdouble x, GLdouble y)
419 {                                                 495 {
420   const std::vector < G4OpenGLViewerPickMap* >    496   const std::vector < G4OpenGLViewerPickMap* > & pickMap = GetPickDetails(x,y);
421   G4String txt = "";                              497   G4String txt = "";
422   if (pickMap.size() == 0) {                      498   if (pickMap.size() == 0) {
423 //        txt += "No hits recorded.";;            499 //        txt += "No hits recorded.";;
424   } else {                                        500   } else {
425     for (unsigned int a=0; a < pickMap.size();    501     for (unsigned int a=0; a < pickMap.size(); a++) {
426       if (pickMap[a]->getAttributes().size() >    502       if (pickMap[a]->getAttributes().size() > 0) {
427         txt += pickMap[a]->print();               503         txt += pickMap[a]->print();
428       }                                           504       }
429     }                                             505     }
430   }                                               506   }
431   return txt;                                     507   return txt;
432 }                                                 508 }
433                                                   509 
434 const std::vector < G4OpenGLViewerPickMap* > &    510 const std::vector < G4OpenGLViewerPickMap* > & G4OpenGLViewer::GetPickDetails(GLdouble x, GLdouble y)
435 {                                                 511 {
436   static std::vector < G4OpenGLViewerPickMap*     512   static std::vector < G4OpenGLViewerPickMap* > pickMapVector;
437   for (auto pickMap: pickMapVector) {             513   for (auto pickMap: pickMapVector) {
438     delete pickMap;                               514     delete pickMap;
439   }                                               515   }
440   pickMapVector.clear();                          516   pickMapVector.clear();
441                                                   517   
442   const G4int BUFSIZE = 512;                      518   const G4int BUFSIZE = 512;
443   GLuint selectBuffer[BUFSIZE];                   519   GLuint selectBuffer[BUFSIZE];
444   glSelectBuffer(BUFSIZE, selectBuffer);          520   glSelectBuffer(BUFSIZE, selectBuffer);
445   glRenderMode(GL_SELECT);                        521   glRenderMode(GL_SELECT);
446   glInitNames();                                  522   glInitNames();
447   glPushName(0);                                  523   glPushName(0);
448   glMatrixMode(GL_PROJECTION);                    524   glMatrixMode(GL_PROJECTION);
449   G4double currentProjectionMatrix[16];           525   G4double currentProjectionMatrix[16];
450   glGetDoublev(GL_PROJECTION_MATRIX, currentPr    526   glGetDoublev(GL_PROJECTION_MATRIX, currentProjectionMatrix);
451   glPushMatrix();                                 527   glPushMatrix();
452   glLoadIdentity();                               528   glLoadIdentity();
453   GLint viewport[4];                              529   GLint viewport[4];
454   glGetIntegerv(GL_VIEWPORT, viewport);           530   glGetIntegerv(GL_VIEWPORT, viewport);
455 /*  G4cout                                        531 /*  G4cout
456   << "viewport, x,y: "                            532   << "viewport, x,y: "
457   << viewport[0] << ',' << viewport[1] << ','     533   << viewport[0] << ',' << viewport[1] << ',' << viewport[2] << ',' << viewport[3]
458   << ", " << x << ',' << y                        534   << ", " << x << ',' << y
459   << G4endl;                                      535   << G4endl;
460 */                                                536 */
461   fIsGettingPickInfos = true;                     537   fIsGettingPickInfos = true;
462   // Define 5x5 pixel pick area                   538   // Define 5x5 pixel pick area
463   g4GluPickMatrix(x, viewport[3] - y, 5., 5.,     539   g4GluPickMatrix(x, viewport[3] - y, 5., 5., viewport);
464   glMultMatrixd(currentProjectionMatrix);         540   glMultMatrixd(currentProjectionMatrix);
465   glMatrixMode(GL_MODELVIEW);                     541   glMatrixMode(GL_MODELVIEW);
466   DrawView();                                     542   DrawView();
467   GLint hits = glRenderMode(GL_RENDER);           543   GLint hits = glRenderMode(GL_RENDER);
468   fIsGettingPickInfos = false;                    544   fIsGettingPickInfos = false;
469   if (hits < 0) {                                 545   if (hits < 0) {
470     G4cout << "Too many hits.  Zoom in to redu    546     G4cout << "Too many hits.  Zoom in to reduce overlaps." << G4endl;
471     goto restoreMatrices;                         547     goto restoreMatrices;
472   }                                               548   }
473   if (hits > 0) {                                 549   if (hits > 0) {
474     GLuint* p = selectBuffer;                     550     GLuint* p = selectBuffer;
475     for (GLint i = 0; i < hits; ++i) {            551     for (GLint i = 0; i < hits; ++i) {
476       GLuint nnames = *p++;                       552       GLuint nnames = *p++;
477       // This bit of debug code or...             553       // This bit of debug code or...
478       //GLuint zmin = *p++;                       554       //GLuint zmin = *p++;
479       //GLuint zmax = *p++;                       555       //GLuint zmax = *p++;
480       //G4cout << "Hit " << i << ": " << nname    556       //G4cout << "Hit " << i << ": " << nnames << " names"
481       //       << "\nzmin: " << zmin << ", zma    557       //       << "\nzmin: " << zmin << ", zmax: " << zmax << G4endl;
482       // ...just increment the pointer            558       // ...just increment the pointer
483       p++;                                        559       p++;
484       p++;                                        560       p++;
485       for (GLuint j = 0; j < nnames; ++j) {       561       for (GLuint j = 0; j < nnames; ++j) {
486         GLuint name = *p++;                       562         GLuint name = *p++;
487   std::map<GLuint, G4AttHolder*>::iterator ite    563   std::map<GLuint, G4AttHolder*>::iterator iter =
488     fOpenGLSceneHandler.fPickMap.find(name);      564     fOpenGLSceneHandler.fPickMap.find(name);
489   if (iter != fOpenGLSceneHandler.fPickMap.end    565   if (iter != fOpenGLSceneHandler.fPickMap.end()) {
490     G4AttHolder* attHolder = iter->second;        566     G4AttHolder* attHolder = iter->second;
491     if(attHolder && attHolder->GetAttDefs().si    567     if(attHolder && attHolder->GetAttDefs().size()) {
492       for (size_t iAtt = 0;                       568       for (size_t iAtt = 0;
493      iAtt < attHolder->GetAttDefs().size(); ++    569      iAtt < attHolder->GetAttDefs().size(); ++iAtt) {
494               std::ostringstream oss;             570               std::ostringstream oss;
495         oss << G4AttCheck(attHolder->GetAttVal    571         oss << G4AttCheck(attHolder->GetAttValues()[iAtt],
496                                 attHolder->Get    572                                 attHolder->GetAttDefs()[iAtt]);
497               G4OpenGLViewerPickMap* pickMap =    573               G4OpenGLViewerPickMap* pickMap = new G4OpenGLViewerPickMap();
498 //              G4cout                            574 //              G4cout
499 //              << "i,j, attHolder->GetAttDefs    575 //              << "i,j, attHolder->GetAttDefs().size(): "
500 //              << i << ',' << j                  576 //              << i << ',' << j
501 //              << ", " << attHolder->GetAttDe    577 //              << ", " << attHolder->GetAttDefs().size()
502 //              << G4endl;                        578 //              << G4endl;
503 //              G4cout << "G4OpenGLViewer::Get    579 //              G4cout << "G4OpenGLViewer::GetPickDetails: " << oss.str() << G4endl;
504               pickMap->addAttributes(oss.str()    580               pickMap->addAttributes(oss.str());
505               pickMap->setHitNumber(i);           581               pickMap->setHitNumber(i);
506               pickMap->setSubHitNumber(j);        582               pickMap->setSubHitNumber(j);
507               pickMap->setPickName(name);         583               pickMap->setPickName(name);
508               pickMapVector.push_back(pickMap)    584               pickMapVector.push_back(pickMap);
509             }                                     585             }
510           }                                       586           }
511         }                                         587         }
512       }                                           588       }
513     }                                             589     }
514   }                                               590   }
515                                                   591 
516 restoreMatrices:                                  592 restoreMatrices:
517   glMatrixMode(GL_PROJECTION);                    593   glMatrixMode(GL_PROJECTION);
518   glPopMatrix();                                  594   glPopMatrix();
519   glMatrixMode(GL_MODELVIEW);                     595   glMatrixMode(GL_MODELVIEW);
520                                                   596 
521   return pickMapVector;                           597   return pickMapVector;
522 }                                                 598 }
523                                                   599 
524 GLubyte* G4OpenGLViewer::grabPixels               600 GLubyte* G4OpenGLViewer::grabPixels
525 (int inColor, unsigned int width, unsigned int    601 (int inColor, unsigned int width, unsigned int height) {
526                                                   602   
527   GLubyte* buffer;                                603   GLubyte* buffer;
528   GLint swapbytes, lsbfirst, rowlength;           604   GLint swapbytes, lsbfirst, rowlength;
529   GLint skiprows, skippixels, alignment;          605   GLint skiprows, skippixels, alignment;
530   GLenum format;                                  606   GLenum format;
531   int size;                                       607   int size;
532                                                   608 
533   if (inColor) {                                  609   if (inColor) {
534     format = GL_RGB;                              610     format = GL_RGB;
535     size = width*height*3;                        611     size = width*height*3;
536   } else {                                        612   } else {
537     format = GL_LUMINANCE;                        613     format = GL_LUMINANCE;
538     size = width*height*1;                        614     size = width*height*1;
539   }                                               615   }
540                                                   616 
541   buffer = new GLubyte[size];                     617   buffer = new GLubyte[size];
542   if (buffer == NULL)                             618   if (buffer == NULL)
543     return NULL;                                  619     return NULL;
544                                                   620 
545   glGetIntegerv (GL_UNPACK_SWAP_BYTES, &swapby    621   glGetIntegerv (GL_UNPACK_SWAP_BYTES, &swapbytes);
546   glGetIntegerv (GL_UNPACK_LSB_FIRST, &lsbfirs    622   glGetIntegerv (GL_UNPACK_LSB_FIRST, &lsbfirst);
547   glGetIntegerv (GL_UNPACK_ROW_LENGTH, &rowlen    623   glGetIntegerv (GL_UNPACK_ROW_LENGTH, &rowlength);
548                                                   624 
549   glGetIntegerv (GL_UNPACK_SKIP_ROWS, &skiprow    625   glGetIntegerv (GL_UNPACK_SKIP_ROWS, &skiprows);
550   glGetIntegerv (GL_UNPACK_SKIP_PIXELS, &skipp    626   glGetIntegerv (GL_UNPACK_SKIP_PIXELS, &skippixels);
551   glGetIntegerv (GL_UNPACK_ALIGNMENT, &alignme    627   glGetIntegerv (GL_UNPACK_ALIGNMENT, &alignment);
552                                                   628 
553   glPixelStorei (GL_UNPACK_SWAP_BYTES, GL_FALS    629   glPixelStorei (GL_UNPACK_SWAP_BYTES, GL_FALSE);
554   glPixelStorei (GL_UNPACK_LSB_FIRST, GL_FALSE    630   glPixelStorei (GL_UNPACK_LSB_FIRST, GL_FALSE);
555   glPixelStorei (GL_UNPACK_ROW_LENGTH, 0);        631   glPixelStorei (GL_UNPACK_ROW_LENGTH, 0);
556                                                   632 
557   glPixelStorei (GL_UNPACK_SKIP_ROWS, 0);         633   glPixelStorei (GL_UNPACK_SKIP_ROWS, 0);
558   glPixelStorei (GL_UNPACK_SKIP_PIXELS, 0);       634   glPixelStorei (GL_UNPACK_SKIP_PIXELS, 0);
559   glPixelStorei (GL_UNPACK_ALIGNMENT, 1);         635   glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
560                                                   636 
561   glReadBuffer(GL_FRONT);                         637   glReadBuffer(GL_FRONT);
562   glReadPixels (0, 0, (GLsizei)width, (GLsizei    638   glReadPixels (0, 0, (GLsizei)width, (GLsizei)height, format, GL_UNSIGNED_BYTE, (GLvoid*) buffer);
563                                                   639 
564   glPixelStorei (GL_UNPACK_SWAP_BYTES, swapbyt    640   glPixelStorei (GL_UNPACK_SWAP_BYTES, swapbytes);
565   glPixelStorei (GL_UNPACK_LSB_FIRST, lsbfirst    641   glPixelStorei (GL_UNPACK_LSB_FIRST, lsbfirst);
566   glPixelStorei (GL_UNPACK_ROW_LENGTH, rowleng    642   glPixelStorei (GL_UNPACK_ROW_LENGTH, rowlength);
567                                                   643   
568   glPixelStorei (GL_UNPACK_SKIP_ROWS, skiprows    644   glPixelStorei (GL_UNPACK_SKIP_ROWS, skiprows);
569   glPixelStorei (GL_UNPACK_SKIP_PIXELS, skippi    645   glPixelStorei (GL_UNPACK_SKIP_PIXELS, skippixels);
570   glPixelStorei (GL_UNPACK_ALIGNMENT, alignmen    646   glPixelStorei (GL_UNPACK_ALIGNMENT, alignment);
571                                                   647   
572   return buffer;                                  648   return buffer;
573 }                                                 649 }
574                                                   650 
                                                   >> 651 bool G4OpenGLViewer::printEPS() {
                                                   >> 652   bool res;
                                                   >> 653 
                                                   >> 654   // Change the LC_NUMERIC value in order to have "." separtor and not ","
                                                   >> 655   // This case is only useful for French, Canadien...
                                                   >> 656   size_t len = strlen(setlocale(LC_NUMERIC,NULL));
                                                   >> 657   char* oldLocale = (char*)(malloc(len+1));
                                                   >> 658   if(oldLocale!=NULL) strncpy(oldLocale,setlocale(LC_NUMERIC,NULL),len);
                                                   >> 659   setlocale(LC_NUMERIC,"C");
                                                   >> 660 
                                                   >> 661   if (((fExportImageFormat == "eps") || (fExportImageFormat == "ps")) && (!fVectoredPs)) {
                                                   >> 662     res = printNonVectoredEPS();
                                                   >> 663   } else {
                                                   >> 664     res = printVectoredEPS();
                                                   >> 665   }
                                                   >> 666 
                                                   >> 667   // restore the local
                                                   >> 668   if (oldLocale) {
                                                   >> 669     setlocale(LC_NUMERIC,oldLocale);
                                                   >> 670     free(oldLocale);
                                                   >> 671   }
                                                   >> 672 
                                                   >> 673   if (res == false) {
                                                   >> 674     G4cerr << "Error saving file... " << getRealPrintFilename().c_str() << G4endl;
                                                   >> 675   } else {
                                                   >> 676     G4cout << "File " << getRealPrintFilename().c_str() << " size: " << getRealExportWidth() << "x" << getRealExportHeight() << " has been saved " << G4endl;
                                                   >> 677 
                                                   >> 678     // increment index if necessary
                                                   >> 679     if ( fExportFilenameIndex != -1) {
                                                   >> 680       fExportFilenameIndex++;
                                                   >> 681     }
                                                   >> 682   }
                                                   >> 683 
                                                   >> 684   return res;
                                                   >> 685 }
                                                   >> 686 
575 bool G4OpenGLViewer::printVectoredEPS() {         687 bool G4OpenGLViewer::printVectoredEPS() {
576   return printGl2PS();                            688   return printGl2PS();
577 }                                                 689 }
578                                                   690 
579 bool G4OpenGLViewer::printNonVectoredEPS () {     691 bool G4OpenGLViewer::printNonVectoredEPS () {
580                                                   692 
581   int width = getRealExportWidth();               693   int width = getRealExportWidth();
582   int height = getRealExportHeight();             694   int height = getRealExportHeight();
583                                                   695 
584   FILE* fp;                                       696   FILE* fp;
585   GLubyte* pixels;                                697   GLubyte* pixels;
586   GLubyte* curpix;                                698   GLubyte* curpix;
587   int components, pos, i;                         699   int components, pos, i;
588                                                   700 
589   pixels = grabPixels (fPrintColour, width, he    701   pixels = grabPixels (fPrintColour, width, height);
590                                                   702 
591   if (pixels == NULL) {                           703   if (pixels == NULL) {
592       G4cerr << "Failed to get pixels from Ope    704       G4cerr << "Failed to get pixels from OpenGl viewport" << G4endl;
593     return false;                                 705     return false;
594   }                                               706   }
595   if (fPrintColour) {                             707   if (fPrintColour) {
596     components = 3;                               708     components = 3;
597   } else {                                        709   } else {
598     components = 1;                               710     components = 1;
599   }                                               711   }
600   std::string name = getRealPrintFilename();      712   std::string name = getRealPrintFilename();
601   fp = fopen (name.c_str(), "w");                 713   fp = fopen (name.c_str(), "w");
602   if (fp == NULL) {                               714   if (fp == NULL) {
603     G4cerr << "Can't open filename " << name.c    715     G4cerr << "Can't open filename " << name.c_str() << G4endl;
604     return false;                                 716     return false;
605   }                                               717   }
606                                                   718   
607   fprintf (fp, "%%!PS-Adobe-2.0 EPSF-1.2\n");     719   fprintf (fp, "%%!PS-Adobe-2.0 EPSF-1.2\n");
608   fprintf (fp, "%%%%Title: %s\n", name.c_str()    720   fprintf (fp, "%%%%Title: %s\n", name.c_str());
609   fprintf (fp, "%%%%Creator: OpenGL pixmap ren    721   fprintf (fp, "%%%%Creator: OpenGL pixmap render output\n");
610   fprintf (fp, "%%%%BoundingBox: 0 0 %d %d\n",    722   fprintf (fp, "%%%%BoundingBox: 0 0 %d %d\n", width, height);
611   fprintf (fp, "%%%%EndComments\n");              723   fprintf (fp, "%%%%EndComments\n");
612   fprintf (fp, "gsave\n");                        724   fprintf (fp, "gsave\n");
613   fprintf (fp, "/bwproc {\n");                    725   fprintf (fp, "/bwproc {\n");
614   fprintf (fp, "    rgbproc\n");                  726   fprintf (fp, "    rgbproc\n");
615   fprintf (fp, "    dup length 3 idiv string 0    727   fprintf (fp, "    dup length 3 idiv string 0 3 0 \n");
616   fprintf (fp, "    5 -1 roll {\n");              728   fprintf (fp, "    5 -1 roll {\n");
617   fprintf (fp, "    add 2 1 roll 1 sub dup 0 e    729   fprintf (fp, "    add 2 1 roll 1 sub dup 0 eq\n");
618   fprintf (fp, "    { pop 3 idiv 3 -1 roll dup    730   fprintf (fp, "    { pop 3 idiv 3 -1 roll dup 4 -1 roll dup\n");
619   fprintf (fp, "       3 1 roll 5 -1 roll } pu    731   fprintf (fp, "       3 1 roll 5 -1 roll } put 1 add 3 0 \n");
620   fprintf (fp, "    { 2 1 roll } ifelse\n");      732   fprintf (fp, "    { 2 1 roll } ifelse\n");
621   fprintf (fp, "    }forall\n");                  733   fprintf (fp, "    }forall\n");
622   fprintf (fp, "    pop pop pop\n");              734   fprintf (fp, "    pop pop pop\n");
623   fprintf (fp, "} def\n");                        735   fprintf (fp, "} def\n");
624   fprintf (fp, "systemdict /colorimage known n    736   fprintf (fp, "systemdict /colorimage known not {\n");
625   fprintf (fp, "   /colorimage {\n");             737   fprintf (fp, "   /colorimage {\n");
626   fprintf (fp, "       pop\n");                   738   fprintf (fp, "       pop\n");
627   fprintf (fp, "       pop\n");                   739   fprintf (fp, "       pop\n");
628   fprintf (fp, "       /rgbproc exch def\n");     740   fprintf (fp, "       /rgbproc exch def\n");
629   fprintf (fp, "       { bwproc } image\n");      741   fprintf (fp, "       { bwproc } image\n");
630   fprintf (fp, "   }  def\n");                    742   fprintf (fp, "   }  def\n");
631   fprintf (fp, "} if\n");                         743   fprintf (fp, "} if\n");
632   fprintf (fp, "/picstr %d string def\n", widt    744   fprintf (fp, "/picstr %d string def\n", width * components);
633   fprintf (fp, "%d %d scale\n", width, height)    745   fprintf (fp, "%d %d scale\n", width, height);
634   fprintf (fp, "%d %d %d\n", width, height, 8)    746   fprintf (fp, "%d %d %d\n", width, height, 8);
635   fprintf (fp, "[%d 0 0 %d 0 0]\n", width, hei    747   fprintf (fp, "[%d 0 0 %d 0 0]\n", width, height);
636   fprintf (fp, "{currentfile picstr readhexstr    748   fprintf (fp, "{currentfile picstr readhexstring pop}\n");
637   fprintf (fp, "false %d\n", components);         749   fprintf (fp, "false %d\n", components);
638   fprintf (fp, "colorimage\n");                   750   fprintf (fp, "colorimage\n");
639                                                   751   
640   curpix = (GLubyte*) pixels;                     752   curpix = (GLubyte*) pixels;
641   pos = 0;                                        753   pos = 0;
642   for (i = width*height*components; i>0; i--)     754   for (i = width*height*components; i>0; i--) {
643     fprintf (fp, "%02hx ", (unsigned short)(*(    755     fprintf (fp, "%02hx ", (unsigned short)(*(curpix++)));
644     if (++pos >= 32) {                            756     if (++pos >= 32) {
645       fprintf (fp, "\n");                         757       fprintf (fp, "\n");
646       pos = 0;                                    758       pos = 0; 
647     }                                             759     }
648   }                                               760   }
649   if (pos)                                        761   if (pos)
650     fprintf (fp, "\n");                           762     fprintf (fp, "\n");
651                                                   763 
652   fprintf (fp, "grestore\n");                     764   fprintf (fp, "grestore\n");
653   fprintf (fp, "showpage\n");                     765   fprintf (fp, "showpage\n");
654   delete [] pixels;                               766   delete [] pixels;
655   fclose (fp);                                    767   fclose (fp);
656                                                   768 
657   // Reset for next time (useful if size chang << 769   // Reset for next time (useful is size change)
658   //  fPrintSizeX = -1;                           770   //  fPrintSizeX = -1;
659   //  fPrintSizeY = -1;                           771   //  fPrintSizeY = -1;
660                                                   772 
661   return true;                                    773   return true;
662 }                                                 774 }
663                                                   775 
664 /** Return if gl2ps is currently writing          776 /** Return if gl2ps is currently writing
665  */                                               777  */
666 bool G4OpenGLViewer::isGl2psWriting() {           778 bool G4OpenGLViewer::isGl2psWriting() {
667                                                   779 
668   if (!fGL2PSAction) return false;                780   if (!fGL2PSAction) return false;
669   if (fGL2PSAction->fileWritingEnabled()) {       781   if (fGL2PSAction->fileWritingEnabled()) {
670     return true;                                  782     return true;
671   }                                               783   }
672   return false;                                   784   return false;
673 }                                                 785 }
674                                                   786 
675                                                   787 
676 G4bool G4OpenGLViewer::isFramebufferReady() {     788 G4bool G4OpenGLViewer::isFramebufferReady() {
677   bool check = false;                             789   bool check = false;
678 #ifdef G4VIS_BUILD_OPENGLQT_DRIVER                790 #ifdef G4VIS_BUILD_OPENGLQT_DRIVER
679   check = true;                                   791   check = true;
680 #endif                                            792 #endif
681 #ifdef G4VIS_BUILD_OPENGLX_DRIVER                 793 #ifdef G4VIS_BUILD_OPENGLX_DRIVER
682   check = false;                                  794   check = false;
683 #endif                                            795 #endif
684 #ifdef G4VIS_BUILD_OPENGLXM_DRIVER                796 #ifdef G4VIS_BUILD_OPENGLXM_DRIVER
685   check = false;                                  797   check = false;
686 #endif                                            798 #endif
687 #ifdef G4VIS_BUILD_OPENGLWIN32_DRIVER             799 #ifdef G4VIS_BUILD_OPENGLWIN32_DRIVER
688   check = false;                                  800   check = false;
689 #endif                                            801 #endif
690                                                   802 
691 #if GL_ARB_framebuffer_object                     803 #if GL_ARB_framebuffer_object
692   if (check) {                                    804   if (check) {
693 //    if ( glCheckFramebufferStatus(GL_FRAMEBU    805 //    if ( glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_UNDEFINED) {
694 //      return false;                             806 //      return false;
695 //    }                                           807 //    }
696   }                                               808   }
697 #endif                                            809 #endif
698     return true;                                  810     return true;
699 }                                                 811 }
700                                                   812 
701                                                   813 
702 /* Draw Gl2Ps text if needed                      814 /* Draw Gl2Ps text if needed
703  */                                               815  */
704 void G4OpenGLViewer::DrawText(const G4Text& g4    816 void G4OpenGLViewer::DrawText(const G4Text& g4text)
705 {                                                 817 {
706   // gl2ps or GL window ?                         818   // gl2ps or GL window ?
707   if (isGl2psWriting()) {                         819   if (isGl2psWriting()) {
708                                                   820 
709     G4VSceneHandler::MarkerSizeType sizeType;     821     G4VSceneHandler::MarkerSizeType sizeType;
710     G4double size = fSceneHandler.GetMarkerSiz    822     G4double size = fSceneHandler.GetMarkerSize(g4text,sizeType);
711     G4Point3D position = g4text.GetPosition();    823     G4Point3D position = g4text.GetPosition();
712                                                   824 
713     G4String textString = g4text.GetText();       825     G4String textString = g4text.GetText();
714                                                   826     
715     glRasterPos3d(position.x(),position.y(),po    827     glRasterPos3d(position.x(),position.y(),position.z());
716     GLint align = GL2PS_TEXT_B;                   828     GLint align = GL2PS_TEXT_B;
717                                                   829 
718     switch (g4text.GetLayout()) {                 830     switch (g4text.GetLayout()) {
719     case G4Text::left: align = GL2PS_TEXT_BL;     831     case G4Text::left: align = GL2PS_TEXT_BL; break;
720     case G4Text::centre: align = GL2PS_TEXT_B;    832     case G4Text::centre: align = GL2PS_TEXT_B; break;
721     case G4Text::right: align = GL2PS_TEXT_BR;    833     case G4Text::right: align = GL2PS_TEXT_BR;
722     }                                             834     }
723                                                   835     
724     fGL2PSAction->addTextOpt(textString.c_str( << 836     gl2psTextOpt(textString.c_str(),"Times-Roman",GLshort(size),align,0);
725                                                   837 
726   } else {                                        838   } else {
727                                                   839 
728     static G4int callCount = 0;                   840     static G4int callCount = 0;
729     ++callCount;                                  841     ++callCount;
730     //if (callCount <= 10 || callCount%100 ==     842     //if (callCount <= 10 || callCount%100 == 0) {
731     if (callCount <= 1) {                         843     if (callCount <= 1) {
732       G4cout <<                                   844       G4cout <<
733   "G4OpenGLViewer::DrawText: Not implemented f    845   "G4OpenGLViewer::DrawText: Not implemented for \""
734        << fName <<                                846        << fName <<
735   "\"\n  Called with "                            847   "\"\n  Called with "
736        << g4text                                  848        << g4text
737        << G4endl;                                 849        << G4endl;
738     }                                             850     }
739   }                                               851   }
740 }                                                 852 }
741                                                   853 
742 /** Change PointSize on gl2ps if needed           854 /** Change PointSize on gl2ps if needed
743  */                                               855  */
744 void G4OpenGLViewer::ChangePointSize(G4double     856 void G4OpenGLViewer::ChangePointSize(G4double size) {
745                                                   857 
746   if (isGl2psWriting()) {                         858   if (isGl2psWriting()) {
747     fGL2PSAction->setPointSize(int(size));        859     fGL2PSAction->setPointSize(int(size));
748   } else {                                        860   } else {
749     glPointSize (size);                           861     glPointSize (size);
750   }                                               862   }
751 }                                                 863 }
752                                                   864 
753                                                   865 
754 /** Change LineSize on gl2ps if needed            866 /** Change LineSize on gl2ps if needed
755  */                                               867  */
756 void G4OpenGLViewer::ChangeLineWidth(G4double     868 void G4OpenGLViewer::ChangeLineWidth(G4double width) {
757                                                   869 
758   if (isGl2psWriting()) {                         870   if (isGl2psWriting()) {
759     fGL2PSAction->setLineWidth(int(width));       871     fGL2PSAction->setLineWidth(int(width));
760   } else {                                        872   } else {
761     glLineWidth (width);                          873     glLineWidth (width);
762   }                                               874   }
763 }                                                 875 }
764                                                   876 
765 /**                                               877 /**
766  Export image with the given name with width a    878  Export image with the given name with width and height
767  Several cases :                                  879  Several cases :
768  If name is "", filename will have the default    880  If name is "", filename will have the default value
769  If name is "toto.png", set the name to "toto"    881  If name is "toto.png", set the name to "toto" and the format to "png". No incremented suffix is added.
770  If name is "toto", set the name to "toto" and    882  If name is "toto", set the name to "toto" and the format to default (or current format if specify).
771    Will also add an incremented suffix at the     883    Will also add an incremented suffix at the end of the file
772 */                                                884 */
773 bool G4OpenGLViewer::exportImage(std::string n    885 bool G4OpenGLViewer::exportImage(std::string name, int width, int height) {
774                                                   886 
775   if (! setExportFilename(name)) {                887   if (! setExportFilename(name)) {
776     return false;                                 888     return false;
777   }                                               889   }
778                                                   890 
779   if ((width != -1) && (height != -1)) {          891   if ((width != -1) && (height != -1)) {
780     setExportSize(width, height);                 892     setExportSize(width, height);
781   }                                               893   }
782                                                   894 
783   if (fExportImageFormat == "eps") {              895   if (fExportImageFormat == "eps") {
784     fGL2PSAction->setExportImageFormat_EPS();  << 896     fGL2PSAction->setExportImageFormat(GL2PS_EPS);
785   } else if (fExportImageFormat == "ps") {        897   } else if (fExportImageFormat == "ps") {
786     fGL2PSAction->setExportImageFormat_PS();   << 898     fGL2PSAction->setExportImageFormat(GL2PS_PS);
787   } else if (fExportImageFormat == "svg") {       899   } else if (fExportImageFormat == "svg") {
788     fGL2PSAction->setExportImageFormat_SVG();  << 900     fGL2PSAction->setExportImageFormat(GL2PS_SVG);
789   } else if (fExportImageFormat == "pdf") {       901   } else if (fExportImageFormat == "pdf") {
790     fGL2PSAction->setExportImageFormat_PDF();  << 902     fGL2PSAction->setExportImageFormat(GL2PS_PDF);
791   } else {                                        903   } else {
792     setExportImageFormat(fExportImageFormat,tr    904     setExportImageFormat(fExportImageFormat,true); // will display a message if this format is not correct for the current viewer
793     return false;                                 905     return false;
794   }                                               906   }
795                                                << 907   return printEPS();
796   bool res;                                    << 
797                                                << 
798   // Change the LC_NUMERIC value in order to h << 
799   // This case is only useful for French, Cana << 
800   size_t len = strlen(setlocale(LC_NUMERIC,NUL << 
801   char* oldLocale = (char*)(malloc(len+1));    << 
802   if(oldLocale!=NULL) strncpy(oldLocale,setloc << 
803   setlocale(LC_NUMERIC,"C");                   << 
804                                                << 
805   if (((fExportImageFormat == "eps") || (fExpo << 
806     res = printNonVectoredEPS();               << 
807   } else {                                     << 
808     res = printVectoredEPS();                  << 
809   }                                            << 
810                                                << 
811   // restore the local                         << 
812   if (oldLocale) {                             << 
813     setlocale(LC_NUMERIC,oldLocale);           << 
814     free(oldLocale);                           << 
815   }                                            << 
816                                                << 
817   if (res == false) {                          << 
818     G4cerr << "Error saving file... " << getRe << 
819   } else {                                     << 
820     G4cout << "File " << getRealPrintFilename( << 
821                                                << 
822     // increment index if necessary            << 
823     if ( fExportFilenameIndex != -1) {         << 
824       fExportFilenameIndex++;                  << 
825     }                                          << 
826   }                                            << 
827                                                << 
828   return res;                                  << 
829 }                                                 908 }
830                                                   909 
831                                                   910 
832 bool G4OpenGLViewer::printGl2PS() {               911 bool G4OpenGLViewer::printGl2PS() {
833                                                   912 
834   int width = getRealExportWidth();               913   int width = getRealExportWidth();
835   int height = getRealExportHeight();             914   int height = getRealExportHeight();
836   bool res = true;                                915   bool res = true;
837                                                   916 
838   // no need to redraw at each new primitive f    917   // no need to redraw at each new primitive for printgl2PS
839   G4OpenGLSceneHandler& oglSceneHandler = dyna    918   G4OpenGLSceneHandler& oglSceneHandler = dynamic_cast<G4OpenGLSceneHandler&>(fSceneHandler);
840   G4OpenGLSceneHandler::FlushAction originalFl    919   G4OpenGLSceneHandler::FlushAction originalFlushAction = oglSceneHandler.GetFlushAction();
841   oglSceneHandler.SetFlushAction(G4OpenGLScene    920   oglSceneHandler.SetFlushAction(G4OpenGLSceneHandler::never);
842                                                   921 
843   if (!fGL2PSAction) return false;                922   if (!fGL2PSAction) return false;
844                                                   923 
845   fGL2PSAction->setFileName(getRealPrintFilena    924   fGL2PSAction->setFileName(getRealPrintFilename().c_str());
846   // try to resize                                925   // try to resize
847   int X = fWinSize_x;                             926   int X = fWinSize_x;
848   int Y = fWinSize_y;                             927   int Y = fWinSize_y;
849                                                   928 
850   fWinSize_x = width;                             929   fWinSize_x = width;
851   fWinSize_y = height;                            930   fWinSize_y = height;
852   // Laurent G. 16/03/10 : Not the good way to    931   // Laurent G. 16/03/10 : Not the good way to do. 
853   // We should draw in a new offscreen context    932   // We should draw in a new offscreen context instead of
854   // resizing and drawing in current window...    933   // resizing and drawing in current window...
855   // This should be solve when we will do an o    934   // This should be solve when we will do an offscreen method
856   // to render OpenGL                             935   // to render OpenGL
857   // See :                                        936   // See : 
858   // http://developer.apple.com/Mac/library/do    937   // http://developer.apple.com/Mac/library/documentation/GraphicsImaging/Conceptual/OpenGL-MacProgGuide/opengl_offscreen/opengl_offscreen.html
859   // http://www.songho.ca/opengl/gl_fbo.html      938   // http://www.songho.ca/opengl/gl_fbo.html
860                                                   939 
861    ResizeGLView();                                940    ResizeGLView();
862    bool extendBuffer = true;                      941    bool extendBuffer = true;
863    bool endWriteAction = false;                   942    bool endWriteAction = false;
864    bool beginWriteAction = true;                  943    bool beginWriteAction = true;
865    bool filePointerOk = true;                     944    bool filePointerOk = true;
866    while ((extendBuffer) && (! endWriteAction)    945    while ((extendBuffer) && (! endWriteAction) && (filePointerOk)) {
867                                                << 946      
868      beginWriteAction = fGL2PSAction->enableFi    947      beginWriteAction = fGL2PSAction->enableFileWriting();
869      if(beginWriteAction) {                    << 
870        GLint vp[4];                            << 
871        ::glGetIntegerv(GL_VIEWPORT,vp);        << 
872        fGL2PSAction->setViewport(vp[0],vp[1],v << 
873        beginWriteAction = fGL2PSAction->beginP << 
874      }                                         << 
875                                                << 
876      // 3 cases :                                 948      // 3 cases :
877      // - true                                    949      // - true
878      // - false && ! fGL2PSAction->fileWriting    950      // - false && ! fGL2PSAction->fileWritingEnabled() => bad file name
879      // - false && fGL2PSAction->fileWritingEn    951      // - false && fGL2PSAction->fileWritingEnabled() => buffer size problem ?
880                                                   952 
881      filePointerOk = fGL2PSAction->fileWriting    953      filePointerOk = fGL2PSAction->fileWritingEnabled();
882                                                   954        
883      if (beginWriteAction) {                      955      if (beginWriteAction) {
884                                                << 956        
885        // Set the viewport                        957        // Set the viewport
886        // By default, we choose the line width    958        // By default, we choose the line width (trajectories...)
887        fGL2PSAction->setLineWidth(fGl2psDefaul    959        fGL2PSAction->setLineWidth(fGl2psDefaultLineWith);
888        // By default, we choose the point size    960        // By default, we choose the point size (markers...)
889        fGL2PSAction->setPointSize(fGl2psDefaul    961        fGL2PSAction->setPointSize(fGl2psDefaultPointSize);
890                                                   962        
891        DrawView ();                               963        DrawView ();
892                                                << 964        endWriteAction = fGL2PSAction->disableFileWriting();
893        endWriteAction = fGL2PSAction->endPage( << 
894        fGL2PSAction->disableFileWriting();     << 
895      }                                            965      }
896      if (filePointerOk) {                         966      if (filePointerOk) {
897        if ((! endWriteAction) || (! beginWrite    967        if ((! endWriteAction) || (! beginWriteAction)) {
898          extendBuffer = fGL2PSAction->extendBu    968          extendBuffer = fGL2PSAction->extendBufferSize();
899        }                                          969        }
900      }                                            970      }
901    }                                              971    }
902    fGL2PSAction->resetBufferSizeParameters();     972    fGL2PSAction->resetBufferSizeParameters();
903                                                   973 
904    if (!extendBuffer ) {                          974    if (!extendBuffer ) {
905      G4cerr << "ERROR: gl2ps buffer size is no    975      G4cerr << "ERROR: gl2ps buffer size is not big enough to print this geometry. Try to extend it. No output produced"<< G4endl;
906      res = false;                                 976      res = false;
907    }                                              977    }
908    if (!beginWriteAction ) {                      978    if (!beginWriteAction ) {
909      G4cerr << "ERROR: saving file "<<getRealP    979      G4cerr << "ERROR: saving file "<<getRealPrintFilename().c_str()<<". Check read/write access. No output produced" << G4endl;
910      res = false;                                 980      res = false;
911    }                                              981    }
912    if (!endWriteAction ) {                        982    if (!endWriteAction ) {
913      G4cerr << "gl2ps error. No output produce    983      G4cerr << "gl2ps error. No output produced" << G4endl;
914      res = false;                                 984      res = false;
915    }                                              985    }
916   fWinSize_x = X;                                 986   fWinSize_x = X;
917   fWinSize_y = Y;                                 987   fWinSize_y = Y;
918                                                   988 
919   oglSceneHandler.SetFlushAction(originalFlush    989   oglSceneHandler.SetFlushAction(originalFlushAction);
920                                                   990 
921   // Reset for next time (useful is size chang    991   // Reset for next time (useful is size change)
922   //  fPrintSizeX = 0;                            992   //  fPrintSizeX = 0;
923   //  fPrintSizeY = 0;                            993   //  fPrintSizeY = 0;
924                                                   994 
925   return res;                                     995   return res;
926 }                                                 996 }
927                                                   997 
928 unsigned int G4OpenGLViewer::getWinWidth() con    998 unsigned int G4OpenGLViewer::getWinWidth() const{
929   return fWinSize_x;                              999   return fWinSize_x;
930 }                                                 1000 }
931                                                   1001 
932 unsigned int G4OpenGLViewer::getWinHeight() co    1002 unsigned int G4OpenGLViewer::getWinHeight() const{
933   return fWinSize_y;                              1003   return fWinSize_y;
934 }                                                 1004 }
935                                                   1005 
936 G4bool G4OpenGLViewer::sizeHasChanged() {         1006 G4bool G4OpenGLViewer::sizeHasChanged() {
937   return fSizeHasChanged;                         1007   return fSizeHasChanged;
938 }                                                 1008 }
939                                                   1009 
940 G4int G4OpenGLViewer::getRealExportWidth() {      1010 G4int G4OpenGLViewer::getRealExportWidth() {
941   if (fPrintSizeX == -1) {                        1011   if (fPrintSizeX == -1) {
942     return fWinSize_x;                            1012     return fWinSize_x;
943   }                                               1013   }
944   GLint dims[2];                                  1014   GLint dims[2];
945   glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);      1015   glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);
946                                                   1016 
947   // L.Garnier 01-2010: Some problems with mac    1017   // L.Garnier 01-2010: Some problems with mac 10.6
948   if ((dims[0] !=0 ) && (dims[1] !=0)) {          1018   if ((dims[0] !=0 ) && (dims[1] !=0)) {
949     if (fPrintSizeX > dims[0]){                   1019     if (fPrintSizeX > dims[0]){
950       return dims[0];                             1020       return dims[0];
951     }                                             1021     }
952   }                                               1022   }
953   if (fPrintSizeX < -1){                          1023   if (fPrintSizeX < -1){
954     return 0;                                     1024     return 0;
955   }                                               1025   }
956   return fPrintSizeX;                             1026   return fPrintSizeX;
957 }                                                 1027 }
958                                                   1028 
959 G4int G4OpenGLViewer::getRealExportHeight() {     1029 G4int G4OpenGLViewer::getRealExportHeight() {
960   if (fPrintSizeY == -1) {                        1030   if (fPrintSizeY == -1) {
961     return fWinSize_y;                            1031     return fWinSize_y;
962   }                                               1032   }
963   GLint dims[2];                                  1033   GLint dims[2];
964   glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);      1034   glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);
965                                                   1035 
966   // L.Garnier 01-2010: Some problems with mac    1036   // L.Garnier 01-2010: Some problems with mac 10.6
967   if ((dims[0] !=0 ) && (dims[1] !=0)) {          1037   if ((dims[0] !=0 ) && (dims[1] !=0)) {
968     if (fPrintSizeY > dims[1]){                   1038     if (fPrintSizeY > dims[1]){
969       return dims[1];                             1039       return dims[1];
970     }                                             1040     }
971   }                                               1041   }
972   if (fPrintSizeY < -1){                          1042   if (fPrintSizeY < -1){
973     return 0;                                     1043     return 0;
974   }                                               1044   }
975   return fPrintSizeY;                             1045   return fPrintSizeY;
976 }                                                 1046 }
977                                                   1047 
978 void G4OpenGLViewer::setExportSize(G4int X, G4    1048 void G4OpenGLViewer::setExportSize(G4int X, G4int Y) {
979   fPrintSizeX = X;                                1049   fPrintSizeX = X;
980   fPrintSizeY = Y;                                1050   fPrintSizeY = Y;
981 }                                                 1051 }
982                                                   1052 
983 /**                                               1053 /**
984  If name is "" or "!", filename and extension     1054  If name is "" or "!", filename and extension will have the default value.
985  If name is "toto.png", set the name to "toto"    1055  If name is "toto.png", set the name to "toto" and the format to "png". No incremented suffix is added.
986  If name is "toto", set the name to "toto" and    1056  If name is "toto", set the name to "toto" and the format to default (or current format if specify).
987  If name is the same as previous, do not reset    1057  If name is the same as previous, do not reset incremented suffix.
988 */                                                1058 */
989 bool G4OpenGLViewer::setExportFilename(G4Strin    1059 bool G4OpenGLViewer::setExportFilename(G4String name,G4bool inc) {
990   if (name == "!") {                              1060   if (name == "!") {
991     name = "";                                    1061     name = "";
992   }                                               1062   }
993                                                   1063 
994   if (inc) {                                      1064   if (inc) {
995     if ((name != "") && (fExportFilename != na    1065     if ((name != "") && (fExportFilename != name)) {
996       fExportFilenameIndex=0;                     1066       fExportFilenameIndex=0;
997     }                                             1067     }
998   } else {                                        1068   } else {
999     fExportFilenameIndex=-1;                      1069     fExportFilenameIndex=-1;
1000   }                                              1070   }
1001                                                  1071 
1002   if (name.size() == 0) {                        1072   if (name.size() == 0) {
1003     name = getRealPrintFilename().c_str();       1073     name = getRealPrintFilename().c_str();
1004   } else {                                       1074   } else {
1005     // guess format by extention                 1075     // guess format by extention
1006     std::string extension = name.substr(name.    1076     std::string extension = name.substr(name.find_last_of(".") + 1);
1007     // If there is a dot in the name the abov << 1077     // no format
1008     if (extension.size() >= 3 && extension.si << 1078     if (name.size() != extension.size()) {
1009       if (setExportImageFormat(extension, fal << 1079       if (! setExportImageFormat(extension, false)) {
1010         fExportFilename = name.substr(0,name. << 
1011       } else {  // No viable extension found  << 
1012         return false;                            1080         return false;
1013       }                                          1081       }
1014     } else {  // Assume name is already the r << 
1015         fExportFilename = name;               << 
1016     }                                            1082     }
                                                   >> 1083     // get the name
                                                   >> 1084     fExportFilename = name.substr(0,name.find_last_of("."));
1017   }                                              1085   }
1018   return true;                                   1086   return true;
1019 }                                                1087 }
1020                                                  1088 
1021 std::string G4OpenGLViewer::getRealPrintFilen    1089 std::string G4OpenGLViewer::getRealPrintFilename() {
1022   std::string temp = fExportFilename;            1090   std::string temp = fExportFilename;
1023   if (fExportFilenameIndex != -1) {              1091   if (fExportFilenameIndex != -1) {
1024     temp += std::string("_");                    1092     temp += std::string("_");
1025     std::ostringstream os;                       1093     std::ostringstream os;
1026     os << std::setw(4) << std::setfill('0') <    1094     os << std::setw(4) << std::setfill('0') << fExportFilenameIndex;
1027     std::string nb_str = os.str();               1095     std::string nb_str = os.str();
1028     temp += nb_str;                              1096     temp += nb_str;
1029   }                                              1097   }
1030   temp += "."+fExportImageFormat;                1098   temp += "."+fExportImageFormat;
1031   return temp;                                   1099   return temp;
1032 }                                                1100 }
1033                                                  1101 
1034 GLdouble G4OpenGLViewer::getSceneNearWidth()     1102 GLdouble G4OpenGLViewer::getSceneNearWidth()
1035 {                                                1103 {
1036   if (!fSceneHandler.GetScene()) {               1104   if (!fSceneHandler.GetScene()) {
1037     return 0;                                    1105     return 0;
1038   }                                              1106   }
1039   const G4Point3D targetPoint                    1107   const G4Point3D targetPoint
1040     = fSceneHandler.GetScene()->GetStandardTa    1108     = fSceneHandler.GetScene()->GetStandardTargetPoint()
1041     + fVP.GetCurrentTargetPoint ();              1109     + fVP.GetCurrentTargetPoint ();
1042   G4double radius = fSceneHandler.GetScene()-    1110   G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
1043   if(radius<=0.) radius = 1.;                    1111   if(radius<=0.) radius = 1.;
1044   const G4double cameraDistance = fVP.GetCame    1112   const G4double cameraDistance = fVP.GetCameraDistance (radius);
1045   const GLdouble pnear   = fVP.GetNearDistanc    1113   const GLdouble pnear   = fVP.GetNearDistance (cameraDistance, radius);
1046   return 2 * fVP.GetFrontHalfHeight (pnear, r    1114   return 2 * fVP.GetFrontHalfHeight (pnear, radius);
1047 }                                                1115 }
1048                                                  1116 
1049 GLdouble G4OpenGLViewer::getSceneFarWidth()      1117 GLdouble G4OpenGLViewer::getSceneFarWidth()
1050 {                                                1118 {
1051   if (!fSceneHandler.GetScene()) {               1119   if (!fSceneHandler.GetScene()) {
1052     return 0;                                    1120     return 0;
1053   }                                              1121   }
1054   const G4Point3D targetPoint                    1122   const G4Point3D targetPoint
1055     = fSceneHandler.GetScene()->GetStandardTa    1123     = fSceneHandler.GetScene()->GetStandardTargetPoint()
1056     + fVP.GetCurrentTargetPoint ();              1124     + fVP.GetCurrentTargetPoint ();
1057   G4double radius = fSceneHandler.GetScene()-    1125   G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
1058   if(radius<=0.) radius = 1.;                    1126   if(radius<=0.) radius = 1.;
1059   const G4double cameraDistance = fVP.GetCame    1127   const G4double cameraDistance = fVP.GetCameraDistance (radius);
1060   const GLdouble pnear   = fVP.GetNearDistanc    1128   const GLdouble pnear   = fVP.GetNearDistance (cameraDistance, radius);
1061   const GLdouble pfar    = fVP.GetFarDistance    1129   const GLdouble pfar    = fVP.GetFarDistance  (cameraDistance, pnear, radius);
1062   return 2 * fVP.GetFrontHalfHeight (pfar, ra    1130   return 2 * fVP.GetFrontHalfHeight (pfar, radius);
1063 }                                                1131 }
1064                                                  1132 
1065                                                  1133 
1066 GLdouble G4OpenGLViewer::getSceneDepth()         1134 GLdouble G4OpenGLViewer::getSceneDepth()
1067 {                                                1135 {
1068   if (!fSceneHandler.GetScene()) {               1136   if (!fSceneHandler.GetScene()) {
1069     return 0;                                    1137     return 0;
1070   }                                              1138   }
1071   const G4Point3D targetPoint                    1139   const G4Point3D targetPoint
1072     = fSceneHandler.GetScene()->GetStandardTa    1140     = fSceneHandler.GetScene()->GetStandardTargetPoint()
1073     + fVP.GetCurrentTargetPoint ();              1141     + fVP.GetCurrentTargetPoint ();
1074   G4double radius = fSceneHandler.GetScene()-    1142   G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
1075   if(radius<=0.) radius = 1.;                    1143   if(radius<=0.) radius = 1.;
1076   const G4double cameraDistance = fVP.GetCame    1144   const G4double cameraDistance = fVP.GetCameraDistance (radius);
1077   const GLdouble pnear   = fVP.GetNearDistanc    1145   const GLdouble pnear   = fVP.GetNearDistance (cameraDistance, radius);
1078   return fVP.GetFarDistance  (cameraDistance,    1146   return fVP.GetFarDistance  (cameraDistance, pnear, radius)- pnear;
1079 }                                                1147 }
1080                                                  1148 
1081                                                  1149 
1082                                                  1150 
1083 void G4OpenGLViewer::rotateScene(G4double dx,    1151 void G4OpenGLViewer::rotateScene(G4double dx, G4double dy)
1084 {                                                1152 {
1085   if (fVP.GetRotationStyle() == G4ViewParamet    1153   if (fVP.GetRotationStyle() == G4ViewParameters::freeRotation) {
1086     rotateSceneInViewDirection(dx,dy);           1154     rotateSceneInViewDirection(dx,dy);
1087   } else {                                       1155   } else {
1088     if( dx != 0) {                               1156     if( dx != 0) {
1089       rotateSceneThetaPhi(dx,0);                 1157       rotateSceneThetaPhi(dx,0);
1090     }                                            1158     }
1091     if( dy != 0) {                               1159     if( dy != 0) {
1092       rotateSceneThetaPhi(0,dy);                 1160       rotateSceneThetaPhi(0,dy);
1093     }                                            1161     }
1094   }                                              1162   }
1095 }                                                1163 }
1096                                                  1164 
1097                                                  1165 
1098 void G4OpenGLViewer::rotateSceneToggle(G4doub    1166 void G4OpenGLViewer::rotateSceneToggle(G4double dx, G4double dy)
1099 {                                                1167 {
1100   if (fVP.GetRotationStyle() != G4ViewParamet    1168   if (fVP.GetRotationStyle() != G4ViewParameters::freeRotation) {
1101     rotateSceneInViewDirection(dx,dy);           1169     rotateSceneInViewDirection(dx,dy);
1102   } else {                                       1170   } else {
1103     if( dx != 0) {                               1171     if( dx != 0) {
1104       rotateSceneThetaPhi(dx,0);                 1172       rotateSceneThetaPhi(dx,0);
1105     }                                            1173     }
1106     if( dy != 0) {                               1174     if( dy != 0) {
1107       rotateSceneThetaPhi(0,dy);                 1175       rotateSceneThetaPhi(0,dy);
1108     }                                            1176     }
1109   }                                              1177   }
1110 }                                                1178 }
1111                                                  1179 
1112 void G4OpenGLViewer::rotateSceneThetaPhi(G4do    1180 void G4OpenGLViewer::rotateSceneThetaPhi(G4double dx, G4double dy)
1113 {                                                1181 {
1114   if (!fSceneHandler.GetScene()) {               1182   if (!fSceneHandler.GetScene()) {
1115     return;                                      1183     return;
1116   }                                              1184   }
1117                                                  1185 
1118   G4Vector3D vp;                                 1186   G4Vector3D vp;
1119   G4Vector3D up;                                 1187   G4Vector3D up;
1120                                                  1188   
1121   G4Vector3D xprime;                             1189   G4Vector3D xprime;
1122   G4Vector3D yprime;                             1190   G4Vector3D yprime;
1123   G4Vector3D zprime;                             1191   G4Vector3D zprime;
1124                                                  1192   
1125   G4double delta_alpha;                          1193   G4double delta_alpha;
1126   G4double delta_theta;                          1194   G4double delta_theta;
1127                                                  1195   
1128   G4Vector3D new_vp;                             1196   G4Vector3D new_vp;
1129   G4Vector3D new_up;                             1197   G4Vector3D new_up;
1130                                                  1198   
1131   G4double cosalpha;                             1199   G4double cosalpha;
1132   G4double sinalpha;                             1200   G4double sinalpha;
1133                                                  1201   
1134   G4Vector3D a1;                                 1202   G4Vector3D a1;
1135   G4Vector3D a2;                                 1203   G4Vector3D a2;
1136   G4Vector3D delta;                              1204   G4Vector3D delta;
1137   G4Vector3D viewPoint;                          1205   G4Vector3D viewPoint;
1138                                                  1206 
1139                                                  1207     
1140   //phi spin stuff here                          1208   //phi spin stuff here
1141                                                  1209   
1142   vp = fVP.GetViewpointDirection ().unit ();     1210   vp = fVP.GetViewpointDirection ().unit ();
1143   up = fVP.GetUpVector ().unit ();               1211   up = fVP.GetUpVector ().unit ();
1144                                                  1212   
1145   yprime = (up.cross(vp)).unit();                1213   yprime = (up.cross(vp)).unit();
1146   zprime = (vp.cross(yprime)).unit();            1214   zprime = (vp.cross(yprime)).unit();
1147                                                  1215   
1148   if (fVP.GetLightsMoveWithCamera()) {           1216   if (fVP.GetLightsMoveWithCamera()) {
1149     delta_alpha = dy * fRot_sens;                1217     delta_alpha = dy * fRot_sens;
1150     delta_theta = -dx * fRot_sens;               1218     delta_theta = -dx * fRot_sens;
1151   } else {                                       1219   } else {
1152     delta_alpha = -dy * fRot_sens;               1220     delta_alpha = -dy * fRot_sens;
1153     delta_theta = dx * fRot_sens;                1221     delta_theta = dx * fRot_sens;
1154   }                                              1222   }    
1155                                                  1223   
1156   delta_alpha *= CLHEP::deg;                  << 1224   delta_alpha *= deg;
1157   delta_theta *= CLHEP::deg;                  << 1225   delta_theta *= deg;
1158                                                  1226   
1159   new_vp = std::cos(delta_alpha) * vp + std::    1227   new_vp = std::cos(delta_alpha) * vp + std::sin(delta_alpha) * zprime;
1160                                                  1228   
1161   // to avoid z rotation flipping                1229   // to avoid z rotation flipping
1162   // to allow more than 360° rotation        << 1230   // to allow more than 360∞ rotation
1163                                                  1231 
1164   if (fVP.GetLightsMoveWithCamera()) {           1232   if (fVP.GetLightsMoveWithCamera()) {
1165     new_up = (new_vp.cross(yprime)).unit();      1233     new_up = (new_vp.cross(yprime)).unit();
1166     if (new_vp.z()*vp.z() <0) {                  1234     if (new_vp.z()*vp.z() <0) {
1167       new_up.set(new_up.x(),-new_up.y(),new_u    1235       new_up.set(new_up.x(),-new_up.y(),new_up.z());
1168     }                                            1236     }
1169   } else {                                       1237   } else {
1170     new_up = up;                                 1238     new_up = up;
1171     if (new_vp.z()*vp.z() <0) {                  1239     if (new_vp.z()*vp.z() <0) {
1172       new_up.set(new_up.x(),-new_up.y(),new_u    1240       new_up.set(new_up.x(),-new_up.y(),new_up.z());
1173     }                                            1241     }
1174   }                                              1242   }
1175   fVP.SetUpVector(new_up);                       1243   fVP.SetUpVector(new_up);
1176   ////////////////                               1244   ////////////////
1177   // Rotates by fixed azimuthal angle delta_t    1245   // Rotates by fixed azimuthal angle delta_theta.
1178                                                  1246   
1179   cosalpha = new_up.dot (new_vp.unit());         1247   cosalpha = new_up.dot (new_vp.unit());
1180   sinalpha = std::sqrt (1. - std::pow (cosalp    1248   sinalpha = std::sqrt (1. - std::pow (cosalpha, 2));
1181   yprime = (new_up.cross (new_vp.unit())).uni    1249   yprime = (new_up.cross (new_vp.unit())).unit ();
1182   xprime = yprime.cross (new_up);                1250   xprime = yprime.cross (new_up);
1183   // Projection of vp on plane perpendicular     1251   // Projection of vp on plane perpendicular to up...
1184   a1 = sinalpha * xprime;                        1252   a1 = sinalpha * xprime;
1185   // Required new projection...                  1253   // Required new projection...
1186   a2 = sinalpha * (std::cos (delta_theta) * x    1254   a2 = sinalpha * (std::cos (delta_theta) * xprime + std::sin (delta_theta) * yprime);
1187   // Required Increment vector...                1255   // Required Increment vector...
1188   delta = a2 - a1;                               1256   delta = a2 - a1;
1189   // So new viewpoint is...                      1257   // So new viewpoint is...
1190   viewPoint = new_vp.unit() + delta;             1258   viewPoint = new_vp.unit() + delta;
1191                                                  1259   
1192   fVP.SetViewAndLights (viewPoint);              1260   fVP.SetViewAndLights (viewPoint);
1193 }                                                1261 }
1194                                                  1262 
1195                                                  1263 
1196 void G4OpenGLViewer::rotateSceneInViewDirecti    1264 void G4OpenGLViewer::rotateSceneInViewDirection(G4double dx, G4double dy)
1197 {                                                1265 {
1198   if (!fSceneHandler.GetScene()) {               1266   if (!fSceneHandler.GetScene()) {
1199     return;                                      1267     return;
1200   }                                              1268   }
1201                                                  1269 
1202   G4Vector3D vp;                                 1270   G4Vector3D vp;
1203   G4Vector3D up;                                 1271   G4Vector3D up;
1204                                                  1272   
1205   G4Vector3D xprime;                             1273   G4Vector3D xprime;
1206   G4Vector3D yprime;                             1274   G4Vector3D yprime;
1207   G4Vector3D zprime;                             1275   G4Vector3D zprime;
1208                                                  1276   
1209   G4Vector3D new_vp;                             1277   G4Vector3D new_vp;
1210   G4Vector3D new_up;                             1278   G4Vector3D new_up;
1211                                                  1279   
1212   G4Vector3D a1;                                 1280   G4Vector3D a1;
1213   G4Vector3D a2;                                 1281   G4Vector3D a2;
1214   G4Vector3D delta;                              1282   G4Vector3D delta;
1215   G4Vector3D viewPoint;                          1283   G4Vector3D viewPoint;
1216                                                  1284 
1217   dx = dx/100;                                   1285   dx = dx/100;
1218   dy = dy/100;                                   1286   dy = dy/100;
1219                                                  1287 
1220   //phi spin stuff here                          1288   //phi spin stuff here
1221                                                  1289   
1222   vp = fVP.GetViewpointDirection ().unit();      1290   vp = fVP.GetViewpointDirection ().unit();
1223   up = fVP.GetUpVector ().unit();                1291   up = fVP.GetUpVector ().unit();
1224                                                  1292 
1225   G4Vector3D zPrimeVector = G4Vector3D(up.y()    1293   G4Vector3D zPrimeVector = G4Vector3D(up.y()*vp.z()-up.z()*vp.y(),
1226                              up.z()*vp.x()-up    1294                              up.z()*vp.x()-up.x()*vp.z(),
1227                              up.x()*vp.y()-up    1295                              up.x()*vp.y()-up.y()*vp.x());
1228                                                  1296 
1229   viewPoint = vp/fRot_sens + (zPrimeVector*dx    1297   viewPoint = vp/fRot_sens + (zPrimeVector*dx - up*dy) ;
1230   new_up = G4Vector3D(viewPoint.y()*zPrimeVec    1298   new_up = G4Vector3D(viewPoint.y()*zPrimeVector.z()-viewPoint.z()*zPrimeVector.y(),
1231                        viewPoint.z()*zPrimeVe    1299                        viewPoint.z()*zPrimeVector.x()-viewPoint.x()*zPrimeVector.z(),
1232                        viewPoint.x()*zPrimeVe    1300                        viewPoint.x()*zPrimeVector.y()-viewPoint.y()*zPrimeVector.x());
1233                                                  1301 
1234   G4Vector3D new_upUnit = new_up.unit();         1302   G4Vector3D new_upUnit = new_up.unit();
1235                                                  1303   
1236                                                  1304   
1237                                                  1305 
1238    fVP.SetUpVector(new_upUnit);                  1306    fVP.SetUpVector(new_upUnit);
1239    fVP.SetViewAndLights (viewPoint);             1307    fVP.SetViewAndLights (viewPoint);
1240 }                                                1308 }
1241                                                  1309 
1242                                                  1310 
1243 void G4OpenGLViewer::addExportImageFormat(std    1311 void G4OpenGLViewer::addExportImageFormat(std::string format) {
1244   fExportImageFormatVector.push_back(format);    1312   fExportImageFormatVector.push_back(format);
1245 }                                                1313 }
1246                                                  1314 
1247 bool G4OpenGLViewer::setExportImageFormat(std    1315 bool G4OpenGLViewer::setExportImageFormat(std::string format, bool quiet) {
1248   bool found = false;                            1316   bool found = false;
1249   std::string list;                              1317   std::string list;
1250   for (unsigned int a=0; a<fExportImageFormat    1318   for (unsigned int a=0; a<fExportImageFormatVector.size(); a++) {
1251     list +=fExportImageFormatVector.at(a) + "    1319     list +=fExportImageFormatVector.at(a) + " ";
1252                                                  1320 
1253     if (fExportImageFormatVector.at(a) == for    1321     if (fExportImageFormatVector.at(a) == format) {
1254       if (! quiet) {                             1322       if (! quiet) {
1255         G4cout << " Changing export format to    1323         G4cout << " Changing export format to \"" << format << "\"" << G4endl;
1256       }                                          1324       }
1257       if (format != fExportImageFormat) {        1325       if (format != fExportImageFormat) {
1258         fExportFilenameIndex = 0;                1326         fExportFilenameIndex = 0;
1259         fExportImageFormat = format;             1327         fExportImageFormat = format;
1260       }                                          1328       }
1261       return true;                               1329       return true;
1262     }                                            1330     }
1263   }                                              1331   }
1264   if (! found) {                                 1332   if (! found) {
1265     if (format.size() == 0) {                    1333     if (format.size() == 0) {
1266       G4cout << " Current formats availables     1334       G4cout << " Current formats availables are : " << list << G4endl;
1267     } else {                                     1335     } else {
1268       G4cerr << " Format \"" << format << "\"    1336       G4cerr << " Format \"" << format << "\" is not available for the selected viewer. Current formats availables are : " << list << G4endl;
1269     }                                            1337     }
1270   }                                              1338   }
1271   return false;                                  1339   return false;
1272 }                                                1340 }
1273                                                  1341 
1274                                                  1342 
1275 // From MESA implementation :                    1343 // From MESA implementation :
1276 // http://www.techques.com/question/1-8660454    1344 // http://www.techques.com/question/1-8660454/gluPickMatrix-code-from-Mesa
1277                                                  1345 
1278 void G4OpenGLViewer::g4GluPickMatrix(GLdouble    1346 void G4OpenGLViewer::g4GluPickMatrix(GLdouble x, GLdouble y, GLdouble width, GLdouble height,
1279                      GLint viewport[4])          1347                      GLint viewport[4])
1280   {                                              1348   {
1281     GLdouble mat[16];                            1349     GLdouble mat[16];
1282     GLdouble sx, sy;                             1350     GLdouble sx, sy;
1283     GLdouble tx, ty;                             1351     GLdouble tx, ty;
1284                                                  1352     
1285     sx = viewport[2] / width;                    1353     sx = viewport[2] / width;
1286     sy = viewport[3] / height;                   1354     sy = viewport[3] / height;
1287     tx = (viewport[2] + 2.0 * (viewport[0] -     1355     tx = (viewport[2] + 2.0 * (viewport[0] - x)) / width;
1288     ty = (viewport[3] + 2.0 * (viewport[1] -     1356     ty = (viewport[3] + 2.0 * (viewport[1] - y)) / height;
1289                                                  1357     
1290 #define M(row, col) mat[col*4+row]               1358 #define M(row, col) mat[col*4+row]
1291     M(0, 0) = sx;                                1359     M(0, 0) = sx;
1292     M(0, 1) = 0.0;                               1360     M(0, 1) = 0.0;
1293     M(0, 2) = 0.0;                               1361     M(0, 2) = 0.0;
1294     M(0, 3) = tx;                                1362     M(0, 3) = tx;
1295     M(1, 0) = 0.0;                               1363     M(1, 0) = 0.0;
1296     M(1, 1) = sy;                                1364     M(1, 1) = sy;
1297     M(1, 2) = 0.0;                               1365     M(1, 2) = 0.0;
1298     M(1, 3) = ty;                                1366     M(1, 3) = ty;
1299     M(2, 0) = 0.0;                               1367     M(2, 0) = 0.0;
1300     M(2, 1) = 0.0;                               1368     M(2, 1) = 0.0;
1301     M(2, 2) = 1.0;                               1369     M(2, 2) = 1.0;
1302     M(2, 3) = 0.0;                               1370     M(2, 3) = 0.0;
1303     M(3, 0) = 0.0;                               1371     M(3, 0) = 0.0;
1304     M(3, 1) = 0.0;                               1372     M(3, 1) = 0.0;
1305     M(3, 2) = 0.0;                               1373     M(3, 2) = 0.0;
1306     M(3, 3) = 1.0;                               1374     M(3, 3) = 1.0;
1307 #undef M                                         1375 #undef M
1308                                                  1376     
1309     glMultMatrixd(mat);                          1377     glMultMatrixd(mat);
1310 }                                                1378 }
1311                                                  1379 
1312                                                  1380 
1313                                                  1381 
1314                                                  1382 
1315                                                  1383 
1316 // From MESA implementation :                    1384 // From MESA implementation :
1317 // https://github.com/jlamarche/iOS-OpenGLES-    1385 // https://github.com/jlamarche/iOS-OpenGLES-Stuff/blob/master/Wavefront%20OBJ%20Loader/Classes/gluLookAt.m
1318 // or http://www.daniweb.com/software-develop    1386 // or http://www.daniweb.com/software-development/game-development/threads/308901/lookat-matrix-source-code
1319                                                  1387 
1320 void G4OpenGLViewer::g4GluLookAt( GLdouble ey    1388 void G4OpenGLViewer::g4GluLookAt( GLdouble eyex, GLdouble eyey, GLdouble eyez,
1321                         GLdouble centerx, GLd    1389                         GLdouble centerx, GLdouble centery, GLdouble
1322                         centerz,                 1390                         centerz,
1323                         GLdouble upx, GLdoubl    1391                         GLdouble upx, GLdouble upy, GLdouble upz )
1324 {                                                1392 {
1325   GLdouble mat[16];                              1393   GLdouble mat[16];
1326   GLdouble x[3], y[3], z[3];                     1394   GLdouble x[3], y[3], z[3];
1327   GLdouble mag;                                  1395   GLdouble mag;
1328                                                  1396   
1329   /* Make rotation matrix */                     1397   /* Make rotation matrix */
1330                                                  1398   
1331   /* Z vector */                                 1399   /* Z vector */
1332   z[0] = eyex - centerx;                         1400   z[0] = eyex - centerx;
1333   z[1] = eyey - centery;                         1401   z[1] = eyey - centery;
1334   z[2] = eyez - centerz;                         1402   z[2] = eyez - centerz;
1335   mag = std::sqrt(z[0] * z[0] + z[1] * z[1] +    1403   mag = std::sqrt(z[0] * z[0] + z[1] * z[1] + z[2] * z[2]);
1336   if (mag) {      /* mpichler, 19950515 */       1404   if (mag) {      /* mpichler, 19950515 */
1337     z[0] /= mag;                                 1405     z[0] /= mag;
1338     z[1] /= mag;                                 1406     z[1] /= mag;
1339     z[2] /= mag;                                 1407     z[2] /= mag;
1340   }                                              1408   }
1341                                                  1409   
1342   /* Y vector */                                 1410   /* Y vector */
1343   y[0] = upx;                                    1411   y[0] = upx;
1344   y[1] = upy;                                    1412   y[1] = upy;
1345   y[2] = upz;                                    1413   y[2] = upz;
1346                                                  1414   
1347   /* X vector = Y cross Z */                     1415   /* X vector = Y cross Z */
1348   x[0] = y[1] * z[2] - y[2] * z[1];              1416   x[0] = y[1] * z[2] - y[2] * z[1];
1349   x[1] = -y[0] * z[2] + y[2] * z[0];             1417   x[1] = -y[0] * z[2] + y[2] * z[0];
1350   x[2] = y[0] * z[1] - y[1] * z[0];              1418   x[2] = y[0] * z[1] - y[1] * z[0];
1351                                                  1419   
1352   /* Recompute Y = Z cross X */                  1420   /* Recompute Y = Z cross X */
1353   y[0] = z[1] * x[2] - z[2] * x[1];              1421   y[0] = z[1] * x[2] - z[2] * x[1];
1354   y[1] = -z[0] * x[2] + z[2] * x[0];             1422   y[1] = -z[0] * x[2] + z[2] * x[0];
1355   y[2] = z[0] * x[1] - z[1] * x[0];              1423   y[2] = z[0] * x[1] - z[1] * x[0];
1356                                                  1424   
1357   /* mpichler, 19950515 */                       1425   /* mpichler, 19950515 */
1358   /* cross product gives area of parallelogra    1426   /* cross product gives area of parallelogram, which is < 1.0 for
1359    * non-perpendicular unit-length vectors; s    1427    * non-perpendicular unit-length vectors; so normalize x, y here
1360    */                                            1428    */
1361                                                  1429   
1362   mag = std::sqrt(x[0] * x[0] + x[1] * x[1] +    1430   mag = std::sqrt(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]);
1363   if (mag) {                                     1431   if (mag) {
1364     x[0] /= mag;                                 1432     x[0] /= mag;
1365     x[1] /= mag;                                 1433     x[1] /= mag;
1366     x[2] /= mag;                                 1434     x[2] /= mag;
1367   }                                              1435   }
1368                                                  1436   
1369   mag = std::sqrt(y[0] * y[0] + y[1] * y[1] +    1437   mag = std::sqrt(y[0] * y[0] + y[1] * y[1] + y[2] * y[2]);
1370   if (mag) {                                     1438   if (mag) {
1371     y[0] /= mag;                                 1439     y[0] /= mag;
1372     y[1] /= mag;                                 1440     y[1] /= mag;
1373     y[2] /= mag;                                 1441     y[2] /= mag;
1374   }                                              1442   }
1375                                                  1443   
1376 #define M(row,col)  mat[col*4+row]               1444 #define M(row,col)  mat[col*4+row]
1377   M(0, 0) = x[0];                                1445   M(0, 0) = x[0];
1378   M(0, 1) = x[1];                                1446   M(0, 1) = x[1];
1379   M(0, 2) = x[2];                                1447   M(0, 2) = x[2];
1380   M(0, 3) = 0.0;                                 1448   M(0, 3) = 0.0;
1381   M(1, 0) = y[0];                                1449   M(1, 0) = y[0];
1382   M(1, 1) = y[1];                                1450   M(1, 1) = y[1];
1383   M(1, 2) = y[2];                                1451   M(1, 2) = y[2];
1384   M(1, 3) = 0.0;                                 1452   M(1, 3) = 0.0;
1385   M(2, 0) = z[0];                                1453   M(2, 0) = z[0];
1386   M(2, 1) = z[1];                                1454   M(2, 1) = z[1];
1387   M(2, 2) = z[2];                                1455   M(2, 2) = z[2];
1388   M(2, 3) = 0.0;                                 1456   M(2, 3) = 0.0;
1389   M(3, 0) = 0.0;                                 1457   M(3, 0) = 0.0;
1390   M(3, 1) = 0.0;                                 1458   M(3, 1) = 0.0;
1391   M(3, 2) = 0.0;                                 1459   M(3, 2) = 0.0;
1392   M(3, 3) = 1.0;                                 1460   M(3, 3) = 1.0;
1393 #undef M                                         1461 #undef M
1394   glMultMatrixd(mat);                            1462   glMultMatrixd(mat);
1395                                                  1463   
1396   /* Translate Eye to Origin */                  1464   /* Translate Eye to Origin */
1397   glTranslated(-eyex, -eyey, -eyez);             1465   glTranslated(-eyex, -eyey, -eyez);
1398 }                                                1466 }
1399                                                  1467 
1400 void G4OpenGLViewer::g4GlOrtho (GLdouble left    1468 void G4OpenGLViewer::g4GlOrtho (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar) {
1401   //  glOrtho (left, right, bottom, top, near    1469   //  glOrtho (left, right, bottom, top, near, far);
1402                                                  1470   
1403   GLdouble a = 2.0 / (right - left);             1471   GLdouble a = 2.0 / (right - left);
1404   GLdouble b = 2.0 / (top - bottom);             1472   GLdouble b = 2.0 / (top - bottom);
1405   GLdouble c = -2.0 / (zFar - zNear);            1473   GLdouble c = -2.0 / (zFar - zNear);
1406                                                  1474   
1407   GLdouble tx = - (right + left)/(right - lef    1475   GLdouble tx = - (right + left)/(right - left);
1408   GLdouble ty = - (top + bottom)/(top - botto    1476   GLdouble ty = - (top + bottom)/(top - bottom);
1409   GLdouble tz = - (zFar + zNear)/(zFar - zNea    1477   GLdouble tz = - (zFar + zNear)/(zFar - zNear);
1410                                                  1478   
1411   GLdouble ortho[16] = {                         1479   GLdouble ortho[16] = {
1412     a, 0, 0, 0,                                  1480     a, 0, 0, 0,
1413     0, b, 0, 0,                                  1481     0, b, 0, 0,
1414     0, 0, c, 0,                                  1482     0, 0, c, 0,
1415     tx, ty, tz, 1                                1483     tx, ty, tz, 1
1416   };                                             1484   };
1417   glMultMatrixd(ortho);                          1485   glMultMatrixd(ortho);
1418                                                  1486   
1419 }                                                1487 }
1420                                                  1488 
1421                                                  1489 
1422 void G4OpenGLViewer::g4GlFrustum (GLdouble le    1490 void G4OpenGLViewer::g4GlFrustum (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar) {
1423   //  glFrustum (left, right, bottom, top, ne    1491   //  glFrustum (left, right, bottom, top, near, far);
1424                                                  1492   
1425   GLdouble deltaX = right - left;                1493   GLdouble deltaX = right - left;
1426   GLdouble deltaY = top - bottom;                1494   GLdouble deltaY = top - bottom;
1427   GLdouble deltaZ = zFar - zNear;                1495   GLdouble deltaZ = zFar - zNear;
1428                                                  1496   
1429   GLdouble a = 2.0f * zNear / deltaX;            1497   GLdouble a = 2.0f * zNear / deltaX;
1430   GLdouble b = 2.0f * zNear / deltaY;            1498   GLdouble b = 2.0f * zNear / deltaY;
1431   GLdouble c = (right + left) / deltaX;          1499   GLdouble c = (right + left) / deltaX;
1432   GLdouble d = (top + bottom) / deltaY;          1500   GLdouble d = (top + bottom) / deltaY;
1433   GLdouble e = -(zFar + zNear) / (zFar - zNea    1501   GLdouble e = -(zFar + zNear) / (zFar - zNear);
1434   GLdouble f = -2.0f * zFar * zNear / deltaZ;    1502   GLdouble f = -2.0f * zFar * zNear / deltaZ;
1435                                                  1503   
1436   GLdouble proj[16] = {                          1504   GLdouble proj[16] = {
1437     a, 0, 0, 0,                                  1505     a, 0, 0, 0,
1438     0, b, 0, 0,                                  1506     0, b, 0, 0,
1439     c, d, e, -1.0f,                              1507     c, d, e, -1.0f,
1440     0, 0, f, 0                                   1508     0, 0, f, 0
1441   };                                             1509   };
1442                                                  1510   
1443   glMultMatrixd(proj);                           1511   glMultMatrixd(proj);
1444                                                  1512   
1445 }                                                1513 }
1446                                                  1514 
                                                   >> 1515 
                                                   >> 1516 #ifdef G4OPENGL_VERSION_2
                                                   >> 1517 
                                                   >> 1518 // Associate the VBO drawer to the OpenGLViewer and the OpenGLSceneHandler
                                                   >> 1519 void G4OpenGLViewer::setVboDrawer(G4OpenGLVboDrawer* drawer) {
                                                   >> 1520   fVboDrawer = drawer;
                                                   >> 1521   try {
                                                   >> 1522     G4OpenGLSceneHandler& sh = dynamic_cast<G4OpenGLSceneHandler&>(fSceneHandler);
                                                   >> 1523     sh.setVboDrawer(fVboDrawer);
                                                   >> 1524   } catch(std::bad_cast exp) { }
                                                   >> 1525 }
                                                   >> 1526 
                                                   >> 1527 #endif
                                                   >> 1528 
                                                   >> 1529 
1447 G4String G4OpenGLViewerPickMap::print() {        1530 G4String G4OpenGLViewerPickMap::print() {
1448   std::ostringstream txt;                        1531   std::ostringstream txt;
1449   for (unsigned int a=0; a<fAttributes.size()    1532   for (unsigned int a=0; a<fAttributes.size(); a++) {
1450     txt << fAttributes[a];                       1533     txt << fAttributes[a];
1451     if (a < fAttributes.size() - 1) txt << "\    1534     if (a < fAttributes.size() - 1) txt << "\n";
1452   }                                              1535   }
1453   return txt.str();                              1536   return txt.str();
1454 }                                                1537 }
                                                   >> 1538 
                                                   >> 1539 #endif
1455                                                  1540