xref: /petsc/src/sys/classes/viewer/impls/glvis/glvis.c (revision 50daf06db6f4c83fd9f199fe2bd33135926c3d95)
1 #define PETSC_DESIRE_FEATURE_TEST_MACROS /* for fdopen */
2 
3 #include <petsc/private/viewerimpl.h> /*I   "petscviewer.h" I*/
4 #include <petsc/private/petscimpl.h>  /*I   "petscsys.h"    I*/
5 #include <petsc/private/glvisviewerimpl.h>
6 
7 /* we may eventually make this function public */
8 static PetscErrorCode PetscViewerASCIISocketOpen(MPI_Comm,const char*,PetscInt,PetscViewer*);
9 
10 struct _n_PetscViewerGLVis {
11   PetscViewerGLVisStatus status;
12   PetscViewerGLVisType   type;                                                  /* either PETSC_VIEWER_GLVIS_DUMP or PETSC_VIEWER_GLVIS_SOCKET */
13   char                   *name;                                                 /* prefix for filename, or hostname, depending on the type */
14   PetscInt               port;                                                  /* used just for the socket case */
15   PetscReal              pause;                                                 /* if positive, calls PetscSleep(pause) after each VecView_GLVis call */
16   PetscViewer            meshwindow;                                            /* used just by the ASCII dumping */
17   PetscObject            dm;                                                    /* DM as passed by PetscViewerGLVisSetDM_Private(): should contain discretization info */
18   PetscInt               nwindow;                                               /* number of windows/fields to be visualized */
19   PetscViewer            *window;
20   char                   **windowtitle;
21   char                   **fec_type;                                            /* type of elements to be used for visualization, see FiniteElementCollection::Name() */
22   PetscErrorCode         (*g2lfield)(PetscObject,PetscInt,PetscObject[],void*); /* global to local operation for generating dofs to be visualized */
23   PetscInt               *locandbs;                                             /* local and block sizes for work vectors */
24   PetscObject            *Ufield;                                               /* work vectors for visualization */
25   PetscInt               snapid;                                                /* snapshot id, use PetscViewerGLVisSetSnapId to change this value*/
26   void                   *userctx;                                              /* User context, used by g2lfield */
27   PetscErrorCode         (*destroyctx)(void*);                                  /* destroy routine for userctx */
28 };
29 typedef struct _n_PetscViewerGLVis *PetscViewerGLVis;
30 
31 /*@
32      PetscViewerGLVisSetSnapId - Set the snapshot id. Only relevant when the viewer is of type PETSC_VIEWER_GLVIS_DUMP
33 
34   Logically Collective on PetscViewer
35 
36   Input Parameters:
37 +  viewer - the PetscViewer
38 -  id     - the current snapshot id in a time-dependent simulation
39 
40   Level: beginner
41 
42 .seealso: PetscViewerGLVisOpen(), PetscViewerCreate(), PetscViewerSetType()
43 @*/
44 PetscErrorCode PetscViewerGLVisSetSnapId(PetscViewer viewer, PetscInt id)
45 {
46   PetscErrorCode ierr;
47 
48   PetscFunctionBegin;
49   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,1);
50   PetscValidLogicalCollectiveInt(viewer,id,2);
51   ierr = PetscTryMethod(viewer,"PetscViewerGLVisSetSnapId_C",(PetscViewer,PetscInt),(viewer,id));CHKERRQ(ierr);
52   PetscFunctionReturn(0);
53 }
54 
55 static PetscErrorCode PetscViewerGLVisSetSnapId_GLVis(PetscViewer viewer, PetscInt id)
56 {
57   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
58 
59   PetscFunctionBegin;
60   socket->snapid = id;;
61   PetscFunctionReturn(0);
62 }
63 
64 /*
65      PetscViewerGLVisSetFields - Sets the required information to visualize different fields from within a vector.
66 
67   Logically Collective on PetscViewer
68 
69   Input Parameters:
70 +  viewer     - the PetscViewer
71 .  nf         - number of fields to be visualized
72 .  namefield  - optional name for each field
73 .  fec_type   - the type of finite element to be used to visualize the data (see FiniteElementCollection::Name() in MFEM)
74 .  nlocal     - array of local sizes for field vectors (can be NULL if nf == 1)
75 .  bs         - array of block sizes for field vectors (can be NULL if nf == 1)
76 .  g2lfields  - User routine to compute the local field vectors to be visualized; PetscObject is used in place of Vec on the prototype
77 .  ctx        - User context to store the relevant data to apply g2lfields
78 -  destroyctx - Destroy function for userctx
79 
80   Notes: g2lfields is called on the Vec V to be visualized, in order to extract the relevant dofs to be put in Vfield[], as
81 .vb
82   g2lfields((PetscObject)V,nfields,(PetscObject*)Vfield[],ctx). Misses Fortran binding
83 .ve
84 
85   Level: intermediate
86 
87 .seealso: PetscViewerGLVisOpen(), PetscViewerCreate(), PetscViewerSetType()
88 */
89 PetscErrorCode PetscViewerGLVisSetFields(PetscViewer viewer, PetscInt nf, const char* namefield[], const char* fec_type[], PetscInt nlocal[], PetscInt bs[], PetscErrorCode(*g2l)(PetscObject,PetscInt,PetscObject[],void*), void* ctx, PetscErrorCode(*destroyctx)(void*))
90 {
91   PetscErrorCode ierr;
92 
93   PetscFunctionBegin;
94   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,1);
95   PetscValidLogicalCollectiveInt(viewer,nf,2);
96   if (namefield) PetscValidPointer(namefield,3);
97   if (!fec_type) SETERRQ(PetscObjectComm((PetscObject)viewer),PETSC_ERR_SUP,"You need to provide the FiniteElementCollection names for the fields");
98   PetscValidPointer(fec_type,4);
99   if (nf > 1) {
100     PetscValidPointer(nlocal,5);
101     PetscValidPointer(bs,6);
102   }
103   ierr = PetscTryMethod(viewer,"PetscViewerGLVisSetFields_C",(PetscViewer,PetscInt,const char*[],const char*[],PetscInt[],PetscInt[],PetscErrorCode(*)(PetscObject,PetscInt,PetscObject[],void*),void*,PetscErrorCode(*)(void*)),(viewer,nf,namefield,fec_type,nlocal,bs,g2l,ctx,destroyctx));CHKERRQ(ierr);
104   PetscFunctionReturn(0);
105 }
106 
107 static PetscErrorCode PetscViewerGLVisSetFields_GLVis(PetscViewer viewer, PetscInt nfields, const char* namefield[], const char* fec_type[], PetscInt nlocal[], PetscInt bs[], PetscErrorCode(*g2l)(PetscObject,PetscInt,PetscObject[],void*),void* ctx, PetscErrorCode(*destroyctx)(void*))
108 {
109   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
110   PetscInt         i;
111   PetscErrorCode   ierr;
112 
113   PetscFunctionBegin;
114   if (socket->nwindow && socket->nwindow != nfields) SETERRQ2(PetscObjectComm((PetscObject)viewer),PETSC_ERR_USER,"Cannot set number of fields %D with number of windows %D",nfields,socket->nwindow);
115   if (!socket->nwindow) {
116     socket->nwindow = nfields;
117 
118     ierr = PetscCalloc5(nfields,&socket->window,nfields,&socket->windowtitle,nfields,&socket->fec_type,2*nfields,&socket->locandbs,nfields,&socket->Ufield);CHKERRQ(ierr);
119     for (i=0;i<nfields;i++) {
120       if (!namefield || !namefield[i]) {
121         char name[16];
122 
123         ierr = PetscSNPrintf(name,16,"Field%d",i);CHKERRQ(ierr);
124         ierr = PetscStrallocpy(name,&socket->windowtitle[i]);CHKERRQ(ierr);
125       } else {
126         ierr = PetscStrallocpy(namefield[i],&socket->windowtitle[i]);CHKERRQ(ierr);
127       }
128       ierr = PetscStrallocpy(fec_type[i],&socket->fec_type[i]);CHKERRQ(ierr);
129       socket->locandbs[2*i  ] = nlocal[i];
130       socket->locandbs[2*i+1] = bs[i];
131     }
132   }
133   /* number of fields are not allowed to vary */
134   if (nfields != socket->nwindow) SETERRQ2(PetscObjectComm((PetscObject)viewer),PETSC_ERR_SUP,"Cannot visualize %D fields using %D socket windows",nfields,socket->nwindow);
135   socket->g2lfield = g2l;
136   if (socket->destroyctx && socket->userctx) { ierr = (*socket->destroyctx)(socket->userctx);CHKERRQ(ierr); }
137   socket->userctx = ctx;
138   socket->destroyctx = destroyctx;
139   PetscFunctionReturn(0);
140 }
141 
142 static PetscErrorCode PetscViewerGLVisInfoDestroy_Private(void *ptr)
143 {
144   PetscViewerGLVisInfo info = (PetscViewerGLVisInfo)ptr;
145   PetscErrorCode       ierr;
146 
147   PetscFunctionBeginUser;
148   ierr = PetscFree(info);CHKERRQ(ierr);
149   PetscFunctionReturn(0);
150 }
151 
152 /* we can decide to prevent specific processes from using the viewer */
153 static PetscErrorCode PetscViewerGLVisAttachInfo_Private(PetscViewer viewer, PetscViewer window)
154 {
155   PetscViewerGLVis     socket = (PetscViewerGLVis)viewer->data;
156   PetscErrorCode       ierr;
157   PetscContainer       container;
158   PetscViewerGLVisInfo info;
159 
160   PetscFunctionBeginUser;
161   ierr = PetscNew(&info);CHKERRQ(ierr);
162   info->enabled = PETSC_TRUE;
163   info->init    = PETSC_FALSE;
164   info->pause   = socket->pause;
165   ierr = PetscContainerCreate(PetscObjectComm((PetscObject)window),&container);CHKERRQ(ierr);
166   ierr = PetscContainerSetPointer(container,(void*)info);CHKERRQ(ierr);
167   ierr = PetscContainerSetUserDestroy(container,PetscViewerGLVisInfoDestroy_Private);CHKERRQ(ierr);
168   ierr = PetscObjectCompose((PetscObject)window,"_glvis_info_container",(PetscObject)container);CHKERRQ(ierr);
169   ierr = PetscContainerDestroy(&container);CHKERRQ(ierr);
170   PetscFunctionReturn(0);
171 }
172 
173 static PetscErrorCode PetscViewerGLVisGetNewWindow_Private(PetscViewer viewer,PetscViewer *view)
174 {
175   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
176   PetscViewer      window = NULL;
177   PetscBool        ldis,dis;
178   PetscErrorCode   ierr;
179 
180   PetscFunctionBegin;
181   ierr = PetscViewerASCIISocketOpen(PETSC_COMM_SELF,socket->name,socket->port,&window);
182   /* if we could not estabilish a connection the first time,
183      we disable the socket viewer */
184   ldis = ierr ? PETSC_TRUE : PETSC_FALSE;
185   ierr = MPI_Allreduce(&ldis,&dis,1,MPIU_BOOL,MPI_LOR,PetscObjectComm((PetscObject)viewer));CHKERRQ(ierr);
186   if (dis) {
187     socket->status = PETSCVIEWERGLVIS_DISABLED;
188     ierr  = PetscViewerDestroy(&window);CHKERRQ(ierr);
189   }
190   *view = window;
191   PetscFunctionReturn(0);
192 }
193 
194 PetscErrorCode PetscViewerGLVisPause_Private(PetscViewer viewer)
195 {
196   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
197   PetscErrorCode   ierr;
198 
199   PetscFunctionBegin;
200   if (socket->pause > 0) {
201     ierr = PetscSleep(socket->pause);CHKERRQ(ierr);
202   }
203   PetscFunctionReturn(0);
204 }
205 
206 /* DM specific support */
207 PetscErrorCode PetscViewerGLVisSetDM_Private(PetscViewer viewer, PetscObject dm)
208 {
209   PetscErrorCode   ierr;
210   PetscViewerGLVis socket  = (PetscViewerGLVis)viewer->data;
211 
212   PetscFunctionBegin;
213   if (socket->dm && socket->dm != dm) SETERRQ(PetscObjectComm((PetscObject)viewer),PETSC_ERR_SUP,"Cannot change DM associated with the GLVis viewer");
214   if (!socket->dm) {
215     PetscErrorCode (*setupwithdm)(PetscObject,PetscViewer) = NULL;
216 
217     ierr = PetscObjectQueryFunction(dm,"DMSetUpGLVisViewer_C",&setupwithdm);CHKERRQ(ierr);
218     if (setupwithdm) {
219       ierr = (*setupwithdm)(dm,viewer);CHKERRQ(ierr);
220     } else SETERRQ1(PetscObjectComm(dm),PETSC_ERR_SUP,"No support for DM type %s",dm->type_name);
221     ierr = PetscObjectReference(dm);CHKERRQ(ierr);
222     socket->dm = dm;
223   }
224   PetscFunctionReturn(0);
225 }
226 
227 PetscErrorCode PetscViewerGLVisGetDMWindow_Private(PetscViewer viewer,PetscViewer* view)
228 {
229   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
230   PetscErrorCode   ierr;
231 
232   PetscFunctionBegin;
233   if (!socket->meshwindow) {
234     if (socket->type == PETSC_VIEWER_GLVIS_SOCKET) {
235       ierr = PetscViewerGLVisGetNewWindow_Private(viewer,&socket->meshwindow);CHKERRQ(ierr);
236     } else {
237       PetscMPIInt rank;
238       char        filename[PETSC_MAX_PATH_LEN];
239 
240       ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)viewer),&rank);CHKERRQ(ierr);
241       ierr = PetscSNPrintf(filename,PETSC_MAX_PATH_LEN,"%s-mesh.%06d",socket->name,rank);CHKERRQ(ierr);
242       ierr = PetscViewerASCIIOpen(PETSC_COMM_SELF,filename,&socket->meshwindow);CHKERRQ(ierr);
243     }
244     if (socket->meshwindow) {
245       ierr = PetscViewerGLVisAttachInfo_Private(viewer,socket->meshwindow);CHKERRQ(ierr);
246       ierr = PetscViewerPushFormat(socket->meshwindow,PETSC_VIEWER_ASCII_GLVIS);CHKERRQ(ierr);
247     }
248   }
249   *view = socket->meshwindow;
250   PetscFunctionReturn(0);
251 }
252 
253 PetscErrorCode PetscViewerGLVisGetType_Private(PetscViewer viewer,PetscViewerGLVisType *type)
254 {
255   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
256 
257   PetscFunctionBegin;
258   PetscValidPointer(type,2);
259   *type = socket->type;
260   PetscFunctionReturn(0);
261 }
262 
263 /* This function is only relevant in the SOCKET_GLIVS case. The status is computed the first time it is requested, as GLVis currently has issues when connecting the first time through the socket */
264 PetscErrorCode PetscViewerGLVisGetStatus_Private(PetscViewer viewer, PetscViewerGLVisStatus *sockstatus)
265 {
266   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
267 
268   PetscFunctionBegin;
269   PetscValidPointer(sockstatus,2);
270   if (socket->type == PETSC_VIEWER_GLVIS_DUMP) {
271     socket->status = PETSCVIEWERGLVIS_DISCONNECTED;
272   } else if (socket->status == PETSCVIEWERGLVIS_DISCONNECTED && socket->nwindow) {
273     PetscInt       i;
274     PetscBool      lconn,conn;
275     PetscErrorCode ierr;
276 
277     for (i=0,lconn=PETSC_TRUE;i<socket->nwindow;i++)
278       if (!socket->window[i])
279         lconn = PETSC_FALSE;
280 
281     ierr = MPI_Allreduce(&lconn,&conn,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)viewer));CHKERRQ(ierr);
282     if (conn) socket->status = PETSCVIEWERGLVIS_CONNECTED;
283   }
284   *sockstatus = socket->status;
285   PetscFunctionReturn(0);
286 }
287 
288 PetscErrorCode PetscViewerGLVisGetDM_Private(PetscViewer viewer, PetscObject* dm)
289 {
290   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
291 
292   PetscFunctionBegin;
293   *dm = socket->dm;
294   PetscFunctionReturn(0);
295 }
296 
297 PetscErrorCode PetscViewerGLVisGetFields_Private(PetscViewer viewer, PetscInt* nfield, const char** names[], const char **fec[], PetscInt *locandbs[], PetscErrorCode(**g2lfield)(PetscObject,PetscInt,PetscObject[],void*), PetscObject *Ufield[], void **userctx)
298 {
299   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
300 
301   PetscFunctionBegin;
302   if (nfield)   *nfield   = socket->nwindow;
303   if (names)    *names    = (const char**)socket->windowtitle;
304   if (fec)      *fec      = (const char**)socket->fec_type;
305   if (locandbs) *locandbs = socket->locandbs;
306   if (g2lfield) *g2lfield = socket->g2lfield;
307   if (Ufield)   *Ufield   = socket->Ufield;
308   if (userctx)  *userctx  = socket->userctx;
309   PetscFunctionReturn(0);
310 }
311 
312 /* accessor routines for the viewer windows:
313    PETSC_VIEWER_GLVIS_DUMP   : it returns a new viewer every time
314    PETSC_VIEWER_GLVIS_SOCKET : it returns the socket, and creates it if not yet done.
315 */
316 PetscErrorCode PetscViewerGLVisGetWindow_Private(PetscViewer viewer,PetscInt wid,PetscViewer* view)
317 {
318   PetscViewerGLVis       socket = (PetscViewerGLVis)viewer->data;
319   PetscViewerGLVisStatus status;
320   PetscErrorCode         ierr;
321 
322   PetscFunctionBegin;
323   PetscValidLogicalCollectiveInt(viewer,wid,2);
324   PetscValidPointer(view,3);
325   if (wid < 0 || wid > socket->nwindow-1) SETERRQ2(PetscObjectComm((PetscObject)viewer),PETSC_ERR_USER,"Cannot get window id %D: allowed range [0,%D)",wid,socket->nwindow-1);
326   status = socket->status;
327   if (socket->type == PETSC_VIEWER_GLVIS_DUMP && socket->window[wid]) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_USER,"Window %D is already in use",wid);
328   switch (status) {
329     case PETSCVIEWERGLVIS_DISCONNECTED:
330       if (socket->window[wid]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,"This should not happen");
331       if (socket->type == PETSC_VIEWER_GLVIS_DUMP) {
332         PetscMPIInt rank;
333         char        filename[PETSC_MAX_PATH_LEN];
334 
335         ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)viewer),&rank);CHKERRQ(ierr);
336         ierr = PetscSNPrintf(filename,PETSC_MAX_PATH_LEN,"%s-%s-%d.%06d",socket->name,socket->windowtitle[wid],socket->snapid,rank);CHKERRQ(ierr);
337         ierr = PetscViewerASCIIOpen(PETSC_COMM_SELF,filename,&socket->window[wid]);CHKERRQ(ierr);
338       } else {
339         ierr = PetscViewerGLVisGetNewWindow_Private(viewer,&socket->window[wid]);CHKERRQ(ierr);
340       }
341       if (socket->window[wid]) {
342         ierr = PetscViewerGLVisAttachInfo_Private(viewer,socket->window[wid]);CHKERRQ(ierr);
343         ierr = PetscViewerPushFormat(socket->window[wid],PETSC_VIEWER_ASCII_GLVIS);CHKERRQ(ierr);
344       }
345       *view = socket->window[wid];
346       break;
347     case PETSCVIEWERGLVIS_CONNECTED:
348       *view = socket->window[wid];
349       break;
350     case PETSCVIEWERGLVIS_DISABLED:
351       *view = NULL;
352       break;
353     default:
354       SETERRQ1(PetscObjectComm((PetscObject)viewer),PETSC_ERR_SUP,"Unhandled socket status %d\n",(int)status);
355       break;
356   }
357   PetscFunctionReturn(0);
358 }
359 
360 /* Restore the window viewer
361    PETSC_VIEWER_GLVIS_DUMP  : destroys the temporary created ASCII viewer used for dumping
362    PETSC_VIEWER_GLVIS_SOCKET: - if the returned window viewer is not NULL, just zeros the pointer.
363                  - it the returned window viewer is NULL, assumes something went wrong
364                    with the socket (i.e. SIGPIPE when a user closes the popup window)
365                    and that the caller already handled it (see VecView_GLVis).
366 */
367 PetscErrorCode PetscViewerGLVisRestoreWindow_Private(PetscViewer viewer,PetscInt wid, PetscViewer* view)
368 {
369   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
370   PetscErrorCode   ierr;
371 
372   PetscFunctionBegin;
373   PetscValidLogicalCollectiveInt(viewer,wid,2);
374   PetscValidPointer(view,3);
375   if (wid < 0 || wid > socket->nwindow-1) SETERRQ2(PetscObjectComm((PetscObject)viewer),PETSC_ERR_USER,"Cannot restore window id %D: allowed range [0,%D)",wid,socket->nwindow);
376   if (*view && *view != socket->window[wid]) SETERRQ(PetscObjectComm((PetscObject)viewer),PETSC_ERR_USER,"Viewer was not obtained from PetscViewerGLVisGetWindow");
377   if (*view) {
378     ierr = PetscViewerFlush(*view);CHKERRQ(ierr);
379     ierr = PetscBarrier((PetscObject)viewer);CHKERRQ(ierr);
380   }
381   if (socket->type == PETSC_VIEWER_GLVIS_DUMP) { /* destroy the viewer, as it is associated with a single time step */
382     ierr = PetscViewerDestroy(&socket->window[wid]);CHKERRQ(ierr);
383   } else if (!*view) { /* something went wrong (SIGPIPE) so we just zero the private pointer */
384     socket->window[wid] = NULL;
385   }
386   *view = NULL;
387   PetscFunctionReturn(0);
388 }
389 
390 /* default window appearance in the PETSC_VIEWER_GLVIS_SOCKET case */
391 PetscErrorCode PetscViewerGLVisInitWindow_Private(PetscViewer viewer, PetscBool mesh, PetscInt dim, const char *name)
392 {
393   PetscErrorCode       ierr;
394   PetscViewerGLVisInfo info;
395   PetscContainer       container;
396 
397   PetscFunctionBegin;
398   ierr = PetscObjectQuery((PetscObject)viewer,"_glvis_info_container",(PetscObject*)&container);CHKERRQ(ierr);
399   if (!container) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,"Viewer was not obtained from PetscGLVisViewerGetNewWindow_Private");
400   ierr = PetscContainerGetPointer(container,(void**)&info);CHKERRQ(ierr);
401   if (info->init) {
402     if (info->pause < 0) {
403       ierr = PetscViewerASCIIPrintf(viewer,"pause\n");CHKERRQ(ierr); /* pause */
404     }
405     PetscFunctionReturn(0);
406   }
407   ierr = PetscViewerASCIIPrintf(viewer,"window_size 800 800\n");CHKERRQ(ierr);
408   if (name) {
409     ierr = PetscViewerASCIIPrintf(viewer,"window_title '%s'\n",name);CHKERRQ(ierr);
410   }
411   if (mesh) {
412     switch (dim) {
413     case 1:
414       break;
415     case 2:
416       ierr = PetscViewerASCIIPrintf(viewer,"keys cmeeppppp\n");CHKERRQ(ierr); /* show colorbar, mesh and ranks */
417       break;
418     case 3: /* TODO: decide default view in 3D */
419       break;
420     }
421   } else {
422     ierr = PetscViewerASCIIPrintf(viewer,"keys cm\n");CHKERRQ(ierr); /* show colorbar and mesh */
423     switch (dim) {
424     case 1:
425       ierr = PetscViewerASCIIPrintf(viewer,"keys RRj\n");CHKERRQ(ierr); /* set to 1D (side view) and turn off perspective */
426       break;
427     case 2:
428       ierr = PetscViewerASCIIPrintf(viewer,"keys Rjl\n");CHKERRQ(ierr); /* set to 2D (top view), turn off perspective and light */
429       break;
430     case 3:
431       break;
432     }
433     ierr = PetscViewerASCIIPrintf(viewer,"autoscale value\n");CHKERRQ(ierr); /* update value-range; keep mesh-extents fixed */
434     if (info->pause == 0) {
435       ierr = PetscViewerASCIIPrintf(viewer,"pause\n");CHKERRQ(ierr); /* pause */
436     }
437   }
438   info->init = PETSC_TRUE;
439   PetscFunctionReturn(0);
440 }
441 
442 static PetscErrorCode PetscViewerDestroy_GLVis(PetscViewer viewer)
443 {
444   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
445   PetscInt         i;
446   PetscErrorCode   ierr;
447 
448   PetscFunctionBegin;
449   for (i=0;i<socket->nwindow;i++) {
450     ierr = PetscViewerDestroy(&socket->window[i]);CHKERRQ(ierr);
451     ierr = PetscFree(socket->windowtitle[i]);CHKERRQ(ierr);
452     ierr = PetscFree(socket->fec_type[i]);CHKERRQ(ierr);
453     ierr = PetscObjectDestroy(&socket->Ufield[i]);CHKERRQ(ierr);
454   }
455   ierr = PetscFree(socket->name);CHKERRQ(ierr);
456   ierr = PetscFree5(socket->window,socket->windowtitle,socket->fec_type,socket->locandbs,socket->Ufield);CHKERRQ(ierr);
457   ierr = PetscViewerDestroy(&socket->meshwindow);CHKERRQ(ierr);
458   ierr = PetscObjectDestroy(&socket->dm);CHKERRQ(ierr);
459   if (socket->destroyctx && socket->userctx) { ierr = (*socket->destroyctx)(socket->userctx);CHKERRQ(ierr); }
460 
461   ierr = PetscObjectComposeFunction((PetscObject)viewer,"PetscViewerGLVisSetSnapId_C",NULL);CHKERRQ(ierr);
462   ierr = PetscObjectComposeFunction((PetscObject)viewer,"PetscViewerGLVisSetFields_C",NULL);CHKERRQ(ierr);
463   ierr = PetscObjectComposeFunction((PetscObject)viewer,"PetscViewerFileSetName_C",NULL);CHKERRQ(ierr);
464   ierr = PetscFree(socket);CHKERRQ(ierr);
465   viewer->data = NULL;
466   PetscFunctionReturn(0);
467 }
468 
469 static PetscErrorCode PetscViewerSetFromOptions_GLVis(PetscOptionItems *PetscOptionsObject,PetscViewer v)
470 {
471   PetscErrorCode   ierr;
472   PetscViewerGLVis socket = (PetscViewerGLVis)v->data;
473 
474   PetscFunctionBegin;
475   ierr = PetscOptionsHead(PetscOptionsObject,"GLVis PetscViewer Options");CHKERRQ(ierr);
476   ierr = PetscOptionsReal("-viewer_glvis_pause","-1 to pause after each visualization, otherwise sleeps for given seconds",NULL,socket->pause,&socket->pause,NULL);CHKERRQ(ierr);
477   ierr = PetscOptionsTail();CHKERRQ(ierr);
478   PetscFunctionReturn(0);
479 }
480 
481 static PetscErrorCode PetscViewerSetFileName_GLVis(PetscViewer viewer, const char name[])
482 {
483   char             *sport;
484   PetscViewerGLVis socket = (PetscViewerGLVis)viewer->data;
485   PetscErrorCode   ierr;
486 
487   PetscFunctionBegin;
488   socket->type = PETSC_VIEWER_GLVIS_DUMP;
489   /* we accept localhost^port */
490   ierr = PetscFree(socket->name);CHKERRQ(ierr);
491   ierr = PetscStrallocpy(name,&socket->name);CHKERRQ(ierr);
492   ierr = PetscStrchr(socket->name,'^',&sport);CHKERRQ(ierr);
493   if (sport) {
494     PetscInt port = 19916;
495     size_t   len;
496 
497     *sport++ = 0;
498     ierr = PetscStrlen(sport,&len);CHKERRQ(ierr);
499     if (len) ierr = PetscOptionsStringToInt(sport,&port);
500     if (!ierr) {
501       socket->port = (port != PETSC_DECIDE && port != PETSC_DEFAULT) ? port : 19916;
502     } else {
503       socket->port = 19916;
504     }
505     socket->type = PETSC_VIEWER_GLVIS_SOCKET;
506   }
507   PetscFunctionReturn(0);
508 }
509 
510 /*
511      PetscViewerGLVisOpen - Opens a GLVis type viewer
512 
513   Collective on comm
514 
515   Input Parameters:
516 +  comm      - the MPI communicator
517 .  type      - the viewer type: PETSC_VIEWER_GLVIS_SOCKET for real-time visualization or PETSC_VIEWER_GLVIS_DUMP for dumping to disk
518 .  name      - either the hostname where the GLVis server is running or the base filename for dumping the data for subsequent visualizations
519 -  port      - socket port where the GLVis server is listening. Not referenced when type is PETSC_VIEWER_GLVIS_DUMP
520 
521   Output Parameters:
522 -  viewer    - the PetscViewer object
523 
524   Notes: misses Fortran binding
525 
526   Level: beginner
527 
528 .seealso: PetscViewerCreate(), PetscViewerSetType(), PetscViewerGLVisType
529 */
530 PETSC_EXTERN PetscErrorCode PetscViewerGLVisOpen(MPI_Comm comm, PetscViewerGLVisType type, const char* name, PetscInt port, PetscViewer* viewer)
531 {
532   PetscViewerGLVis socket;
533   PetscErrorCode   ierr;
534 
535   PetscFunctionBegin;
536   ierr = PetscViewerCreate(comm,viewer);CHKERRQ(ierr);
537   ierr = PetscViewerSetType(*viewer,PETSCVIEWERGLVIS);CHKERRQ(ierr);
538 
539   socket       = (PetscViewerGLVis)((*viewer)->data);
540   ierr         = PetscFree(socket->name);
541   ierr         = PetscStrallocpy(name,&socket->name);CHKERRQ(ierr);
542   socket->type = type;
543   socket->port = port;
544 
545   ierr = PetscViewerSetFromOptions(*viewer);CHKERRQ(ierr);
546   PetscFunctionReturn(0);
547 }
548 
549 /*
550   PETSC_VIEWER_GLVIS_ - Creates an GLVIS PetscViewer shared by all processors in a communicator.
551 
552   Collective on MPI_Comm
553 
554   Input Parameter:
555 . comm - the MPI communicator to share the GLVIS PetscViewer
556 
557   Level: intermediate
558 
559   Notes: misses Fortran bindings
560 
561   Environmental variables:
562 + PETSC_VIEWER_GLVIS_FILENAME : output filename (if specified dump to disk, and takes precedence on PETSC_VIEWER_GLVIS_HOSTNAME)
563 . PETSC_VIEWER_GLVIS_HOSTNAME : machine where the GLVis server is listening (defaults to localhost)
564 - PETSC_VIEWER_GLVIS_PORT     : port opened by the GLVis server (defaults to 19916)
565 
566   Notes:
567   Unlike almost all other PETSc routines, PETSC_VIEWER_GLVIS_ does not return
568   an error code.  The GLVIS PetscViewer is usually used in the form
569 $       XXXView(XXX object, PETSC_VIEWER_GLVIS_(comm));
570 
571 .seealso: PetscViewerGLVISOpen(), PetscViewerGLVisType, PetscViewerCreate(), PetscViewerDestroy()
572 */
573 PETSC_EXTERN PetscViewer PETSC_VIEWER_GLVIS_(MPI_Comm comm)
574 {
575   PetscErrorCode       ierr;
576   PetscBool            flg;
577   PetscViewer          viewer;
578   PetscViewerGLVisType type;
579   char                 fname[PETSC_MAX_PATH_LEN],sport[16];
580   PetscInt             port = 19916; /* default for GLVis */
581 
582   PetscFunctionBegin;
583   ierr = PetscOptionsGetenv(comm,"PETSC_VIEWER_GLVIS_FILENAME",fname,PETSC_MAX_PATH_LEN,&flg);
584   if (!flg) {
585     type = PETSC_VIEWER_GLVIS_SOCKET;
586     ierr = PetscOptionsGetenv(comm,"PETSC_VIEWER_GLVIS_HOSTNAME",fname,PETSC_MAX_PATH_LEN,&flg);
587     if (ierr) {PetscError(PETSC_COMM_SELF,__LINE__,"PETSC_VIEWER_GLVIS_",__FILE__,PETSC_ERR_PLIB,PETSC_ERROR_INITIAL," ");PetscFunctionReturn(0);}
588     if (!flg) {
589       ierr = PetscStrcpy(fname,"localhost");
590       if (ierr) {PetscError(PETSC_COMM_SELF,__LINE__,"PETSC_VIEWER_GLVIS_",__FILE__,PETSC_ERR_PLIB,PETSC_ERROR_INITIAL," ");PetscFunctionReturn(0);}
591     }
592     ierr = PetscOptionsGetenv(comm,"PETSC_VIEWER_GLVIS_PORT",sport,16,&flg);
593     if (flg) {
594       ierr = PetscOptionsStringToInt(sport,&port);
595       if (ierr) {PetscError(PETSC_COMM_SELF,__LINE__,"PETSC_VIEWER_GLVIS_",__FILE__,PETSC_ERR_PLIB,PETSC_ERROR_INITIAL," ");PetscFunctionReturn(0);}
596     }
597   } else {
598     type = PETSC_VIEWER_GLVIS_DUMP;
599   }
600   ierr = PetscViewerGLVisOpen(comm,type,fname,port,&viewer);
601   if (ierr) {PetscError(PETSC_COMM_SELF,__LINE__,"PETSC_VIEWER_GLVIS_",__FILE__,PETSC_ERR_PLIB,PETSC_ERROR_INITIAL," ");PetscFunctionReturn(0);}
602   ierr = PetscObjectRegisterDestroy((PetscObject)viewer);
603   if (ierr) {PetscError(PETSC_COMM_SELF,__LINE__,"PETSC_VIEWER_GLVIS_",__FILE__,PETSC_ERR_PLIB,PETSC_ERROR_INITIAL," ");PetscFunctionReturn(0);}
604   if (ierr) {PetscError(PETSC_COMM_SELF,__LINE__,"PETSC_VIEWER_GLVIS_",__FILE__,PETSC_ERR_PLIB,PETSC_ERROR_INITIAL," ");PetscFunctionReturn(0);}
605   PetscFunctionReturn(viewer);
606 }
607 
608 PETSC_EXTERN PetscErrorCode PetscViewerCreate_GLVis(PetscViewer viewer)
609 {
610   PetscViewerGLVis socket;
611   PetscErrorCode   ierr;
612 
613   PetscFunctionBegin;
614   ierr = PetscNewLog(viewer,&socket);CHKERRQ(ierr);
615 
616   /* defaults to socket viewer */
617   ierr = PetscStrallocpy("localhost",&socket->name);CHKERRQ(ierr);
618   socket->port  = 19916; /* GLVis default listening port */
619   socket->type  = PETSC_VIEWER_GLVIS_SOCKET;
620   socket->pause = 0; /* just pause the first time */
621 
622   viewer->data                = (void*)socket;
623   viewer->ops->destroy        = PetscViewerDestroy_GLVis;
624   viewer->ops->setfromoptions = PetscViewerSetFromOptions_GLVis;
625 
626   ierr = PetscObjectComposeFunction((PetscObject)viewer,"PetscViewerGLVisSetSnapId_C",PetscViewerGLVisSetSnapId_GLVis);CHKERRQ(ierr);
627   ierr = PetscObjectComposeFunction((PetscObject)viewer,"PetscViewerGLVisSetFields_C",PetscViewerGLVisSetFields_GLVis);CHKERRQ(ierr);
628   ierr = PetscObjectComposeFunction((PetscObject)viewer,"PetscViewerFileSetName_C",PetscViewerSetFileName_GLVis);CHKERRQ(ierr);
629   PetscFunctionReturn(0);
630 }
631 
632 /* this is a private implementation of a SOCKET with ASCII data format
633    GLVis does not currently handle binary socket streams */
634 #if defined(PETSC_HAVE_UNISTD_H)
635 #include <unistd.h>
636 #endif
637 
638 #if defined(PETSC_USE_SOCKET_VIEWER)
639 static PetscErrorCode (*PetscViewerDestroy_ASCII)(PetscViewer);
640 
641 static PetscErrorCode PetscViewerDestroy_ASCII_Socket(PetscViewer viewer)
642 {
643   FILE *stream;
644   PetscErrorCode ierr = 0;
645   PetscFunctionBegin;
646   ierr = PetscViewerASCIIGetPointer(viewer,&stream);CHKERRQ(ierr);
647   if (stream) {
648     ierr = fclose(stream);
649     if (ierr) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on stream");
650   }
651   ierr = PetscViewerDestroy_ASCII(viewer);CHKERRQ(ierr);
652   PetscFunctionReturn(0);
653 }
654 #endif
655 
656 static PetscErrorCode PetscViewerASCIISocketOpen(MPI_Comm comm,const char* hostname,PetscInt port,PetscViewer* viewer)
657 {
658 #if !defined(PETSC_USE_SOCKET_VIEWER)
659   PetscFunctionBegin;
660   SETERRQ(comm,PETSC_ERR_SUP,"Not implemented for Windows");
661 #else
662   FILE           *stream = NULL;
663   int            fd;
664   PetscErrorCode ierr;
665 
666   PetscFunctionBegin;
667   PetscValidPointer(hostname,2);
668   PetscValidPointer(viewer,4);
669   ierr = PetscOpenSocket(hostname,port,&fd);
670   if (ierr) {
671     PetscInt sierr = ierr;
672     char     err[1024];
673 
674     ierr    = PetscSNPrintf(err,1024,"Cannot connect to socket on %s:%D. Socket visualization is disabled\n",hostname,port);CHKERRQ(ierr);
675     ierr    = PetscInfo(NULL,err);CHKERRQ(ierr);
676     *viewer = NULL;
677     PetscFunctionReturn(sierr);
678   } else {
679     char msg[1024];
680 
681     ierr = PetscSNPrintf(msg,1024,"Successfully connect to socket on %s:%D. Socket visualization is enabled\n",hostname,port);CHKERRQ(ierr);
682     ierr = PetscInfo(NULL,msg);CHKERRQ(ierr);
683   }
684   stream = fdopen(fd,"w"); /* Not possible on Windows */
685   if (!stream) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_SYS,"Cannot open stream from socket %s:%d",hostname,port);
686   ierr = PetscViewerASCIIOpenWithFILE(PETSC_COMM_SELF,stream,viewer);CHKERRQ(ierr);
687   PetscViewerDestroy_ASCII = (*viewer)->ops->destroy;
688   (*viewer)->ops->destroy = PetscViewerDestroy_ASCII_Socket;
689 #endif
690   PetscFunctionReturn(0);
691 }
692