source: trunk/source/visualization/OpenGL/src/G4OpenGLViewer.cc @ 1241

Last change on this file since 1241 was 1241, checked in by garnier, 15 years ago

update

  • Property svn:mime-type set to text/cpp
File size: 27.2 KB
Line 
1//
2// ********************************************************************
3// * License and Disclaimer                                           *
4// *                                                                  *
5// * The  Geant4 software  is  copyright of the Copyright Holders  of *
6// * the Geant4 Collaboration.  It is provided  under  the terms  and *
7// * conditions of the Geant4 Software License,  included in the file *
8// * LICENSE and available at  http://cern.ch/geant4/license .  These *
9// * include a list of copyright holders.                             *
10// *                                                                  *
11// * Neither the authors of this software system, nor their employing *
12// * institutes,nor the agencies providing financial support for this *
13// * work  make  any representation or  warranty, express or implied, *
14// * regarding  this  software system or assume any liability for its *
15// * use.  Please see the license in the file  LICENSE  and URL above *
16// * for the full disclaimer and the limitation of liability.         *
17// *                                                                  *
18// * This  code  implementation is the result of  the  scientific and *
19// * technical work of the GEANT4 collaboration.                      *
20// * By using,  copying,  modifying or  distributing the software (or *
21// * any work based  on the software)  you  agree  to acknowledge its *
22// * use  in  resulting  scientific  publications,  and indicate your *
23// * acceptance of all terms of the Geant4 Software license.          *
24// ********************************************************************
25//
26//
27// $Id: G4OpenGLViewer.cc,v 1.59 2009/10/20 12:47:45 lgarnier Exp $
28// GEANT4 tag $Name:  $
29//
30//
31// Andrew Walkden  27th March 1996
32// OpenGL view - opens window, hard copy, etc.
33
34#ifdef G4VIS_BUILD_OPENGL_DRIVER
35
36#include "G4ios.hh"
37#include "G4OpenGLViewer.hh"
38#include "G4OpenGLSceneHandler.hh"
39#include "G4OpenGLTransform3D.hh"
40#include "G4OpenGL2PSAction.hh"
41
42#include "G4Scene.hh"
43#include "G4VisExtent.hh"
44#include "G4LogicalVolume.hh"
45#include "G4VSolid.hh"
46#include "G4Point3D.hh"
47#include "G4Normal3D.hh"
48#include "G4Plane3D.hh"
49#include "G4AttHolder.hh"
50#include "G4AttCheck.hh"
51
52// GL2PS
53#include "Geant4_gl2ps.h"
54
55#include <sstream>
56
57G4OpenGLViewer::G4OpenGLViewer (G4OpenGLSceneHandler& scene):
58G4VViewer (scene, -1),
59fPrintColour (true),
60fVectoredPs (true),
61fOpenGLSceneHandler(scene),
62background (G4Colour(0.,0.,0.)),
63transparency_enabled (true),
64antialiasing_enabled (false),
65haloing_enabled (false),
66fStartTime(-DBL_MAX),
67fEndTime(DBL_MAX),
68fFadeFactor(0.),
69fDisplayHeadTime(false),
70fDisplayHeadTimeX(-0.9),
71fDisplayHeadTimeY(-0.9),
72fDisplayHeadTimeSize(24.),
73fDisplayHeadTimeRed(0.),
74fDisplayHeadTimeGreen(1.),
75fDisplayHeadTimeBlue(1.),
76fDisplayLightFront(false),
77fDisplayLightFrontX(0.),
78fDisplayLightFrontY(0.),
79fDisplayLightFrontZ(0.),
80fDisplayLightFrontT(0.),
81fDisplayLightFrontRed(0.),
82fDisplayLightFrontGreen(1.),
83fDisplayLightFrontBlue(0.),
84fPrintSizeX(-1),
85fPrintSizeY(-1),
86fPrintFilename ("G4OpenGL"),
87fPrintFilenameIndex(0),
88fPointSize (0),
89fSizeHasChanged(0)
90{
91  // Make changes to view parameters for OpenGL...
92  fVP.SetAutoRefresh(true);
93  fDefaultVP.SetAutoRefresh(true);
94
95  fGL2PSAction = new G4OpenGL2PSAction();
96
97  //  glClearColor (0.0, 0.0, 0.0, 0.0);
98  //  glClearDepth (1.0);
99  //  glDisable (GL_BLEND);
100  //  glDisable (GL_LINE_SMOOTH);
101  //  glDisable (GL_POLYGON_SMOOTH);
102}
103
104G4OpenGLViewer::~G4OpenGLViewer () {
105#ifdef G4DEBUG_VIS_OGL
106  printf("G4OpenGLViewer::~G4OpenGLViewer DELETING \n");
107#endif
108}
109
110void G4OpenGLViewer::InitializeGLView ()
111{
112  glClearColor (0.0, 0.0, 0.0, 0.0);
113  glClearDepth (1.0);
114  glDisable (GL_BLEND);
115  glDisable (GL_LINE_SMOOTH);
116  glDisable (GL_POLYGON_SMOOTH);
117
118  fWinSize_x = fVP.GetWindowSizeHintX();
119  fWinSize_y = fVP.GetWindowSizeHintY();
120#ifdef G4DEBUG_VIS_OGL
121  printf("G4OpenGLViewer::InitializeGLView to W:%d H:%d pt:%d\n",fWinSize_x,fWinSize_y,this);
122#endif
123
124
125void G4OpenGLViewer::ClearView () {
126#ifdef G4DEBUG_VIS_OGL
127  printf("G4OpenGLViewer::ClearView\n");
128#endif
129  glClearColor (background.GetRed(),
130                background.GetGreen(),
131                background.GetBlue(),
132                1.);
133  glClearDepth (1.0);
134  //Below line does not compile with Mesa includes.
135  //glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
136  glClear (GL_COLOR_BUFFER_BIT);
137  glClear (GL_DEPTH_BUFFER_BIT);
138  glClear (GL_STENCIL_BUFFER_BIT);
139#ifdef G4DEBUG_VIS_OGL
140  printf("G4OpenGLViewer::ClearView flush\n");
141#endif
142  glFlush ();
143}
144
145
146void G4OpenGLViewer::ResizeWindow(unsigned int aWidth, unsigned int aHeight) {
147  if ((fWinSize_x != aWidth) || (fWinSize_y != aHeight)) {
148    fWinSize_x = aWidth;
149    fWinSize_y = aHeight;
150    fSizeHasChanged = true;
151  } else {
152    fSizeHasChanged = false;
153  }
154#ifdef G4DEBUG_VIS_OGL
155  printf("G4OpenGLViewer::ResizeWindow :W:%d H:%d changed?:%d set:W:%d H:%d pt:%d\n",fWinSize_x,fWinSize_y,fSizeHasChanged,aWidth,aHeight,this);
156#endif
157}
158
159/**
160 * Set the viewport of the scene
161 * MAXIMUM SIZE is :
162 * GLint dims[2];
163 * glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);
164 */
165void G4OpenGLViewer::ResizeGLView()
166{
167#ifdef G4DEBUG_VIS_OGL
168  printf("G4OpenGLViewer::ResizeGLView %d %d pt:%d\n",fWinSize_x,fWinSize_y,this);
169#endif
170  // Check size
171  GLint dims[2];
172  glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);
173
174  // L.Garnier 01-2010: Some problems with mac 10.6
175  if ((dims[0] !=0 ) && (dims[1] !=0)) {
176
177#ifdef G4DEBUG_VIS_OGL
178    GLenum err = glGetError();
179    if (err != GL_NO_ERROR) {                          \
180      printf("%s: %s at %s:%d\n",                      \
181             __FUNCTION__,                             \
182             gluErrorString(err),                      \
183             __FILE__, __LINE__);                      \
184      printf("G4OpenGLViewer::ResizeGLView ERRRRR\n");
185    }
186    printf("G4OpenGLViewer::ResizeGLView DIM X:%d Y:%d\n",dims[0],dims[1]);
187#endif
188    if (fWinSize_x > (unsigned)dims[0]) {
189      G4cerr << "Try to resize view greater than max X viewport dimension. Desired size "<<dims[0] <<" is resize to "<<  dims[0] << G4endl;
190      fWinSize_x = dims[0];
191    }
192    if (fWinSize_y > (unsigned)dims[1]) {
193      G4cerr << "Try to resize view greater than max Y viewport dimension. Desired size "<<dims[0] <<" is resize to "<<  dims[1] << G4endl;
194      fWinSize_y = dims[1];
195    }
196  }
197//   GLsizei side = fWinSize_x;
198//   if (fWinSize_y < fWinSize_x) side = fWinSize_y;
199 
200  // SPECIAL CASE if fWinSize_x is even (69 for example)
201  // Ex : X: 69 Y: 26
202  // side = 26
203  // width / 2 = 21,5
204  // height / 2 = 0
205  // Should be fixed to closed : 21 0 for ex
206  // Then size must by change to :
207  // X:68 Y: 26
208
209  // SPECIAL CASE
210//   if ((fWinSize_x - side)%2) {
211//     //    fWinSize_x --;
212
213//     side = fWinSize_x;
214//     if (fWinSize_y < fWinSize_x) side = fWinSize_y;
215//   }
216//   if ((fWinSize_y - side)%2) {
217//     //    fWinSize_y --;
218
219//     side = fWinSize_x;
220//     if (fWinSize_y < fWinSize_x) side = fWinSize_y;
221//   }
222 
223//   GLint X = (fWinSize_x - side) / 2;
224//   GLint Y = (fWinSize_y - side) / 2;
225 
226#ifdef G4DEBUG_VIS_OGL
227  //  printf("G4OpenGLViewer::ResizeGLView X:%d Y:%d W:%d H:%d --side%d\n",(fWinSize_x - side) / 2,(fWinSize_y - side) / 2,fWinSize_x,fWinSize_y,side);
228#endif
229
230  //  glViewport(X, Y, side, side);
231  glViewport(0, 0, fWinSize_x,fWinSize_y); 
232 
233
234}
235
236
237void G4OpenGLViewer::SetView () {
238
239  if (!fSceneHandler.GetScene()) {
240    return;
241  }
242  // Calculates view representation based on extent of object being
243  // viewed and (initial) viewpoint.  (Note: it can change later due
244  // to user interaction via visualization system's GUI.)
245 
246  // Lighting.
247  GLfloat lightPosition [4];
248  lightPosition [0] = fVP.GetActualLightpointDirection().x();
249  lightPosition [1] = fVP.GetActualLightpointDirection().y();
250  lightPosition [2] = fVP.GetActualLightpointDirection().z();
251  lightPosition [3] = 0.;
252  // Light position is "true" light direction, so must come after gluLookAt.
253  GLfloat ambient [] = { 0.2, 0.2, 0.2, 1.};
254  GLfloat diffuse [] = { 0.8, 0.8, 0.8, 1.};
255  glEnable (GL_LIGHT0);
256  glLightfv (GL_LIGHT0, GL_AMBIENT, ambient);
257  glLightfv (GL_LIGHT0, GL_DIFFUSE, diffuse);
258 
259  G4double ratioX = 1;
260  G4double ratioY = 1;
261  if (fWinSize_y > fWinSize_x) {
262    ratioX = ((G4double)fWinSize_y) / ((G4double)fWinSize_x);
263  }
264  if (fWinSize_x > fWinSize_y) {
265    ratioY = ((G4double)fWinSize_x) / ((G4double)fWinSize_y);
266  }
267 
268  // Get radius of scene, etc.
269  // Note that this procedure properly takes into account zoom, dolly and pan.
270  const G4Point3D targetPoint
271    = fSceneHandler.GetScene()->GetStandardTargetPoint()
272    + fVP.GetCurrentTargetPoint ();
273  G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
274  if(radius<=0.) radius = 1.;
275  const G4double cameraDistance = fVP.GetCameraDistance (radius);
276  const G4Point3D cameraPosition =
277    targetPoint + cameraDistance * fVP.GetViewpointDirection().unit();
278  const GLdouble pnear  = fVP.GetNearDistance (cameraDistance, radius);
279  const GLdouble pfar   = fVP.GetFarDistance  (cameraDistance, pnear, radius);
280  const GLdouble right  = fVP.GetFrontHalfHeight (pnear, radius) * ratioY;
281  const GLdouble left   = -right;
282  const GLdouble top    = fVP.GetFrontHalfHeight (pnear, radius) * ratioX;
283  const GLdouble bottom = -top;
284 
285  // FIXME
286#ifdef G4DEBUG_VIS_OGL
287  printf("G4OpenGLViewer::SetView Call ResizeGLView VVVVVV sizeX:%d sizeY:%d ratioX:%f ratioY:%f\n",fWinSize_x,fWinSize_y,ratioX,ratioY);
288#endif
289  ResizeGLView();
290#ifdef G4DEBUG_VIS_OGL
291  printf("G4OpenGLViewer::SetView Call ResizeGLView ^^^^^^\n");
292#endif
293  //SHOULD SetWindowsSizeHint()...
294
295  glMatrixMode (GL_PROJECTION); // set up Frustum.
296  glLoadIdentity();
297
298  const G4Vector3D scaleFactor = fVP.GetScaleFactor();
299  glScaled(scaleFactor.x(),scaleFactor.y(),scaleFactor.z());
300 
301  if (fVP.GetFieldHalfAngle() == 0.) {
302    glOrtho (left, right, bottom, top, pnear, pfar);
303#ifdef G4DEBUG_VIS_OGL
304    printf("G4OpenGLViewer::SetView glOrtho %f %f %f %f %f %f\n",left, right, bottom, top, pnear, pfar);
305#endif
306  }
307  else {
308    glFrustum (left, right, bottom, top, pnear, pfar);
309  } 
310
311  glMatrixMode (GL_MODELVIEW); // apply further transformations to scene.
312  glLoadIdentity();
313 
314  const G4Normal3D& upVector = fVP.GetUpVector (); 
315  G4Point3D gltarget;
316  if (cameraDistance > 1.e-6 * radius) {
317    gltarget = targetPoint;
318  }
319  else {
320    gltarget = targetPoint - radius * fVP.GetViewpointDirection().unit();
321  }
322
323  const G4Point3D& pCamera = cameraPosition;  // An alias for brevity.
324  gluLookAt (pCamera.x(),  pCamera.y(),  pCamera.z(),       // Viewpoint.
325             gltarget.x(), gltarget.y(), gltarget.z(),      // Target point.
326             upVector.x(), upVector.y(), upVector.z());     // Up vector.
327
328  // Light position is "true" light direction, so must come after gluLookAt.
329  glLightfv (GL_LIGHT0, GL_POSITION, lightPosition);
330
331  // OpenGL no longer seems to reconstruct clipped edges, so, when the
332  // BooleanProcessor is up to it, abandon this and use generic
333  // clipping in G4OpenGLSceneHandler::CreateSectionPolyhedron.  Also,
334  // force kernel visit on change of clipping plane in
335  // G4OpenGLStoredViewer::CompareForKernelVisit.
336  if (fVP.IsSection () ) {  // pair of back to back clip planes.
337    const G4Plane3D& s = fVP.GetSectionPlane ();
338    double sArray[4];
339    sArray[0] = s.a();
340    sArray[1] = s.b();
341    sArray[2] = s.c();
342    sArray[3] = s.d() + radius * 1.e-05;
343    glClipPlane (GL_CLIP_PLANE0, sArray);
344    glEnable (GL_CLIP_PLANE0);
345    sArray[0] = -s.a();
346    sArray[1] = -s.b();
347    sArray[2] = -s.c();
348    sArray[3] = -s.d() + radius * 1.e-05;
349    glClipPlane (GL_CLIP_PLANE1, sArray);
350    glEnable (GL_CLIP_PLANE1);
351  } else {
352    glDisable (GL_CLIP_PLANE0);
353    glDisable (GL_CLIP_PLANE1);
354  }
355
356  const G4Planes& cutaways = fVP.GetCutawayPlanes();
357  size_t nPlanes = cutaways.size();
358  if (fVP.IsCutaway() &&
359      fVP.GetCutawayMode() == G4ViewParameters::cutawayIntersection &&
360      nPlanes > 0) {
361    double a[4];
362    a[0] = cutaways[0].a();
363    a[1] = cutaways[0].b();
364    a[2] = cutaways[0].c();
365    a[3] = cutaways[0].d();
366    glClipPlane (GL_CLIP_PLANE2, a);
367    glEnable (GL_CLIP_PLANE2);
368    if (nPlanes > 1) {
369      a[0] = cutaways[1].a();
370      a[1] = cutaways[1].b();
371      a[2] = cutaways[1].c();
372      a[3] = cutaways[1].d();
373      glClipPlane (GL_CLIP_PLANE3, a);
374      glEnable (GL_CLIP_PLANE3);
375    }
376    if (nPlanes > 2) {
377      a[0] = cutaways[2].a();
378      a[1] = cutaways[2].b();
379      a[2] = cutaways[2].c();
380      a[3] = cutaways[2].d();
381      glClipPlane (GL_CLIP_PLANE4, a);
382      glEnable (GL_CLIP_PLANE4);
383    }
384  } else {
385    glDisable (GL_CLIP_PLANE2);
386    glDisable (GL_CLIP_PLANE3);
387    glDisable (GL_CLIP_PLANE4);
388  }
389
390  // Background.
391  background = fVP.GetBackgroundColour ();
392
393}
394
395void G4OpenGLViewer::HaloingFirstPass () {
396 
397  //To perform haloing, first Draw all information to the depth buffer
398  //alone, using a chunky line width, and then Draw all info again, to
399  //the colour buffer, setting a thinner line width an the depth testing
400  //function to less than or equal, so if two lines cross, the one
401  //passing behind the other will not pass the depth test, and so not
402  //get rendered either side of the infront line for a short distance.
403
404  //First, disable writing to the colo(u)r buffer...
405  glColorMask (GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
406
407  //Now enable writing to the depth buffer...
408  glDepthMask (GL_TRUE);
409  glDepthFunc (GL_LESS);
410  glClearDepth (1.0);
411
412  //Finally, set the line width to something wide...
413  glLineWidth (3.0);
414
415}
416
417void G4OpenGLViewer::HaloingSecondPass () {
418
419  //And finally, turn the colour buffer back on with a sesible line width...
420  glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
421  glDepthFunc (GL_LEQUAL);
422  glLineWidth (1.0);
423
424}
425
426void G4OpenGLViewer::Pick(GLdouble x, GLdouble y)
427{
428  //G4cout << "X: " << x << ", Y: " << y << G4endl;
429  const G4int BUFSIZE = 512;
430  GLuint selectBuffer[BUFSIZE];
431  glSelectBuffer(BUFSIZE, selectBuffer);
432  glRenderMode(GL_SELECT);
433  glInitNames();
434  glPushName(0);
435  glMatrixMode(GL_PROJECTION);
436  G4double currentProjectionMatrix[16];
437  glGetDoublev(GL_PROJECTION_MATRIX, currentProjectionMatrix);
438  glPushMatrix();
439  glLoadIdentity();
440  GLint viewport[4];
441  glGetIntegerv(GL_VIEWPORT, viewport);
442  // Define 5x5 pixel pick area
443  gluPickMatrix(x, viewport[3] - y, 5., 5., viewport);
444  glMultMatrixd(currentProjectionMatrix);
445  glMatrixMode(GL_MODELVIEW);
446  DrawView();
447  GLint hits = glRenderMode(GL_RENDER);
448  if (hits < 0)
449    G4cout << "Too many hits.  Zoom in to reduce overlaps." << G4cout;
450  else if (hits > 0) {
451    //G4cout << hits << " hit(s)" << G4endl;
452    GLuint* p = selectBuffer;
453    for (GLint i = 0; i < hits; ++i) {
454      GLuint nnames = *p++;
455      *p++; //OR GLuint zmin = *p++;
456      *p++; //OR GLuint zmax = *p++;
457      //G4cout << "Hit " << i << ": " << nnames << " names"
458      //     << "\nzmin: " << zmin << ", zmax: " << zmax << G4endl;
459      for (GLuint j = 0; j < nnames; ++j) {
460        GLuint name = *p++;
461        //G4cout << "Name " << j << ": PickName: " << name << G4endl;
462        std::map<GLuint, G4AttHolder*>::iterator iter =
463          fOpenGLSceneHandler.fPickMap.find(name);
464        if (iter != fOpenGLSceneHandler.fPickMap.end()) {
465          G4AttHolder* attHolder = iter->second;
466          if(attHolder && attHolder->GetAttDefs().size()) {
467            for (size_t i = 0; i < attHolder->GetAttDefs().size(); ++i) {
468              G4cout << G4AttCheck(attHolder->GetAttValues()[i],
469                                   attHolder->GetAttDefs()[i]);
470            }
471          }
472        }
473      }
474      G4cout << G4endl;
475    }
476  }
477  glMatrixMode(GL_PROJECTION);
478  glPopMatrix();
479  glMatrixMode(GL_MODELVIEW);
480}
481
482
483
484
485GLubyte* G4OpenGLViewer::grabPixels (int inColor, unsigned int width, unsigned int height) {
486 
487  GLubyte* buffer;
488  GLint swapbytes, lsbfirst, rowlength;
489  GLint skiprows, skippixels, alignment;
490  GLenum format;
491  int size;
492
493  if (inColor) {
494    format = GL_RGB;
495    size = width*height*3;
496  } else {
497    format = GL_LUMINANCE;
498    size = width*height*1;
499  }
500
501  buffer = new GLubyte[size];
502  if (buffer == NULL)
503    return NULL;
504
505  glGetIntegerv (GL_UNPACK_SWAP_BYTES, &swapbytes);
506  glGetIntegerv (GL_UNPACK_LSB_FIRST, &lsbfirst);
507  glGetIntegerv (GL_UNPACK_ROW_LENGTH, &rowlength);
508
509  glGetIntegerv (GL_UNPACK_SKIP_ROWS, &skiprows);
510  glGetIntegerv (GL_UNPACK_SKIP_PIXELS, &skippixels);
511  glGetIntegerv (GL_UNPACK_ALIGNMENT, &alignment);
512
513  glPixelStorei (GL_UNPACK_SWAP_BYTES, GL_FALSE);
514  glPixelStorei (GL_UNPACK_LSB_FIRST, GL_FALSE);
515  glPixelStorei (GL_UNPACK_ROW_LENGTH, 0);
516
517  glPixelStorei (GL_UNPACK_SKIP_ROWS, 0);
518  glPixelStorei (GL_UNPACK_SKIP_PIXELS, 0);
519  glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
520
521  glReadBuffer(GL_FRONT);
522  glReadPixels (0, 0, (GLsizei)width, (GLsizei)height, format, GL_UNSIGNED_BYTE, (GLvoid*) buffer);
523
524  glPixelStorei (GL_UNPACK_SWAP_BYTES, swapbytes);
525  glPixelStorei (GL_UNPACK_LSB_FIRST, lsbfirst);
526  glPixelStorei (GL_UNPACK_ROW_LENGTH, rowlength);
527 
528  glPixelStorei (GL_UNPACK_SKIP_ROWS, skiprows);
529  glPixelStorei (GL_UNPACK_SKIP_PIXELS, skippixels);
530  glPixelStorei (GL_UNPACK_ALIGNMENT, alignment);
531 
532  return buffer;
533}
534
535void G4OpenGLViewer::printEPS() {
536  bool res;
537#ifdef G4DEBUG_VIS_OGL
538  printf("G4OpenGLViewer::printEPS file:%s Vec:%d Name:%s\n",getRealPrintFilename().c_str(),fVectoredPs,GetName().c_str());
539#endif
540
541  // Change the LC_NUMERIC value in order to have "." separtor and not ","
542  // This case is only useful for French, Canadien...
543  char *oldLocale = strdup(setlocale(LC_NUMERIC,NULL));
544  setlocale(LC_NUMERIC,"C");
545
546  if (fVectoredPs) {
547    res = printVectoredEPS();
548  } else {
549    res = printNonVectoredEPS();
550  }
551
552  // restore the local
553  if (oldLocale) {
554    setlocale(LC_NUMERIC,oldLocale);
555    free(oldLocale);
556  }
557
558  if (res == false) {
559    G4cerr << "Error while saving file... "<<getRealPrintFilename().c_str()<< G4endl;
560  } else {
561    G4cout << "File "<<getRealPrintFilename().c_str()<<" has been saved " << G4endl;
562  }
563
564  // increment index if necessary
565  if ( fPrintFilenameIndex != -1) {
566    fPrintFilenameIndex++;
567  }
568
569}
570
571bool G4OpenGLViewer::printVectoredEPS() {
572  return printGl2PS();
573}
574
575bool G4OpenGLViewer::printNonVectoredEPS () {
576
577  int width = getRealPrintSizeX();
578  int height = getRealPrintSizeY();
579
580#ifdef G4DEBUG_VIS_OGL
581  printf("G4OpenGLViewer::printNonVectoredEPS file:%s Vec:%d X:%d Y:%d col:%d\n",getRealPrintFilename().c_str(),fVectoredPs,width,height,fPrintColour);
582#endif
583  FILE* fp;
584  GLubyte* pixels;
585  GLubyte* curpix;
586  int components, pos, i;
587
588  pixels = grabPixels (fPrintColour, width, height);
589
590  if (pixels == NULL) {
591      G4cerr << "Failed to get pixels from OpenGl viewport" << G4endl;
592    return false;
593  }
594  if (fPrintColour) {
595    components = 3;
596  } else {
597    components = 1;
598  }
599  std::string name = getRealPrintFilename();
600  fp = fopen (name.c_str(), "w");
601  if (fp == NULL) {
602    G4cerr << "Can't open filename " << name.c_str() << G4endl;
603    return false;
604  }
605 
606  fprintf (fp, "%%!PS-Adobe-2.0 EPSF-1.2\n");
607  fprintf (fp, "%%%%Title: %s\n", name.c_str());
608  fprintf (fp, "%%%%Creator: OpenGL pixmap render output\n");
609  fprintf (fp, "%%%%BoundingBox: 0 0 %d %d\n", width, height);
610  fprintf (fp, "%%%%EndComments\n");
611  fprintf (fp, "gsave\n");
612  fprintf (fp, "/bwproc {\n");
613  fprintf (fp, "    rgbproc\n");
614  fprintf (fp, "    dup length 3 idiv string 0 3 0 \n");
615  fprintf (fp, "    5 -1 roll {\n");
616  fprintf (fp, "    add 2 1 roll 1 sub dup 0 eq\n");
617  fprintf (fp, "    { pop 3 idiv 3 -1 roll dup 4 -1 roll dup\n");
618  fprintf (fp, "       3 1 roll 5 -1 roll } put 1 add 3 0 \n");
619  fprintf (fp, "    { 2 1 roll } ifelse\n");
620  fprintf (fp, "    }forall\n");
621  fprintf (fp, "    pop pop pop\n");
622  fprintf (fp, "} def\n");
623  fprintf (fp, "systemdict /colorimage known not {\n");
624  fprintf (fp, "   /colorimage {\n");
625  fprintf (fp, "       pop\n");
626  fprintf (fp, "       pop\n");
627  fprintf (fp, "       /rgbproc exch def\n");
628  fprintf (fp, "       { bwproc } image\n");
629  fprintf (fp, "   }  def\n");
630  fprintf (fp, "} if\n");
631  fprintf (fp, "/picstr %d string def\n", width * components);
632  fprintf (fp, "%d %d scale\n", width, height);
633  fprintf (fp, "%d %d %d\n", width, height, 8);
634  fprintf (fp, "[%d 0 0 %d 0 0]\n", width, height);
635  fprintf (fp, "{currentfile picstr readhexstring pop}\n");
636  fprintf (fp, "false %d\n", components);
637  fprintf (fp, "colorimage\n");
638 
639  curpix = (GLubyte*) pixels;
640  pos = 0;
641  for (i = width*height*components; i>0; i--) {
642    fprintf (fp, "%02hx ", *(curpix++));
643    if (++pos >= 32) {
644      fprintf (fp, "\n");
645      pos = 0;
646    }
647  }
648  if (pos)
649    fprintf (fp, "\n");
650
651  fprintf (fp, "grestore\n");
652  fprintf (fp, "showpage\n");
653  delete pixels;
654  fclose (fp);
655
656  // Reset for next time (useful is size change)
657  //  fPrintSizeX = -1;
658  //  fPrintSizeY = -1;
659
660  return true;
661}
662
663
664bool G4OpenGLViewer::printGl2PS() {
665
666  int width = getRealPrintSizeX();
667  int height = getRealPrintSizeY();
668
669  if (!fGL2PSAction) return false;
670
671  fGL2PSAction->setFileName(getRealPrintFilename().c_str());
672  // try to resize
673  int X = fWinSize_x;
674  int Y = fWinSize_y;
675
676  fWinSize_x = width;
677  fWinSize_y = height;
678  ResizeGLView();
679  if (fGL2PSAction->enableFileWriting()) {
680
681    // By default, we choose the line width (trajectories...)
682    fGL2PSAction->setLineWidth(1);
683    // By default, we choose the point size (markers...)
684   
685#ifdef G4DEBUG_VIS_OGL
686    //  printf("G4OpenGLViewer::printGl2PS marker size:%f\n",    GetSceneHandler()->GetMarkerSize());
687#endif
688#ifdef G4DEBUG_VIS_OGL
689  //  printf("G4OpenGLViewer::printGl2PS marker2 size:%f\n",fpViewer -> GetViewParameters ()->GetDefaultMarker ().GetScreenSize());
690#endif
691    //    if (fpViewer -> GetViewParameters ().IsMarkerNotHidden ()) {
692    //      fGL2PSAction->setPointSize(fpViewer -> GetViewParameters ()->GetDefaultMarker ().GetScreenSize());
693    //    } else {
694      fGL2PSAction->setPointSize(2);
695      //    }
696    DrawView ();
697    fGL2PSAction->disableFileWriting();
698  }
699
700  fWinSize_x = X;
701  fWinSize_y = Y;
702  ResizeGLView();
703
704  // Reset for next time (useful is size change)
705  //  fPrintSizeX = 0;
706  //  fPrintSizeY = 0;
707
708  return true;
709}
710
711unsigned int G4OpenGLViewer::getWinWidth() {
712  return fWinSize_x;
713}
714
715unsigned int G4OpenGLViewer::getWinHeight() {
716  return fWinSize_y;
717}
718
719G4bool G4OpenGLViewer::sizeHasChanged() {
720  return fSizeHasChanged;
721}
722
723G4int G4OpenGLViewer::getRealPrintSizeX() {
724  if (fPrintSizeX == -1) {
725    return fWinSize_x;
726  }
727  GLint dims[2];
728  glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);
729
730  // L.Garnier 01-2010: Some problems with mac 10.6
731  if ((dims[0] !=0 ) && (dims[1] !=0)) {
732    if (fPrintSizeX > dims[0]){
733      return dims[0];
734    }
735  }
736  if (fPrintSizeX < -1){
737    return 0;
738  }
739  return fPrintSizeX;
740}
741
742G4int G4OpenGLViewer::getRealPrintSizeY() {
743  if (fPrintSizeY == -1) {
744    return fWinSize_y;
745  }
746  GLint dims[2];
747  glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);
748
749  // L.Garnier 01-2010: Some problems with mac 10.6
750  if ((dims[0] !=0 ) && (dims[1] !=0)) {
751    if (fPrintSizeY > dims[1]){
752      return dims[1];
753    }
754  }
755  if (fPrintSizeY < -1){
756    return 0;
757  }
758  return fPrintSizeY;
759}
760
761void G4OpenGLViewer::setPrintSize(G4int X, G4int Y) {
762  fPrintSizeX = X;
763  fPrintSizeY = Y;
764}
765
766void G4OpenGLViewer::setPrintFilename(G4String name,G4bool inc) {
767  if (name != "") {
768    fPrintFilename = name;
769  } else {
770    fPrintFilename = "G4OpenGL";  // by default
771  }
772  if (inc) {
773    fPrintFilenameIndex=0;
774  } else {
775    fPrintFilenameIndex=-1;
776  }
777}
778
779std::string G4OpenGLViewer::getRealPrintFilename() {
780  std::string temp = fPrintFilename;
781  if (fPrintFilenameIndex != -1) {
782    temp += std::string("_");
783    std::ostringstream os;
784    os << fPrintFilenameIndex;
785    std::string nb_str = os.str();
786    temp += nb_str;
787  }
788  temp += ".eps";
789  return temp;
790}
791
792GLdouble G4OpenGLViewer::getSceneNearWidth()
793{
794  if (!fSceneHandler.GetScene()) {
795    return 0;
796  }
797  const G4Point3D targetPoint
798    = fSceneHandler.GetScene()->GetStandardTargetPoint()
799    + fVP.GetCurrentTargetPoint ();
800  G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
801  if(radius<=0.) radius = 1.;
802  const G4double cameraDistance = fVP.GetCameraDistance (radius);
803  const GLdouble pnear   = fVP.GetNearDistance (cameraDistance, radius);
804  return 2 * fVP.GetFrontHalfHeight (pnear, radius);
805}
806
807GLdouble G4OpenGLViewer::getSceneFarWidth()
808{
809  if (!fSceneHandler.GetScene()) {
810    return 0;
811  }
812  const G4Point3D targetPoint
813    = fSceneHandler.GetScene()->GetStandardTargetPoint()
814    + fVP.GetCurrentTargetPoint ();
815  G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
816  if(radius<=0.) radius = 1.;
817  const G4double cameraDistance = fVP.GetCameraDistance (radius);
818  const GLdouble pnear   = fVP.GetNearDistance (cameraDistance, radius);
819  const GLdouble pfar    = fVP.GetFarDistance  (cameraDistance, pnear, radius);
820  return 2 * fVP.GetFrontHalfHeight (pfar, radius);
821}
822
823
824GLdouble G4OpenGLViewer::getSceneDepth()
825{
826  if (!fSceneHandler.GetScene()) {
827    return 0;
828  }
829  const G4Point3D targetPoint
830    = fSceneHandler.GetScene()->GetStandardTargetPoint()
831    + fVP.GetCurrentTargetPoint ();
832  G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
833  if(radius<=0.) radius = 1.;
834  const G4double cameraDistance = fVP.GetCameraDistance (radius);
835  const GLdouble pnear   = fVP.GetNearDistance (cameraDistance, radius);
836  return fVP.GetFarDistance  (cameraDistance, pnear, radius)- pnear;
837}
838
839
840
841void G4OpenGLViewer::rotateScene(G4double dx, G4double dy,G4double deltaRotation)
842{
843  if (!fSceneHandler.GetScene()) {
844    return;
845  }
846
847  G4Vector3D vp;
848  G4Vector3D up;
849 
850  G4Vector3D xprime;
851  G4Vector3D yprime;
852  G4Vector3D zprime;
853 
854  G4double delta_alpha;
855  G4double delta_theta;
856 
857  G4Vector3D new_vp;
858  G4Vector3D new_up;
859 
860  G4double cosalpha;
861  G4double sinalpha;
862 
863  G4Vector3D a1;
864  G4Vector3D a2;
865  G4Vector3D delta;
866  G4Vector3D viewPoint;
867
868   
869  //phi spin stuff here
870 
871  vp = fVP.GetViewpointDirection ().unit ();
872  up = fVP.GetUpVector ().unit ();
873 
874  yprime = (up.cross(vp)).unit();
875  zprime = (vp.cross(yprime)).unit();
876 
877  if (fVP.GetLightsMoveWithCamera()) {
878    delta_alpha = dy * deltaRotation;
879    delta_theta = -dx * deltaRotation;
880  } else {
881    delta_alpha = -dy * deltaRotation;
882    delta_theta = dx * deltaRotation;
883  }   
884 
885  delta_alpha *= deg;
886  delta_theta *= deg;
887 
888  new_vp = std::cos(delta_alpha) * vp + std::sin(delta_alpha) * zprime;
889 
890  // to avoid z rotation flipping
891  // to allow more than 360° rotation
892
893  const G4Point3D targetPoint
894    = fSceneHandler.GetScene()->GetStandardTargetPoint()
895    + fVP.GetCurrentTargetPoint ();
896  G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
897  if(radius<=0.) radius = 1.;
898  const G4double cameraDistance = fVP.GetCameraDistance (radius);
899  const G4Point3D cameraPosition =
900    targetPoint + cameraDistance * fVP.GetViewpointDirection().unit();
901
902  if (fVP.GetLightsMoveWithCamera()) {
903    new_up = (new_vp.cross(yprime)).unit();
904    if (new_vp.z()*vp.z() <0) {
905      new_up.set(new_up.x(),-new_up.y(),new_up.z());
906    }
907  } else {
908    new_up = up;
909    if (new_vp.z()*vp.z() <0) {
910      new_up.set(new_up.x(),-new_up.y(),new_up.z());
911    }
912  }
913  fVP.SetUpVector(new_up);
914  ////////////////
915  // Rotates by fixed azimuthal angle delta_theta.
916 
917  cosalpha = new_up.dot (new_vp.unit());
918  sinalpha = std::sqrt (1. - std::pow (cosalpha, 2));
919  yprime = (new_up.cross (new_vp.unit())).unit ();
920  xprime = yprime.cross (new_up);
921  // Projection of vp on plane perpendicular to up...
922  a1 = sinalpha * xprime;
923  // Required new projection...
924  a2 = sinalpha * (std::cos (delta_theta) * xprime + std::sin (delta_theta) * yprime);
925  // Required Increment vector...
926  delta = a2 - a1;
927  // So new viewpoint is...
928  viewPoint = new_vp.unit() + delta;
929 
930  fVP.SetViewAndLights (viewPoint);
931}
932
933#endif
Note: See TracBrowser for help on using the repository browser.