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

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

update CVS release candidate geant4.9.3.01

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