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

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

Fix of bad initialization from XGeometry

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