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