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 11.1.2)


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