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

Last change on this file since 1247 was 1245, checked in by garnier, 14 years ago

update

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