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

Last change on this file since 1346 was 1346, checked in by garnier, 13 years ago

before tag

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