source: trunk/source/visualization/OpenGL/src/G4OpenGLXViewer.cc @ 891

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

pre-tag revision and some improvments

  • Property svn:mime-type set to text/cpp
File size: 18.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: G4OpenGLXViewer.cc,v 1.42 2007/05/25 10:47:17 allison Exp $
28// GEANT4 tag $Name: HEAD $
29//
30//
31// Andrew Walkden  7th February 1997
32// G4OpenGLXViewer : Class to provide XWindows specific
33//                 functionality for OpenGL in GEANT4
34
35#ifdef G4VIS_BUILD_OPENGLX_DRIVER
36
37#include "G4OpenGLXViewer.hh"
38
39#include "G4OpenGLFontBaseStore.hh"
40
41#include <sstream>
42
43#include "G4VisExtent.hh"
44#include "G4LogicalVolume.hh"
45#include "G4VSolid.hh"
46#include "G4Point3D.hh"
47#include "G4Normal3D.hh"
48
49#include <X11/Xatom.h>
50#include <X11/Xutil.h>
51
52#include <assert.h>
53
54int G4OpenGLXViewer::snglBuf_RGBA[12] =
55{ GLX_RGBA,
56  GLX_RED_SIZE, 1,
57  GLX_GREEN_SIZE, 1,
58  GLX_BLUE_SIZE, 1,
59  GLX_DEPTH_SIZE, 1,
60  GLX_STENCIL_SIZE, 1,
61  None };
62
63int G4OpenGLXViewer::dblBuf_RGBA[13] =
64{ GLX_RGBA,
65  GLX_RED_SIZE, 1,
66  GLX_GREEN_SIZE, 1,
67  GLX_BLUE_SIZE, 1,
68  GLX_DOUBLEBUFFER,
69  GLX_DEPTH_SIZE, 1,
70  GLX_STENCIL_SIZE, 1,
71  None };
72
73#define NewString(str) \
74 ((str) != NULL ? (strcpy((char*)malloc((unsigned)strlen(str) + 1), str)) : (char*)NULL)
75
76#define USE_DEFAULT_COLORMAP 1
77#define USE_STANDARD_COLORMAP 0
78
79XVisualInfo*  G4OpenGLXViewer::vi_single_buffer = 0;
80XVisualInfo*  G4OpenGLXViewer::vi_double_buffer = 0;
81
82extern "C" {
83  static Bool G4OpenGLXViewerWaitForNotify (Display*, XEvent* e, char* arg) {
84    return (e->type == MapNotify) && (e->xmap.window == (Window) arg);
85  }
86}
87
88void G4OpenGLXViewer::SetView () {
89  glXMakeCurrent (dpy, win, cx);
90  G4OpenGLViewer::SetView (); 
91}
92
93void G4OpenGLXViewer::ShowView () {
94  glXWaitGL (); //Wait for effects of all previous OpenGL commands to
95                //be propagated before progressing.
96  glFlush ();
97
98  if (fVP.IsPicking()) {
99    G4cout <<
100      "Window activated for picking (left-mouse), exit (middle-mouse)."
101           << G4endl;
102    while (true) {
103      if (XPending(dpy)) {
104        XNextEvent(dpy, &event);
105        if (event.type == ButtonPress && event.xbutton.button == 1) {
106          Pick(event.xbutton.x, event.xbutton.y);
107        }
108        else if (event.type == ButtonPress && event.xbutton.button == 2) break;
109      }
110    }
111  }
112}
113
114void G4OpenGLXViewer::GetXConnection () {
115// get a connection.
116  dpy = XOpenDisplay (0);
117  if (!dpy) {
118    fViewId = -1;  // This flags an error.
119    G4cerr << "G4OpenGLViewer::G4OpenGLViewer couldn't open display." << G4endl;
120    return;
121  }
122
123// make sure OpenGL is supported and installed properly.
124  if (!glXQueryExtension (dpy, &errorBase, &eventBase)) {
125    fViewId = -1;  // This flags an error.
126    G4cerr << "G4OpenGLViewer::G4OpenGLViewer X Server has no GLX extension."
127         << G4endl;
128    return;
129  }
130
131}
132
133void G4OpenGLXViewer::CreateGLXContext (XVisualInfo* v) {
134
135  vi = v;
136// get window's attributes
137  if (!XGetWindowAttributes(dpy, XRootWindow (dpy, vi -> screen), &xwa)) {
138    fViewId = -1;  // This flags an error.
139    G4cerr << "G4OpenGLViewer::G4OpenGLViewer couldn't return window attributes"
140         << G4endl;
141    return;
142  }
143 
144// create a GLX context
145  cx = glXCreateContext (dpy, vi, 0, true);
146  if (!cx) {
147    fViewId = -1;  // This flags an error.
148    G4cerr << "G4OpenGLViewer::G4OpenGLViewer couldn't create context."
149         << G4endl;
150    return;
151  }
152
153// New stab at getting a colormap
154
155  Status status;
156  XStandardColormap *standardCmaps = XAllocStandardColormap ();
157  int i, numCmaps;
158
159  status = XmuLookupStandardColormap (dpy,
160                                      vi -> screen,
161                                      vi -> visualid,
162                                      vi -> depth,
163                                      XA_RGB_DEFAULT_MAP,
164                                      False,
165                                      True);
166 
167  if (status == 1) {
168    cmap = 0;
169    status = XGetRGBColormaps (dpy,
170                               XRootWindow (dpy, vi -> screen),
171                               &standardCmaps,
172                               &numCmaps,
173                               XA_RGB_DEFAULT_MAP);
174    if (status == 1)
175      for (i = 0; i < numCmaps; i++) {
176        if (standardCmaps[i].visualid == vi -> visualid) {
177          cmap = standardCmaps[i].colormap;
178          XFree (standardCmaps);
179          break;
180        }
181      }
182    if (!cmap) {
183      fViewId = -1;  // This flags an error.
184      G4cerr <<
185   "G4OpenGLViewer::G4OpenGLViewer failed to allocate a standard colormap."
186             << G4endl;
187      return;
188    }
189    G4cout << "Got standard cmap" << G4endl;
190  } else {
191    cmap = XCreateColormap (dpy,
192                            XRootWindow(dpy, vi -> screen),
193                            vi -> visual,
194                            AllocNone);
195    G4cout << "Created own cmap" << G4endl;
196  }
197
198  if (!cmap) {
199    fViewId = -1;  // This flags an error.
200    G4cerr << "G4OpenGLViewer::G4OpenGLViewer failed to allocate a Colormap."
201         << G4endl;
202    return;
203  }
204
205}
206 
207void G4OpenGLXViewer::CreateMainWindow () {
208 
209// create a window
210  swa.colormap = cmap;
211  swa.border_pixel = 0;
212  swa.event_mask = ExposureMask | ButtonPressMask | StructureNotifyMask;
213  swa.backing_store = WhenMapped;
214
215  // Window size and position...
216  unsigned int width, height;
217  x_origin = 0;
218  y_origin = 0;
219  size_hints = XAllocSizeHints();
220
221  // already done in G4VViewer at creation
222
223//   const G4String& XGeometryString = fVP.GetXGeometryString();
224//   int screen_num = DefaultScreen(dpy);
225//   if (!XGeometryString.empty()) {
226//     G4int geometryResultMask = XParseGeometry
227//       ((char*)XGeometryString.c_str(),
228//        &x_origin, &y_origin, &width, &height);
229//     if (geometryResultMask & (WidthValue | HeightValue)) {
230//       if (geometryResultMask & XValue) {
231//      if (geometryResultMask & XNegative) {
232//        x_origin = DisplayWidth(dpy, screen_num) + x_origin - width;
233//      }
234//      size_hints->flags |= PPosition;
235//      size_hints->x = x_origin;
236//       }
237//       if (geometryResultMask & YValue) {
238//      if (geometryResultMask & YNegative) {
239//        y_origin = DisplayHeight(dpy, screen_num) + y_origin - height;
240//      }
241//      size_hints->flags |= PPosition;
242//      size_hints->y = y_origin;
243//       }
244//     } else {
245//       G4cout << "ERROR: Geometry string \""
246//           << XGeometryString
247//           << "\" invalid.  Using \"600x600\"."
248//           << G4endl;
249//       width = 600;
250//       height = 600;
251//     }
252//   }
253//  size_hints->width = width;
254//  size_hints->height = height;
255
256#ifdef G4DEBUG
257  printf("CreateWindow Size:%d=%d - %d=%d \n",width,fVP.GetWindowSizeHintX(),height, fVP.GetWindowSizeHintY());
258#endif
259
260  size_hints->width = fVP.GetWindowSizeHintX();
261  size_hints->height = fVP.GetWindowSizeHintY();
262  size_hints->flags |= PSize;
263
264  //  G4int                             WinSize_x;
265  //  G4int                             WinSize_y;
266  WinSize_x = width;
267  WinSize_y = height;
268
269  G4cout << "Window name: " << fName << G4endl;
270  strncpy (charViewName, fName, 100);
271  char *window_name = charViewName;
272  char *icon_name = charViewName;
273  //char tmpatom[] = "XA_WM_NORMAL_HINTS";
274  wm_hints = XAllocWMHints();
275  class_hints = XAllocClassHint();
276
277  XStringListToTextProperty (&window_name, 1, &windowName);
278  XStringListToTextProperty (&icon_name, 1, &iconName);
279
280  wm_hints -> initial_state = NormalState;
281  wm_hints -> input = True;
282  wm_hints -> icon_pixmap = icon_pixmap;
283  wm_hints -> flags = StateHint | IconPixmapHint | InputHint;
284
285  class_hints -> res_name  = NewString("G4OpenGL");
286  class_hints -> res_class = NewString("G4OpenGL");
287
288  win = XCreateWindow (dpy, XRootWindow (dpy, vi -> screen), x_origin,
289                       y_origin, WinSize_x, WinSize_y, 0, vi -> depth,
290                       InputOutput, vi -> visual, 
291                       CWBorderPixel | CWColormap |
292                       CWEventMask | CWBackingStore,
293                       &swa);
294 
295  XSetWMProperties (dpy, win, &windowName, &iconName, 0, 0,
296                    size_hints, wm_hints, class_hints);
297 
298// request X to Draw window on screen.
299  XMapWindow (dpy, win);
300
301// Wait for window to appear (wait for an "expose" event).
302  XIfEvent (dpy, &event, G4OpenGLXViewerWaitForNotify, (char*) win);
303
304// connect the context to a window
305  Bool success = glXMakeCurrent (dpy, win, cx);
306  if (!success) {
307    fViewId = -1;  // This flags an error.
308    G4cerr << "G4OpenGLViewer::G4OpenGLViewer failed to attach a GLX context."
309         << G4endl;
310    GLint error = GL_NO_ERROR;
311    while ((error = glGetError()) != GL_NO_ERROR) {
312      G4cout << "GL Error: " << gluErrorString(error) << G4endl;
313    }
314    return;
315  }
316
317}
318
319void G4OpenGLXViewer::CreateFontLists () {
320
321  std::map<G4double,G4String> fonts;  // G4VMarker screen size and font name.
322  fonts[10.] = "-adobe-courier-bold-r-normal--10-100-75-75-m-60-iso8859-1";
323  fonts[11.] = "-adobe-courier-bold-r-normal--11-80-100-100-m-60-iso8859-1";
324  fonts[12.] = "-adobe-courier-bold-r-normal--12-120-75-75-m-70-iso8859-1";
325  fonts[13.] = "fixed";
326  fonts[14.] = "-adobe-courier-bold-r-normal--14-100-100-100-m-90-iso8859-1";
327  fonts[17.] = "-adobe-courier-bold-r-normal--17-120-100-100-m-100-iso8859-1";
328  fonts[18.] = "-adobe-courier-bold-r-normal--18-180-75-75-m-110-iso8859-1";
329  fonts[20.] = "-adobe-courier-bold-r-normal--20-140-100-100-m-110-iso8859-1";
330  fonts[24.] = "-adobe-courier-bold-r-normal--24-240-75-75-m-150-iso8859-1";
331  fonts[25.] = "-adobe-courier-bold-r-normal--25-180-100-100-m-150-iso8859-1";
332  fonts[34.] = "-adobe-courier-bold-r-normal--34-240-100-100-m-200-iso8859-1";
333  std::map<G4double,G4String>::const_iterator i;
334  for (i = fonts.begin(); i != fonts.end(); ++i) {
335    XFontStruct* font_info = XLoadQueryFont(dpy, i->second);
336    if (!font_info) {
337      G4cerr <<
338        "G4OpenGLXViewer: XLoadQueryFont failed for font\n  "
339             << i->second
340             << G4endl;
341      continue;
342    }
343    G4int font_base = glGenLists(256);
344    if (!font_base) {
345      G4cerr << "G4OpenGLXViewer: out of display lists for fonts."
346             << G4endl;
347      continue;
348    }
349    G4int first = font_info->min_char_or_byte2;
350    G4int last  = font_info->max_char_or_byte2;
351    glXUseXFont(font_info->fid, first, last-first+1,font_base+first);
352    G4OpenGLFontBaseStore::AddFontBase(this,font_base,i->first,i->second);
353  }
354}
355
356G4OpenGLXViewer::G4OpenGLXViewer (G4OpenGLSceneHandler& scene):
357G4VViewer (scene, -1),
358G4OpenGLViewer (scene),
359vi_immediate (0),
360vi_stored (0),
361vi (0),
362cmap (0)
363{
364  GetXConnection ();
365  if (fViewId < 0) return;
366 
367  // Try for a visual suitable for OpenGLImmediate..
368  // first try for a single buffered RGB window
369  if (!vi_single_buffer) {
370    vi_single_buffer =
371      glXChooseVisual (dpy, XDefaultScreen (dpy), snglBuf_RGBA);
372  }
373  if (!vi_double_buffer) {
374    vi_double_buffer =
375      glXChooseVisual (dpy, XDefaultScreen (dpy), dblBuf_RGBA);
376  }
377
378  if (vi_single_buffer || vi_double_buffer) {
379    if (!vi_double_buffer) {
380      G4cout <<
381        "G4OpenGLXViewer::G4OpenGLXViewer: unable to get a double buffer visual."
382        "\n  Working with a single buffer."
383             << G4endl;
384    }
385  } else {
386    if (!vi_single_buffer) {
387      G4cout <<
388        "G4OpenGLXViewer::G4OpenGLXViewer: unable to get a single buffer visual."
389             << G4endl;
390    }
391    if (!vi_double_buffer) {
392      G4cout <<
393        "G4OpenGLXViewer::G4OpenGLXViewer: unable to get a double buffer visual."
394             << G4endl;
395    }
396  }
397
398  if (vi_single_buffer) {
399    vi_immediate = vi_single_buffer;
400    attributeList = snglBuf_RGBA;
401  }
402 
403  if (!vi_immediate){
404    // next try for a double buffered RGB, but Draw to top buffer
405    if (vi_double_buffer) {
406      vi_immediate = vi_double_buffer;
407      attributeList = dblBuf_RGBA;
408    }
409  }
410
411  // Now try for a visual suitable for OpenGLStored...
412  // Try for a double buffered RGB window
413  if (vi_double_buffer) {
414    vi_stored = vi_double_buffer;
415    attributeList = dblBuf_RGBA;
416  }
417
418  if (!vi_immediate || !vi_stored) {
419    G4cout <<
420    "G4OpenGLXViewer::G4OpenGLXViewer: unable to get required visuals."
421           << G4endl;
422    fViewId = -1;  // This flags an error.
423  }
424
425  //  glClearColor (0., 0., 0., 0.);
426  //  glClearDepth (1.);
427}
428
429G4OpenGLXViewer::~G4OpenGLXViewer () {
430  if (fViewId >= 0) {
431    //Close a window from here
432    glXMakeCurrent (dpy, None, NULL);
433    glXDestroyContext (dpy, cx);
434    if (win) XDestroyWindow (dpy, win); // ...if already deleted in
435    // sub-class G4OpenGLXmViewer.
436    XFlush (dpy);
437  }
438}
439
440void G4OpenGLXViewer::print() {
441 
442  //using namespace std;
443  //cout << "print_col_callback requested with file name: " << print_string << G4endl;
444 
445  if (vectored_ps) {
446
447    G4OpenGLViewer::print();
448
449  } else {
450
451    XVisualInfo* pvi;
452    GLXContext pcx = create_GL_print_context(pvi);
453
454    if (!pcx) {
455      G4cout << "Unable to create print context." << G4endl;
456      return;
457    }
458
459    GLXContext tmp_cx;
460    tmp_cx = cx;
461    cx=pcx;
462   
463    Pixmap pmap = XCreatePixmap (dpy,
464                                 XRootWindow (dpy, pvi->screen),
465                                 WinSize_x, WinSize_y,
466                                 pvi->depth);
467   
468    GLXPixmap glxpmap = glXCreateGLXPixmap (dpy,
469                                            pvi,
470                                            pmap);
471   
472    GLXDrawable tmp_win;
473    tmp_win=win;
474    win=glxpmap;
475   
476    glXMakeCurrent (dpy,
477                    win,
478                    cx);
479   
480    glViewport (0, 0, WinSize_x, WinSize_y);
481   
482    ClearView ();
483    SetView ();
484    DrawView ();
485   
486    generateEPS (print_string,
487                 print_colour,
488                 WinSize_x, WinSize_y);
489   
490    win=tmp_win;
491    cx=tmp_cx;
492   
493    glXMakeCurrent (dpy,
494                    win,
495                    cx);
496   
497  }
498
499}
500
501GLubyte* G4OpenGLXViewer::grabPixels (int inColor, unsigned int width, unsigned int height) {
502 
503  GLubyte* buffer;
504  GLint swapbytes, lsbfirst, rowlength;
505  GLint skiprows, skippixels, alignment;
506  GLenum format;
507  int size;
508
509  if (inColor) {
510    format = GL_RGB;
511    size = width*height*3;
512  } else {
513    format = GL_LUMINANCE;
514    size = width*height*1;
515  }
516
517  buffer = new GLubyte[size];
518  if (buffer == NULL)
519    return NULL;
520
521  glGetIntegerv (GL_UNPACK_SWAP_BYTES, &swapbytes);
522  glGetIntegerv (GL_UNPACK_LSB_FIRST, &lsbfirst);
523  glGetIntegerv (GL_UNPACK_ROW_LENGTH, &rowlength);
524
525  glGetIntegerv (GL_UNPACK_SKIP_ROWS, &skiprows);
526  glGetIntegerv (GL_UNPACK_SKIP_PIXELS, &skippixels);
527  glGetIntegerv (GL_UNPACK_ALIGNMENT, &alignment);
528
529  glPixelStorei (GL_UNPACK_SWAP_BYTES, GL_FALSE);
530  glPixelStorei (GL_UNPACK_LSB_FIRST, GL_FALSE);
531  glPixelStorei (GL_UNPACK_ROW_LENGTH, 0);
532
533  glPixelStorei (GL_UNPACK_SKIP_ROWS, 0);
534  glPixelStorei (GL_UNPACK_SKIP_PIXELS, 0);
535  glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
536
537  glReadPixels (0, 0, (GLsizei)width, (GLsizei)height, format, GL_UNSIGNED_BYTE, (GLvoid*) buffer);
538
539  glPixelStorei (GL_UNPACK_SWAP_BYTES, swapbytes);
540  glPixelStorei (GL_UNPACK_LSB_FIRST, lsbfirst);
541  glPixelStorei (GL_UNPACK_ROW_LENGTH, rowlength);
542 
543  glPixelStorei (GL_UNPACK_SKIP_ROWS, skiprows);
544  glPixelStorei (GL_UNPACK_SKIP_PIXELS, skippixels);
545  glPixelStorei (GL_UNPACK_ALIGNMENT, alignment);
546 
547  return buffer;
548}
549
550int G4OpenGLXViewer::generateEPS (char* filnam,
551                                int inColour,
552                                unsigned int width,
553                                unsigned int height) {
554
555  FILE* fp;
556  GLubyte* pixels;
557  GLubyte* curpix;
558  int components, pos, i;
559
560  pixels = grabPixels (inColour, width, height);
561
562  if (pixels == NULL)
563    return 1;
564  if (inColour) {
565    components = 3;
566  } else {
567    components = 1;
568  }
569 
570  fp = fopen (filnam, "w");
571  if (fp == NULL) {
572    return 2;
573  }
574 
575  fprintf (fp, "%%!PS-Adobe-2.0 EPSF-1.2\n");
576  fprintf (fp, "%%%%Title: %s\n", filnam);
577  fprintf (fp, "%%%%Creator: OpenGL pixmap render output\n");
578  fprintf (fp, "%%%%BoundingBox: 0 0 %d %d\n", width, height);
579  fprintf (fp, "%%%%EndComments\n");
580  fprintf (fp, "gsave\n");
581  fprintf (fp, "/bwproc {\n");
582  fprintf (fp, "    rgbproc\n");
583  fprintf (fp, "    dup length 3 idiv string 0 3 0 \n");
584  fprintf (fp, "    5 -1 roll {\n");
585  fprintf (fp, "    add 2 1 roll 1 sub dup 0 eq\n");
586  fprintf (fp, "    { pop 3 idiv 3 -1 roll dup 4 -1 roll dup\n");
587  fprintf (fp, "       3 1 roll 5 -1 roll } put 1 add 3 0 \n");
588  fprintf (fp, "    { 2 1 roll } ifelse\n");
589  fprintf (fp, "    }forall\n");
590  fprintf (fp, "    pop pop pop\n");
591  fprintf (fp, "} def\n");
592  fprintf (fp, "systemdict /colorimage known not {\n");
593  fprintf (fp, "   /colorimage {\n");
594  fprintf (fp, "       pop\n");
595  fprintf (fp, "       pop\n");
596  fprintf (fp, "       /rgbproc exch def\n");
597  fprintf (fp, "       { bwproc } image\n");
598  fprintf (fp, "   }  def\n");
599  fprintf (fp, "} if\n");
600  fprintf (fp, "/picstr %d string def\n", width * components);
601  fprintf (fp, "%d %d scale\n", width, height);
602  fprintf (fp, "%d %d %d\n", width, height, 8);
603  fprintf (fp, "[%d 0 0 %d 0 0]\n", width, height);
604  fprintf (fp, "{currentfile picstr readhexstring pop}\n");
605  fprintf (fp, "false %d\n", components);
606  fprintf (fp, "colorimage\n");
607 
608  curpix = (GLubyte*) pixels;
609  pos = 0;
610  for (i = width*height*components; i>0; i--) {
611    fprintf (fp, "%02hx ", *(curpix++));
612    if (++pos >= 32) {
613      fprintf (fp, "\n");
614      pos = 0;
615    }
616  }
617  if (pos)
618    fprintf (fp, "\n");
619
620  fprintf (fp, "grestore\n");
621  fprintf (fp, "showpage\n");
622  delete pixels;
623  fclose (fp);
624  return 0;
625}
626
627GLXContext G4OpenGLXViewer::create_GL_print_context(XVisualInfo*& pvi) {
628 
629  pvi = glXChooseVisual (dpy,
630                         XDefaultScreen (dpy),
631                         snglBuf_RGBA);
632
633  if (!pvi) {
634    pvi = glXChooseVisual (dpy,
635                           XDefaultScreen (dpy),
636                           dblBuf_RGBA);
637  }
638
639  return glXCreateContext (dpy,
640                           pvi,
641                           NULL,
642                           False);
643}
644
645#endif
Note: See TracBrowser for help on using the repository browser.