chiark / gitweb /
3d nice and everything
[moebius2.git] / project.c
1 /*
2  * Displays a conformation
3  */
4
5 #include <X11/Xlib.h>
6 #include <X11/Xutil.h>
7
8 #include "mgraph.h"
9
10 #define MAXTRIS (N*2)
11
12 typedef struct { double vertex[3][D3]; } Triangle;
13
14 static Triangle trisbuffer[MAXTRIS], *displaylist[MAXTRIS];
15 static int ntris;
16 static Vertices conformation;
17
18 static double transform[D3][D3]= {{1,0,0}, {0,1,0}, {0,0,1}};
19 static GSL_MATRIX(transform);
20
21 const char *input_filename;
22
23 static void read_input(void) {
24   FILE *f;
25   int r;
26   
27   f= fopen(input_filename, "rb");  if (!f) diee("input file");
28   errno= 0;
29   r= fread(&conformation,sizeof(conformation),1,f);  if (r!=1) diee("fread");
30   fclose(f);
31 }
32
33 static void transform_coordinates(void) {
34   double result[D3];
35   GSL_VECTOR(result);
36   gsl_vector input_gsl= { D3,1 };
37
38   int v, k;
39   
40   FOR_VERTEX(v) {
41     input_gsl.data= &conformation[v][0];
42     GA( gsl_blas_dgemv(CblasNoTrans, 1.0,&transform_gsl, &input_gsl,
43                        0.0, &result_gsl) );
44     K conformation[v][k]= result[k];
45   }
46 }
47
48 static void addtriangle(int va, int vb, int vc) {
49   Triangle *t= &trisbuffer[ntris];
50   int k;
51   
52   assert(ntris < MAXTRIS);
53   K {
54     t->vertex[0][k]= conformation[va][k];
55     t->vertex[1][k]= conformation[vb][k];
56     t->vertex[2][k]= conformation[vc][k];
57   }
58   displaylist[ntris++]= t;
59 }
60
61 static void generate_display_list(void) {
62   int vb, ve[3], e;
63
64   ntris= 0;
65   FOR_VERTEX(vb) {
66     /* We use the two triangles in the parallelogram vb, vb+e1, vb+e0, vb+e2.
67      * We go round each triangle clockwise (although our surface is non-
68      * orientable so it shouldn't matter).
69      */
70     for (e=0; e<3; e++) ve[e]= EDGE_END2(vb,e);
71     if (ve[0]>=0) {
72       if (ve[1]>=0) addtriangle(vb,ve[0],ve[1]);
73       if (ve[2]>=0) addtriangle(vb,ve[2],ve[0]);
74     }
75   }
76 }    
77
78 static int dl_compare(const void *tav, const void *tbv) {
79   const Triangle *const *tap= tav, *ta= *tap;
80   const Triangle *const *tbp= tbp, *tb= *tbp;
81   double za= ta->vertex[0][2];
82   double zb= tb->vertex[0][2];
83   return za > zb ? -1 :
84          za < zb ? +1 : 0;
85 }
86
87 static void sort_display_list(void) {
88   qsort(displaylist, ntris, sizeof(*displaylist), dl_compare);
89 }
90
91 /*---------- X stuff ----------*/
92
93 #define WSZ 400
94
95 typedef struct { GC fillgc, linegc; } DrawingMode;
96
97 static Display *display;
98 static Pixmap pixmap, doublebuffers[2];
99 static Window window;
100
101 static DrawingMode dmred, dmblue, dmwhite;
102 static const DrawingMode *dmcurrent;
103 static int wwidth=WSZ, wheight=WSZ, wmindim=WSZ, wmaxdim=WSZ;
104 static int ncut, currentbuffer, x11depth, x11screen;
105 XVisualInfo visinfo;
106
107 static double sizeadj_scale= 0.3, eyes_apart, scale_wmindim;
108 static double eye_z= -10, eye_x=0;
109 static double cut_z= -9;
110
111 static void drawtriangle(const Triangle *t) {
112   XPoint points[4];
113   int i;
114
115   for (i=0; i<3; i++) {
116     double *v= t->vertex[i];
117     double x= v[0];
118     double y= v[1];
119     double z= v[2];
120
121     if (z < cut_z) { ncut++; return; }
122     
123     double zezezp= eye_z / (eye_z - z);
124     points[i].x= scale_wmindim * (zezezp * (x - eye_x) + eye_x) + wwidth/2;
125     points[i].y= scale_wmindim * (zezezp *  y                 ) + wheight/2;
126   }
127   points[3]= points[0];
128
129   XA( XFillPolygon(display,pixmap, dmcurrent->fillgc,
130                    points,3,Convex,CoordModeOrigin) );
131   XA( XDrawLines(display,pixmap, dmcurrent->linegc,
132                  points, 4,CoordModeOrigin) );
133 }
134
135 static const unsigned long core_event_mask=
136   ButtonPressMask|ButtonReleaseMask|StructureNotifyMask|ButtonMotionMask;
137
138 static void mkpixmaps(void) {
139   for (currentbuffer=0; currentbuffer<2; currentbuffer++) {
140     XA( pixmap= XCreatePixmap(display,window,wwidth,wheight,x11depth) );
141     doublebuffers[currentbuffer]= pixmap;
142   }
143   currentbuffer= 0;
144 }
145
146 static void mkgcs(DrawingMode *dm, unsigned long planes) {
147   XGCValues gcv;
148
149   gcv.function= GXcopy;
150   gcv.foreground= WhitePixel(display,x11screen);
151   gcv.plane_mask= planes;
152   dm->linegc= XCreateGC(display,pixmap,
153                         GCFunction|GCForeground|GCPlaneMask,
154                         &gcv);
155
156   gcv.function= GXclear;
157   dm->fillgc= XCreateGC(display,pixmap,
158                         GCFunction|GCPlaneMask,
159                         &gcv);
160 }
161
162 static void display_prepare(void) {
163   XSetWindowAttributes wa;
164   XSizeHints hints;
165   
166   XA( display= XOpenDisplay(0) );
167   x11screen= DefaultScreen(display);
168   x11depth= DefaultDepth(display,x11screen);
169   XA( XMatchVisualInfo(display,x11screen,x11depth, TrueColor,&visinfo) );
170   
171   wa.event_mask= core_event_mask;
172   XA( window= XCreateWindow(display, DefaultRootWindow(display),
173                             0,0, wwidth,wheight, 0,x11depth,
174                             InputOutput, visinfo.visual,
175                             CWEventMask, &wa) );
176
177   hints.flags= USPosition;
178   hints.x= 10;
179   hints.y= 10;
180   XSetWMNormalHints(display,window,&hints);
181
182   mkpixmaps();
183
184   mkgcs(&dmwhite, AllPlanes);
185   mkgcs(&dmblue, visinfo.blue_mask);
186   mkgcs(&dmred, visinfo.red_mask);
187 }
188
189 static void drawtriangles(const DrawingMode *dm) {
190   Triangle *const *t;
191   int i;
192
193   dmcurrent= dm;
194   for (i=0, t=displaylist, ncut=0; i<ntris; i++, t++)
195     drawtriangle(*t);
196 }
197
198 static void display_conformation(void) {
199   pixmap= doublebuffers[currentbuffer];
200
201   XA( XFillRectangle(display,pixmap,dmwhite.fillgc,0,0,wwidth,wheight) );
202
203   if (eyes_apart > 0) {
204     const double preferred=0.05, beyond=0.07;
205
206     eye_x= eyes_apart < preferred ? eyes_apart :
207            eyes_apart < beyond ? preferred :
208            eyes_apart - (beyond - preferred);
209     eye_x /= sizeadj_scale;
210     drawtriangles(&dmblue);
211     eye_x= -eye_x;
212     drawtriangles(&dmred);
213   } else {
214     drawtriangles(&dmwhite);
215     printf("shown, %d/%d triangles cut\n", ncut, ntris);
216   }
217   
218   XA( XSetWindowBackgroundPixmap(display,window,pixmap) );
219   XA( XClearWindow(display,window) );
220   currentbuffer= !currentbuffer;
221 }
222
223 static void show(void) {
224   scale_wmindim= sizeadj_scale * wmindim;
225   read_input();
226   transform_coordinates();
227   generate_display_list();
228   sort_display_list();
229   display_conformation();
230 }
231
232 typedef struct {
233   const char *name;
234   void (*start)(void);
235   void (*delta)(double dx, double dy);
236   void (*conclude)(void);
237   void (*abandon)(void);
238 } Drag;
239
240 #define DRAG(x)                                 \
241   static const Drag drag_##x= {                 \
242     #x, drag_##x##_start, drag_##x##_delta,     \
243     drag_##x##_conclude, drag_##x##_abandon     \
244   }
245
246 #define DRAG_SAVING(x, thing)                           \
247   static typeof(thing) original_##thing;                \
248   static void drag_##x##_start(void) {                  \
249     memcpy(&original_##thing, &thing, sizeof(thing));   \
250   }                                                     \
251   static void drag_##x##_conclude(void) { }             \
252   static void drag_##x##_abandon(void) {                \
253     memcpy(&thing, &original_##thing, sizeof(thing));   \
254     show();                                             \
255   }                                                     \
256   DRAG(x)
257
258 static void drag_none_start(void) { }
259 static void drag_none_delta(double dx, double dy) { }
260 static void drag_none_conclude(void) { }
261 static void drag_none_abandon(void) { }
262 DRAG(none);
263
264 static void pvectorcore(const char *n, double v[D3]) {
265   int k;
266   printf("%10s [ ",n);
267   K printf("%# 10.10f ",v[k]);
268   printf("]\n");
269 }
270 static void pvector(const char *n, double v[D3]) {
271   pvectorcore(n,v);
272   putchar('\n');
273 }
274 static void pmatrix(const char *n, double m[D3][D3]) {
275   int j;
276   for (j=0; j<D3; j++) { pvectorcore(n,m[j]); n=""; }
277   putchar('\n');
278 }
279 #define PMATRIX(x) pmatrix(#x,x);
280
281 static void drag_rotate_delta(double dx, double dy) {
282   /* We multiple our transformation matrix by a matrix:
283    *
284    * If we just had y movement, we would rotate about x axis:
285    *  rotation X = [  1    0   0 ]
286    *               [  0   cy  sy ]
287    *               [  0  -sy  cy ]
288    *  where cy and sy are sin and cos of y rotation
289    *
290    * But we should pre-rotate this by a rotation about the z axis
291    * to get it to the right angle (to include x rotation).  So
292    * we make cy and sy be cos() and sin(hypot(x,y)) and use
293    * with cr,sr as cos() and sin(atan2(y,y)):
294    *
295    * Ie we would do  T' = R^T X R T   where
296    *             or  T' =    C    T   where  C = R^T X R  and
297    *
298    *  adjustment R = [  cr  sr  0 ]
299    *                 [ -sr  cr  0 ]
300    *                 [  0    0  1 ]
301    */
302
303   double rotx[D3][D3], adjr[D3][D3];
304   GSL_MATRIX(rotx);
305   GSL_MATRIX(adjr);
306
307   static double temp[D3][D3], change[D3][D3];
308   static GSL_MATRIX(temp);
309   static GSL_MATRIX(change);
310
311   double d= hypot(dx,dy);
312   if (d < 1e-6) return;
313
314   double ang= d*2.0;
315   
316   double cy= cos(ang);
317   double sy= sin(ang);
318   double cr= -dy / d;
319   double sr=  dx / d;
320   printf("\n d=%g cy,sy=%g,%g cr,sr=%g,%g\n\n", d,cy,sy,cr,sr);
321   
322   rotx[0][0]=   1;    rotx[0][1]=   0;     rotx[0][2]=  0;
323   rotx[1][0]=   0;    rotx[1][1]=  cy;     rotx[1][2]= sy;
324   rotx[2][0]=   0;    rotx[2][1]= -sy;     rotx[2][2]= cy;
325   PMATRIX(rotx);
326
327   adjr[0][0]=  cr;    adjr[0][1]=  sr;     adjr[0][2]=  0;
328   adjr[1][0]= -sr;    adjr[1][1]=  cr;     adjr[1][2]=  0;
329   adjr[2][0]=   0;    adjr[2][1]=   0;     adjr[2][2]=  1;
330   PMATRIX(adjr);
331
332   GA( gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0,
333                      &rotx_gsl,&adjr_gsl,
334                      0.0, &temp_gsl) );
335   PMATRIX(temp);
336   
337   GA( gsl_blas_dgemm(CblasTrans,CblasNoTrans, 1.0,
338                      &adjr_gsl,&temp_gsl,
339                      0.0, &change_gsl) );
340   PMATRIX(change);
341
342   static double skew[D3][D3];
343   static GSL_MATRIX(skew);
344   
345   GA( gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0,
346                      &change_gsl,&transform_gsl,
347                      0.0, &skew_gsl) );
348   PMATRIX(skew);
349
350   memcpy(&transform,&skew,sizeof(transform));
351   show();
352   return;
353
354   /* Now we want to normalise skew, the result becomes new transform */
355   double svd_v[D3][D3];
356   GSL_MATRIX(svd_v);
357
358   double sigma[D3], tau[D3];
359   GSL_VECTOR(sigma);
360   GSL_VECTOR(tau);
361   
362   /* We use notation from Wikipedia Polar_decomposition
363    *     Wikipedia's  W      is GSL's U
364    *     Wikipedia's  Sigma  is GSL's S
365    *     Wikipedia's  V      is GSL's V
366    *     Wikipedia's  U      is our desired result
367    * Wikipedia which says if the SVD is    A = W Sigma V*
368    * then the polar decomposition is       A = U P
369    *   where                               P = V Sigma V*
370    *   and                                 U = W V*
371    */
372   
373   GA( gsl_linalg_SV_decomp(&skew_gsl, &svd_v_gsl, &sigma_gsl, &tau_gsl) );
374   pmatrix("W",    skew);
375   pvector("Sigma",sigma);
376   pmatrix("V",    svd_v);
377
378   /* We only need U, not P. */
379   GA( gsl_blas_dgemm(CblasNoTrans,CblasTrans, 1.0,
380                      &skew_gsl,&svd_v_gsl,
381                      0.0,&transform_gsl) );
382
383   pmatrix("U", transform);
384
385   printf("drag_rotate_delta...\n");
386   show();
387 }
388 DRAG_SAVING(rotate, transform);
389
390 static void drag_sizeadj_delta(double dx, double dy) {
391   sizeadj_scale *= pow(3.0, -dy);
392   show();
393 }
394 DRAG_SAVING(sizeadj, sizeadj_scale);
395
396 static void drag_3d_delta(double dx, double dy) {
397   const double min_eyes_apart= -0.02;
398   eyes_apart += dx * 0.1;
399   if (eyes_apart < min_eyes_apart) eyes_apart= min_eyes_apart;
400   printf("sizeadj eyes_apart %g\n", eyes_apart);
401   show();
402 }
403 DRAG_SAVING(3d, eyes_apart);
404
405 static const Drag *drag= &drag_none;
406
407 static int drag_last_x, drag_last_y;
408
409 static void drag_position(int x, int y) {
410   drag->delta((x - drag_last_x) * 1.0 / wmaxdim,
411               (y - drag_last_y) * 1.0 / wmaxdim);
412   drag_last_x= x;
413   drag_last_y= y;
414 }
415
416 static void event_button(XButtonEvent *e) {
417   if (e->window != window || !e->same_screen) return;
418   if (e->type == ButtonPress) {
419     if (e->state || drag != &drag_none) {
420       printf("drag=%s press state=0x%lx abandon\n",
421              drag->name, (unsigned long)e->state);
422       drag->abandon();
423       drag= &drag_none;
424       return;
425     }
426     switch (e->button) {
427     case Button1: drag= &drag_rotate;  break;
428     case Button2: drag= &drag_sizeadj; break;
429     case Button3: drag= &drag_3d;      break;
430     default: printf("unknown drag start %d\n", e->button);
431     }
432     printf("drag=%s press button=%lu start %d,%d\n",
433            drag->name, (unsigned long)e->button, e->x, e->y);
434     drag_last_x= e->x;
435     drag_last_y= e->y;
436     drag->start();
437   }
438   if (e->type == ButtonRelease) {
439     printf("drag=%s release %d,%d\n", drag->name, e->x, e->y);
440     drag_position(e->x, e->y);
441     drag->conclude();
442     drag= &drag_none;
443   }
444 }
445
446 static void event_motion(int x, int y) {
447   printf("drag=%s motion %d,%d\n", drag->name, x, y);
448   drag_position(x,y);
449 }
450
451 static void event_config(XConfigureEvent *e) {
452   if (e->width == wwidth && e->height == wheight)
453     return;
454
455   wwidth= e->width;  wheight= e->height;
456   wmaxdim= wwidth > wheight ? wwidth : wheight;
457   wmindim= wwidth < wheight ? wwidth : wheight;
458   
459   XA( XSetWindowBackground(display,window,BlackPixel(display,x11screen)) );
460   for (currentbuffer=0; currentbuffer<2; currentbuffer++)
461     XA( XFreePixmap(display, doublebuffers[currentbuffer]) );
462
463   mkpixmaps();
464   show();
465 }
466
467 int main(int argc, const char *const *argv) {
468   XEvent event;
469   int k;
470   int motion_deferred=0, motion_x=-1, motion_y=-1;
471   
472   if (argc != 2 || argv[1][0]=='-') {
473     fputs("need filename\n",stderr); exit(8);
474   }
475   input_filename= argv[1];
476
477   read_input();
478   K transform[k][k]= 1.0;
479   display_prepare();
480   show();
481
482   XMapWindow(display,window);
483   for (;;) {
484     if (motion_deferred) {
485       int r= XCheckMaskEvent(display,~0UL,&event);
486       if (!r) {
487         event_motion(motion_x, motion_y);
488         motion_deferred=0;
489         continue;
490       }
491     } else {
492       XNextEvent(display,&event);
493     }
494     switch (event.type) {
495
496     case ButtonPress:
497     case ButtonRelease:     event_button(&event.xbutton);     break;
498       
499     case ConfigureNotify:   event_config(&event.xconfigure);  break;
500
501     case MotionNotify:
502       motion_x= event.xmotion.x;
503       motion_y= event.xmotion.y;
504       motion_deferred= 1;
505       continue;
506       
507     default:
508       printf("unknown event type %u 0x%x\n", event.type,event.type);
509     }
510   }
511 }
512