chiark / gitweb /
memoise edge_end2 now performance is good
[moebius2.git] / view.c
1 /*
2  * Displays a conformation
3  */
4
5 #include <X11/Xlib.h>
6 #include <X11/Xutil.h>
7
8 #include <sys/poll.h>
9
10 #include "mgraph.h"
11
12 #define MAXTRIS (N*2)
13
14 typedef struct { double vertex[3][D3]; } Triangle;
15
16 static Triangle trisbuffer[MAXTRIS], *displaylist[MAXTRIS];
17 static int ntris;
18 static Vertices conformation;
19
20 static double transform[D3][D3]= {{1,0,0}, {0,1,0}, {0,0,1}};
21 static GSL_MATRIX(transform);
22
23 static FILE *input_f;
24 static struct stat input_stab;
25 static const char *input_filename;
26 static int pause_updates;
27
28 static void read_input(void) {
29   int r;
30   
31   if (input_f) fclose(input_f);
32   input_f= fopen(input_filename, "rb");  if (!input_f) diee("input file");
33
34   if (fstat(fileno(input_f), &input_stab)) diee("fstat input file");
35
36   errno= 0;
37   r= fread(&conformation,sizeof(conformation),1,input_f);
38   if (r!=1) diee("fread");
39 }
40
41 static void transform_coordinates(void) {
42   double result[D3];
43   GSL_VECTOR(result);
44   gsl_vector input_gsl= { D3,1 };
45
46   int v, k;
47   
48   FOR_VERTEX(v,INNER) {
49     input_gsl.data= &conformation[v][0];
50     GA( gsl_blas_dgemv(CblasNoTrans, 1.0,&transform_gsl, &input_gsl,
51                        0.0, &result_gsl) );
52     K conformation[v][k]= result[k];
53   }
54 }
55
56 static int vertex_in_triangles[N], vertex_in_triangles_checked;
57
58 static void addtriangle(int va, int vb, int vc) {
59   Triangle *t= &trisbuffer[ntris];
60   int k;
61   
62   assert(ntris < MAXTRIS);
63   K {
64     t->vertex[0][k]= conformation[va][k];
65     t->vertex[1][k]= conformation[vb][k];
66     t->vertex[2][k]= conformation[vc][k];
67   }
68   if (!vertex_in_triangles_checked) {
69     vertex_in_triangles[va]++;
70     vertex_in_triangles[vb]++;
71     vertex_in_triangles[vc]++;
72   }
73   displaylist[ntris++]= t;
74 }
75
76 static void generate_display_list(void) {
77   int vb, ve[V6], e;
78
79   ntris= 0;
80   FOR_VERTEX(vb,INNER) {
81     /* We use the two triangles in the parallelogram vb, vb+e5, vb+e0, vb+e1.
82      * We go round each triangle clockwise (although our surface is non-
83      * orientable so it shouldn't matter).  Picking the parallelogram
84      * to our right avoids getting it wrong at the join.
85      */
86 //if ((vb & YMASK) > Y1) continue;
87 //if ((vb & XMASK) > 2) continue; 
88     for (e=0; e<V6; e++) ve[e]= EDGE_END2(vb,e);
89     assert(ve[0]>=0);
90     if (ve[5]>=0) addtriangle(vb,ve[0],ve[5]);
91 //continue;
92     if (ve[1]>=0) addtriangle(vb,ve[1],ve[0]);
93   }
94
95   if (!vertex_in_triangles_checked) {
96     int v, expd;
97     FOR_VERTEX(v,INNER) {
98       expd= RIM_VERTEX_P(v) ? 3 : 6;
99       if (vertex_in_triangles[v] != expd) {
100         fprintf(stderr,"vertex %02x used for %d triangles, expected %d\n",
101                 v, vertex_in_triangles[v], expd);
102 //      abort();
103       }
104     }
105     vertex_in_triangles_checked= 1;
106   }
107 }    
108
109 static int dl_compare(const void *tav, const void *tbv) {
110   int i;
111   const Triangle *const *tap= tav, *ta= *tap;
112   const Triangle *const *tbp= tbv, *tb= *tbp;
113   double za=0, zb=0;
114   for (i=0; i<3; i++) {
115     za += ta->vertex[i][2];
116     zb += tb->vertex[i][2];
117   }
118   return za > zb ? -1 :
119          za < zb ? +1 : 0;
120 }
121
122 static void sort_display_list(void) {
123   qsort(displaylist, ntris, sizeof(*displaylist), dl_compare);
124 }
125
126 /*---------- X stuff ----------*/
127
128 #define WSZ 400
129
130 typedef struct { GC fillgc, linegc; } DrawingMode;
131
132 static Display *display;
133 static Pixmap pixmap, doublebuffers[2];
134 static Window window;
135
136 static DrawingMode dmred, dmblue, dmwhite;
137 static const DrawingMode *dmcurrent;
138 static int wwidth=WSZ, wheight=WSZ, wmindim=WSZ, wmaxdim=WSZ;
139 static int ncut, currentbuffer, x11depth, x11screen, wireframe;
140 XVisualInfo visinfo;
141
142 static double sizeadj_scale= 0.3, eyes_apart, scale_wmindim;
143 static double eye_z= -10, eye_x=0;
144 static double cut_z= -9;
145 static const double eyes_apart_preferred=0.05, eyes_apart_min= -0.02;
146
147
148 static void drawtriangle(const Triangle *t) {
149   XPoint points[4];
150   int i;
151
152   for (i=0; i<3; i++) {
153     const double *v= t->vertex[i];
154     double x= v[0];
155     double y= v[1];
156     double z= v[2];
157
158     if (z < cut_z) { ncut++; return; }
159     
160     double zezezp= eye_z / (eye_z - z);
161     points[i].x= scale_wmindim * (zezezp * (x - eye_x) + eye_x) + wwidth/2;
162     points[i].y= scale_wmindim * (zezezp *  y                 ) + wheight/2;
163   }
164   points[3]= points[0];
165
166   if (!wireframe)
167     XA( XFillPolygon(display,pixmap, dmcurrent->fillgc,
168                      points,3,Convex,CoordModeOrigin) );
169   XA( XDrawLines(display,pixmap, dmcurrent->linegc,
170                  points, 4,CoordModeOrigin) );
171 }
172
173 static const unsigned long core_event_mask=
174   ButtonPressMask|ButtonReleaseMask|StructureNotifyMask|ButtonMotionMask|
175   KeyPressMask|SubstructureNotifyMask;
176
177 static void mkpixmaps(void) {
178   for (currentbuffer=0; currentbuffer<2; currentbuffer++) {
179     XA( pixmap= XCreatePixmap(display,window,wwidth,wheight,x11depth) );
180     doublebuffers[currentbuffer]= pixmap;
181   }
182   currentbuffer= 0;
183 }
184
185 static void mkgcs(DrawingMode *dm, unsigned long planes) {
186   XGCValues gcv;
187
188   gcv.function= GXcopy;
189   gcv.foreground= WhitePixel(display,x11screen);
190   gcv.plane_mask= planes;
191   dm->linegc= XCreateGC(display,pixmap,
192                         GCFunction|GCForeground|GCPlaneMask,
193                         &gcv);
194
195   gcv.function= GXclear;
196   dm->fillgc= XCreateGC(display,pixmap,
197                         GCFunction|GCPlaneMask,
198                         &gcv);
199 }
200
201 static void display_prepare(void) {
202   XSetWindowAttributes wa;
203   XSizeHints hints;
204   
205   XA( display= XOpenDisplay(0) );
206   x11screen= DefaultScreen(display);
207   x11depth= DefaultDepth(display,x11screen);
208   XA( XMatchVisualInfo(display,x11screen,x11depth, TrueColor,&visinfo) );
209   
210   wa.event_mask= core_event_mask;
211   XA( window= XCreateWindow(display, DefaultRootWindow(display),
212                             0,0, wwidth,wheight, 0,x11depth,
213                             InputOutput, visinfo.visual,
214                             CWEventMask, &wa) );
215
216   hints.flags= USPosition;
217   hints.x= 10;
218   hints.y= 10;
219   XSetWMNormalHints(display,window,&hints);
220
221   mkpixmaps();
222
223   mkgcs(&dmwhite, AllPlanes);
224   mkgcs(&dmblue, visinfo.blue_mask);
225   mkgcs(&dmred, visinfo.red_mask);
226 }
227
228 static void drawtriangles(const DrawingMode *dm) {
229   Triangle *const *t;
230   int i;
231
232   dmcurrent= dm;
233   for (i=0, t=displaylist, ncut=0; i<ntris; i++, t++)
234     drawtriangle(*t);
235 }
236
237 static void display_conformation(void) {
238   pixmap= doublebuffers[currentbuffer];
239
240   XA( XFillRectangle(display,pixmap,dmwhite.fillgc,0,0,wwidth,wheight) );
241
242   if (eyes_apart > 0) {
243     const double stationary= 0.07;
244
245     eye_x= eyes_apart < eyes_apart_preferred
246               ? eyes_apart :
247            eyes_apart < (eyes_apart_preferred + stationary)
248               ? eyes_apart_preferred
249               : eyes_apart - stationary;
250     eye_x /= sizeadj_scale;
251     drawtriangles(&dmblue);
252     eye_x= -eye_x;
253     drawtriangles(&dmred);
254   } else {
255     drawtriangles(&dmwhite);
256     printf("shown, %d/%d triangles cut\n", ncut, ntris);
257   }
258   
259   XA( XSetWindowBackgroundPixmap(display,window,pixmap) );
260   XA( XClearWindow(display,window) );
261   currentbuffer= !currentbuffer;
262 }
263
264 static void show(void) {
265   scale_wmindim= sizeadj_scale * wmindim;
266   read_input();
267   transform_coordinates();
268   generate_display_list();
269   sort_display_list();
270   display_conformation();
271 }
272
273 typedef struct {
274   const char *name;
275   void (*start)(const XButtonEvent *e);
276   void (*delta)(double dx, double dy);
277   void (*conclude)(void);
278   void (*abandon)(void);
279 } Drag;
280
281 #define DRAG(x)                                 \
282   static const Drag drag_##x= {                 \
283     #x, drag_##x##_start, drag_##x##_delta,     \
284     drag_##x##_conclude, drag_##x##_abandon     \
285   }
286
287 #define DRAG_SAVING(x, thing, hook)                     \
288   static typeof(thing) original_##thing;                \
289   static void drag_##x##_start(const XButtonEvent *e) { \
290     memcpy(&original_##thing, &thing, sizeof(thing));   \
291     hook;                                               \
292   }                                                     \
293   static void drag_##x##_conclude(void) { }             \
294   static void drag_##x##_abandon(void) {                \
295     memcpy(&thing, &original_##thing, sizeof(thing));   \
296     show();                                             \
297   }                                                     \
298   DRAG(x)
299
300 static void drag_none_start(const XButtonEvent *e) { }
301 static void drag_none_delta(double dx, double dy) { }
302 static void drag_none_conclude(void) { }
303 static void drag_none_abandon(void) { }
304 DRAG(none);
305
306 static void pvectorcore(const char *n, double v[D3]) {
307   int k;
308   printf("%10s [ ",n);
309   K printf("%# 10.10f ",v[k]);
310   printf("]\n");
311 }
312 static void pvector(const char *n, double v[D3]) {
313   pvectorcore(n,v);
314   putchar('\n');
315 }
316 static void pmatrix(const char *n, double m[D3][D3]) {
317   int j;
318   for (j=0; j<D3; j++) { pvectorcore(n,m[j]); n=""; }
319   putchar('\n');
320 }
321 #define PMATRIX(x) pmatrix(#x,x);
322
323 static double drag_transform_conv_x_z= 0;
324 static double drag_transform_conv_y_z= 0;
325
326 static void drag_transform_prep(const XButtonEvent *e) {
327   static const double factor= 2.5;
328   drag_transform_conv_x_z= MAX( MIN(e->y * factor / wheight - (factor/2),
329                                     1.0), -1.0);
330   drag_transform_conv_y_z= MAX( MIN(e->x * factor / wwidth  - (factor/2),
331                                     1.0), -1.0);
332   printf("drag_transform_conv_{x,y}_z = %g,%g\n",
333          drag_transform_conv_x_z, drag_transform_conv_y_z);
334 }
335
336 static void make_z_rotation(double rotz[D3][D3], double cz, double sz) {
337   rotz[0][0]=  cz;    rotz[0][1]=  sz;     rotz[0][2]=  0;
338   rotz[1][0]= -sz;    rotz[1][1]=  cz;     rotz[1][2]=  0;
339   rotz[2][0]=   0;    rotz[2][1]=   0;     rotz[2][2]=  1;
340 }
341
342 static void drag_rotate_delta(double dx, double dy) {
343   /* We multiple our transformation matrix by a matrix:
344    *
345    * If we just had y movement, we would rotate about x axis:
346    *  rotation X = [  1    0   0 ]
347    *               [  0   cy  sy ]
348    *               [  0  -sy  cy ]
349    *  where cy and sy are sin and cos of y rotation
350    *
351    * But we should pre-rotate this by a rotation about the z axis
352    * to get it to the right angle (to include x rotation).  So
353    * we make cy and sy be cos() and sin(hypot(x,y)) and use
354    * with cr,sr as cos() and sin(atan2(y,y)):
355    *
356    * Ie we would do  T' = Z R^T X R T   where
357    *             or  T' = Z    C    T   where  C = R^T X R  and
358    *
359    *  adjustment R = [  cr  sr  0 ]
360    *                 [ -sr  cr  0 ]
361    *                 [  0    0  1 ]    or make_z_rotation(cr,sr)
362    *
363    *  rotation Z   = [  cz  sz  0 ]
364    *                 [ -sz  cz  0 ]
365    *                 [  0    0  1 ]    or make_z_rotation(cz,sz)
366    */
367
368   double rotx[D3][D3], adjr[D3][D3], rotz[D3][D3];
369   GSL_MATRIX(rotx);
370   GSL_MATRIX(adjr);
371   GSL_MATRIX(rotz);
372
373   static double temp[D3][D3], change[D3][D3];
374   static GSL_MATRIX(temp);
375   static GSL_MATRIX(change);
376
377   printf("\nTRANSFORM %g, %g\n", dx,dy);
378
379   double dz= -drag_transform_conv_x_z * dx +
380               drag_transform_conv_y_z * dy;
381           
382   dx *= (1 - fabs(drag_transform_conv_x_z));
383   dy *= (1 - fabs(drag_transform_conv_y_z));
384
385   double d= hypot(dx,dy);
386
387   printf(" dx,dy,dz = %g, %g, %g    d = %g\n", dx,dy,dz, d);
388
389   if (hypot(d,dz) < 1e-6) return;
390
391   printf(" no xy rotation\n");
392
393   double ang= d*2.0;
394   
395   double cy= cos(ang);
396   double sy= sin(ang);
397
398   double cr, sr;
399   if (d > 1e-6) {
400     cr= -dy / d;
401     sr=  dx / d;
402   } else {
403     cr= 1;
404     sr= 0;
405   }
406   printf("\n d=%g cy,sy=%g,%g cr,sr=%g,%g\n\n", d,cy,sy,cr,sr);
407   
408   rotx[0][0]=   1;    rotx[0][1]=   0;     rotx[0][2]=  0;
409   rotx[1][0]=   0;    rotx[1][1]=  cy;     rotx[1][2]= sy;
410   rotx[2][0]=   0;    rotx[2][1]= -sy;     rotx[2][2]= cy;
411   PMATRIX(rotx);
412
413   make_z_rotation(adjr,cr,sr);
414   PMATRIX(adjr);
415
416   GA( gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0,
417                      &rotx_gsl,&adjr_gsl,
418                      0.0, &temp_gsl) );
419   pmatrix("X R", temp);
420   
421   GA( gsl_blas_dgemm(CblasTrans,CblasNoTrans, 1.0,
422                      &adjr_gsl,&temp_gsl,
423                      0.0, &change_gsl) );
424   PMATRIX(change);
425
426   double angz= dz*2.0;
427   make_z_rotation(rotz,cos(angz),sin(angz));
428   PMATRIX(rotz);
429
430   GA( gsl_blas_dgemm(CblasTrans,CblasNoTrans, 1.0,
431                      &rotz_gsl,&change_gsl,
432                      0.0, &temp_gsl) );
433   pmatrix("Z C", temp);
434
435   static double skew[D3][D3];
436   static GSL_MATRIX(skew);
437   
438   GA( gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0,
439                      &temp_gsl, &transform_gsl,
440                      0.0, &skew_gsl) );
441   PMATRIX(skew);
442
443   memcpy(&transform,&skew,sizeof(transform));
444   show();
445   return;
446
447   /* Now we want to normalise skew, the result becomes new transform */
448   double svd_v[D3][D3];
449   GSL_MATRIX(svd_v);
450
451   double sigma[D3], tau[D3];
452   GSL_VECTOR(sigma);
453   GSL_VECTOR(tau);
454   
455   /* We use notation from Wikipedia Polar_decomposition
456    *     Wikipedia's  W      is GSL's U
457    *     Wikipedia's  Sigma  is GSL's S
458    *     Wikipedia's  V      is GSL's V
459    *     Wikipedia's  U      is our desired result
460    * Wikipedia which says if the SVD is    A = W Sigma V*
461    * then the polar decomposition is       A = U P
462    *   where                               P = V Sigma V*
463    *   and                                 U = W V*
464    */
465   
466   GA( gsl_linalg_SV_decomp(&skew_gsl, &svd_v_gsl, &sigma_gsl, &tau_gsl) );
467   pmatrix("W",    skew);
468   pvector("Sigma",sigma);
469   pmatrix("V",    svd_v);
470
471   /* We only need U, not P. */
472   GA( gsl_blas_dgemm(CblasNoTrans,CblasTrans, 1.0,
473                      &skew_gsl,&svd_v_gsl,
474                      0.0,&transform_gsl) );
475
476   pmatrix("U", transform);
477
478   printf("drag_rotate_delta...\n");
479   show();
480 }
481 DRAG_SAVING(rotate, transform, drag_transform_prep(e));
482
483 static void drag_sizeadj_delta(double dx, double dy) {
484   sizeadj_scale *= pow(3.0, -dy);
485   show();
486 }
487 DRAG_SAVING(sizeadj, sizeadj_scale, );
488
489 static void drag_3d_delta(double dx, double dy) {
490   eyes_apart += dx * 0.1;
491   if (eyes_apart < eyes_apart_min) eyes_apart= eyes_apart_min;
492   printf("sizeadj eyes_apart %g\n", eyes_apart);
493   show();
494 }
495 DRAG_SAVING(3d, eyes_apart, );
496
497 static const Drag *drag= &drag_none;
498
499 static int drag_last_x, drag_last_y;
500
501 static void drag_position(int x, int y) {
502   drag->delta((x - drag_last_x) * 1.0 / wmaxdim,
503               (y - drag_last_y) * 1.0 / wmaxdim);
504   drag_last_x= x;
505   drag_last_y= y;
506 }
507
508 static void event_button(XButtonEvent *e) {
509   if (e->window != window || !e->same_screen) return;
510   if (e->type == ButtonPress) {
511     if (e->state || drag != &drag_none) {
512       printf("drag=%s press state=0x%lx abandon\n",
513              drag->name, (unsigned long)e->state);
514       drag->abandon();
515       drag= &drag_none;
516       return;
517     }
518     switch (e->button) {
519     case Button1: drag= &drag_rotate;  break;
520     case Button2: drag= &drag_sizeadj; break;
521     case Button3: drag= &drag_3d;      break;
522     default: printf("unknown drag start %d\n", e->button);
523     }
524     printf("drag=%s press button=%lu start %d,%d\n",
525            drag->name, (unsigned long)e->button, e->x, e->y);
526     drag_last_x= e->x;
527     drag_last_y= e->y;
528     drag->start(e);
529   }
530   if (e->type == ButtonRelease) {
531     printf("drag=%s release %d,%d\n", drag->name, e->x, e->y);
532     drag_position(e->x, e->y);
533     drag->conclude();
534     drag= &drag_none;
535   }
536 }
537
538 static void event_motion(int x, int y) {
539   printf("drag=%s motion %d,%d\n", drag->name, x, y);
540   drag_position(x,y);
541 }
542
543 static void transform_preset_record(const char *fn, const char *fn_new) {
544   FILE *f;
545   f= fopen(fn_new,"wb");
546   if (!f) diee("open new transform");
547   if (fwrite(transform,sizeof(transform),1,f) != 1) diee("write transform");
548   if (fclose(f)) diee("fclose new transform");
549   if (rename(fn_new,fn)) diee("install transform");
550 }
551
552 static void transform_preset_playback(const char *fn) {
553   FILE *f;
554   f= fopen(fn,"rb");
555   if (!f && errno==ENOENT) {
556     fprintf(stderr,"no preset %s\n",fn);
557     XBell(display,100);
558     return;
559   }
560   errno= 0;
561   if (fread(transform,sizeof(transform),1,f) != 1) {
562     perror("read preset!");
563     XBell(display,100);
564     return;
565   }
566   fclose(f);
567   show();
568 }
569
570 static void event_key(XKeyEvent *e) {
571   KeySym ks;
572   XKeyEvent e_nomod;
573   char buf[10], buf_nomod[10];
574   int r, r_nomod;
575
576   r= XLookupString(e,buf,sizeof(buf)-1,&ks,0);
577   if (!r) {
578     printf("XLookupString keycode=%u state=0x%x gave %d\n",
579            e->keycode, e->state, r);
580     return;
581   }
582
583   if (!strcmp(buf,"q"))
584     exit(0);
585   else if (!strcmp(buf,"p"))
586     pause_updates= !pause_updates;
587   else if (!strcmp(buf,"w")) {
588     wireframe= !wireframe;
589     show();
590     return;
591   } else if (!strcmp(buf,"d")) {
592     eyes_apart= eyes_apart>0 ? eyes_apart_min : eyes_apart_preferred;
593     show();
594     return;
595   }
596
597   e_nomod= *e;
598   e_nomod.state= 0;
599   buf_nomod[0]= 0;
600   r_nomod= XLookupString(&e_nomod,buf_nomod,sizeof(buf_nomod)-1,&ks,0);
601   if (r_nomod && !buf_nomod[1] && buf_nomod[0]>='0' && buf_nomod[0]<='9') {
602     char filename[20], filename_new[25];
603     snprintf(filename,sizeof(filename)-1,".view-preset-%s",buf_nomod);
604     snprintf(filename_new,sizeof(filename_new)-1,"%s.new",filename);
605     printf("transform preset %d %s\n", e->state, filename);
606     if (e->state) transform_preset_record(filename,filename_new);
607     else transform_preset_playback(filename);
608     return;
609   }
610
611   printf("unknown key keycode=%d state=0x%x char=%c 0x%02x "
612          "[rnm=%d bnm[0,1]=0x%02x,%02x]\n",
613          e->keycode, e->state, buf[0]>' ' && buf[0]<127 ? buf[0] : '?',
614          buf[0], r_nomod, buf_nomod[0], buf_nomod[1]);
615   printf("%d %d %d %d\n",
616          r_nomod,
617          !buf_nomod[1],
618          buf_nomod[0]>='0',
619          buf_nomod[0]<='9');
620 }
621
622 static void event_config(XConfigureEvent *e) {
623   if (e->width == wwidth && e->height == wheight)
624     return;
625
626   wwidth= e->width;  wheight= e->height;
627   wmaxdim= wwidth > wheight ? wwidth : wheight;
628   wmindim= wwidth < wheight ? wwidth : wheight;
629   
630   XA( XSetWindowBackground(display,window,BlackPixel(display,x11screen)) );
631   for (currentbuffer=0; currentbuffer<2; currentbuffer++)
632     XA( XFreePixmap(display, doublebuffers[currentbuffer]) );
633
634   mkpixmaps();
635   show();
636 }
637
638 static void check_input(void) {
639   struct stat newstab;
640   int r;
641
642   r= stat(input_filename, &newstab);
643   if (r<0) diee("could not check input");
644
645 #define CI(x) if (newstab.st_##x == input_stab.st_##x) ; else goto changed
646   CI(dev);
647   CI(ino);
648   CI(size);
649   CI(mtime);
650 #undef CI
651   return;
652
653  changed:
654   show();
655 }
656
657 static void topocheck(void) {
658   int v1,e,v2,eprime,v1prime, count;
659   FOR_EDGE(v1,e,v2, INNER) {
660     count= 0;
661     FOR_VEDGE(v2,eprime,v1prime)
662       if (v1prime==v1) count++;
663     if (count!=1) {
664       fprintf(stderr,"%02x -%d-> %02x  reverse edge count = %d!\n",
665               v1,e,v2, count);
666       FOR_VEDGE(v2,eprime,v1prime)
667         fprintf(stderr,"%02x -%d-> %02x -> %d -> %02x\n",
668                 v1,e,v2,eprime,v1prime);
669       exit(-1);
670     }
671   }
672 }
673
674 int main(int argc, const char *const *argv) {
675   static const int wantedevents= POLLIN|POLLPRI|POLLERR|POLLHUP;
676
677   XEvent event;
678   int k, i, r, *xfds, nxfds, polls_alloc=0;
679   struct pollfd *polls=0;
680   int motion_deferred=0, motion_x=-1, motion_y=-1;
681
682   mgraph_prepare();
683   topocheck();
684   if (argc==1) { printf("topology self-consistent, ok\n"); exit(0); }
685   
686   if (argc != 2 || argv[1][0]=='-') {
687     fputs("need filename\n",stderr); exit(8);
688   }
689   input_filename= argv[1];
690
691   read_input();
692   K transform[k][k]= 1.0;
693   display_prepare();
694   show();
695
696   XMapWindow(display,window);
697   for (;;) {
698
699     XA( XInternalConnectionNumbers(display, &xfds, &nxfds) );
700     if (polls_alloc <= nxfds) {
701       polls_alloc= nxfds + polls_alloc + 1;
702       polls= realloc(polls, sizeof(*polls) * polls_alloc);
703       if (!polls) diee("realloc for pollfds");
704     }
705     for (i=0; i<nxfds; i++) {
706       polls[i].fd= xfds[i];
707       polls[i].events= wantedevents;
708       polls[i].revents= 0;
709     }
710     XFree(xfds);
711
712     polls[i].fd= ConnectionNumber(display);
713     polls[i].events= wantedevents;
714
715     r= poll(polls, nxfds+1, motion_deferred ? 0 : pause_updates ? -1 : 200);
716     if (r<0) {
717       if (errno==EINTR) continue;
718       diee("poll");
719     }
720
721     for (i=0; i<nxfds; i++)
722       if (polls[i].revents)
723         XProcessInternalConnection(display, polls[i].fd);
724
725     r= XCheckMaskEvent(display,~0UL,&event);
726     if (!r) {
727       if (motion_deferred) {
728         event_motion(motion_x, motion_y);
729         motion_deferred=0;
730       }
731       if (!pause_updates)
732         check_input();
733       continue;
734     }
735     
736     switch (event.type) {
737
738     case ButtonPress:
739     case ButtonRelease:     event_button(&event.xbutton);     break;
740       
741     case KeyPress:          event_key(&event.xkey);           break;
742
743     case ConfigureNotify:   event_config(&event.xconfigure);  break;
744
745     case MotionNotify:
746       motion_x= event.xmotion.x;
747       motion_y= event.xmotion.y;
748       motion_deferred= 1;
749       continue;
750       
751     default:
752       printf("unknown event type %u 0x%x\n", event.type,event.type);
753     }
754   }
755 }
756