2 * Displays a conformation
14 typedef struct { double vertex[3][D3]; } Triangle;
16 static Triangle trisbuffer[MAXTRIS], *displaylist[MAXTRIS];
18 static Vertices conformation;
20 static double transform[D3][D3]= {{1,0,0}, {0,1,0}, {0,0,1}};
21 static GSL_MATRIX(transform);
24 static struct stat input_stab;
25 static const char *input_filename;
26 static int pause_updates;
28 static void read_input(void) {
31 if (input_f) fclose(input_f);
32 input_f= fopen(input_filename, "rb"); if (!input_f) diee("input file");
34 if (fstat(fileno(input_f), &input_stab)) diee("fstat input file");
37 r= fread(&conformation,sizeof(conformation),1,input_f);
38 if (r!=1) diee("fread");
41 static void transform_coordinates(void) {
44 gsl_vector input_gsl= { D3,1 };
49 input_gsl.data= &conformation[v][0];
50 GA( gsl_blas_dgemv(CblasNoTrans, 1.0,&transform_gsl, &input_gsl,
52 K conformation[v][k]= result[k];
56 static int vertex_in_triangles[N], vertex_in_triangles_checked;
58 static void addtriangle(int va, int vb, int vc) {
59 Triangle *t= &trisbuffer[ntris];
62 assert(ntris < MAXTRIS);
64 t->vertex[0][k]= conformation[va][k];
65 t->vertex[1][k]= conformation[vb][k];
66 t->vertex[2][k]= conformation[vc][k];
68 if (!vertex_in_triangles_checked) {
69 vertex_in_triangles[va]++;
70 vertex_in_triangles[vb]++;
71 vertex_in_triangles[vc]++;
73 displaylist[ntris++]= t;
76 static void generate_display_list(void) {
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.
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);
90 if (ve[5]>=0) addtriangle(vb,ve[0],ve[5]);
92 if (ve[1]>=0) addtriangle(vb,ve[1],ve[0]);
95 if (!vertex_in_triangles_checked) {
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);
105 vertex_in_triangles_checked= 1;
109 static int dl_compare(const void *tav, const void *tbv) {
111 const Triangle *const *tap= tav, *ta= *tap;
112 const Triangle *const *tbp= tbv, *tb= *tbp;
114 for (i=0; i<3; i++) {
115 za += ta->vertex[i][2];
116 zb += tb->vertex[i][2];
118 return za > zb ? -1 :
122 static void sort_display_list(void) {
123 qsort(displaylist, ntris, sizeof(*displaylist), dl_compare);
126 /*---------- X stuff ----------*/
130 typedef struct { GC fillgc, linegc; } DrawingMode;
132 static Display *display;
133 static Pixmap pixmap, doublebuffers[2];
134 static Window window;
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;
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;
148 static void drawtriangle(const Triangle *t) {
152 for (i=0; i<3; i++) {
153 const double *v= t->vertex[i];
158 if (z < cut_z) { ncut++; return; }
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;
164 points[3]= points[0];
167 XA( XFillPolygon(display,pixmap, dmcurrent->fillgc,
168 points,3,Convex,CoordModeOrigin) );
169 XA( XDrawLines(display,pixmap, dmcurrent->linegc,
170 points, 4,CoordModeOrigin) );
173 static const unsigned long core_event_mask=
174 ButtonPressMask|ButtonReleaseMask|StructureNotifyMask|ButtonMotionMask|
175 KeyPressMask|SubstructureNotifyMask;
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;
185 static void mkgcs(DrawingMode *dm, unsigned long planes) {
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,
195 gcv.function= GXclear;
196 dm->fillgc= XCreateGC(display,pixmap,
197 GCFunction|GCPlaneMask,
201 static void display_prepare(void) {
202 XSetWindowAttributes wa;
205 XA( display= XOpenDisplay(0) );
206 x11screen= DefaultScreen(display);
207 x11depth= DefaultDepth(display,x11screen);
208 XA( XMatchVisualInfo(display,x11screen,x11depth, TrueColor,&visinfo) );
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,
216 hints.flags= USPosition;
219 XSetWMNormalHints(display,window,&hints);
223 mkgcs(&dmwhite, AllPlanes);
224 mkgcs(&dmblue, visinfo.blue_mask);
225 mkgcs(&dmred, visinfo.red_mask);
228 static void drawtriangles(const DrawingMode *dm) {
233 for (i=0, t=displaylist, ncut=0; i<ntris; i++, t++)
237 static void display_conformation(void) {
238 pixmap= doublebuffers[currentbuffer];
240 XA( XFillRectangle(display,pixmap,dmwhite.fillgc,0,0,wwidth,wheight) );
242 if (eyes_apart > 0) {
243 const double stationary= 0.07;
245 eye_x= eyes_apart < eyes_apart_preferred
247 eyes_apart < (eyes_apart_preferred + stationary)
248 ? eyes_apart_preferred
249 : eyes_apart - stationary;
250 eye_x /= sizeadj_scale;
251 drawtriangles(&dmblue);
253 drawtriangles(&dmred);
255 drawtriangles(&dmwhite);
256 printf("shown, %d/%d triangles cut\n", ncut, ntris);
259 XA( XSetWindowBackgroundPixmap(display,window,pixmap) );
260 XA( XClearWindow(display,window) );
261 currentbuffer= !currentbuffer;
264 static void show(void) {
265 scale_wmindim= sizeadj_scale * wmindim;
267 transform_coordinates();
268 generate_display_list();
270 display_conformation();
275 void (*start)(const XButtonEvent *e);
276 void (*delta)(double dx, double dy);
277 void (*conclude)(void);
278 void (*abandon)(void);
282 static const Drag drag_##x= { \
283 #x, drag_##x##_start, drag_##x##_delta, \
284 drag_##x##_conclude, drag_##x##_abandon \
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)); \
293 static void drag_##x##_conclude(void) { } \
294 static void drag_##x##_abandon(void) { \
295 memcpy(&thing, &original_##thing, sizeof(thing)); \
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) { }
306 static void pvectorcore(const char *n, double v[D3]) {
309 K printf("%# 10.10f ",v[k]);
312 static void pvector(const char *n, double v[D3]) {
316 static void pmatrix(const char *n, double m[D3][D3]) {
318 for (j=0; j<D3; j++) { pvectorcore(n,m[j]); n=""; }
321 #define PMATRIX(x) pmatrix(#x,x);
323 static double drag_transform_conv_x_z= 0;
324 static double drag_transform_conv_y_z= 0;
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),
330 drag_transform_conv_y_z= MAX( MIN(e->x * factor / wwidth - (factor/2),
332 printf("drag_transform_conv_{x,y}_z = %g,%g\n",
333 drag_transform_conv_x_z, drag_transform_conv_y_z);
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;
342 static void drag_rotate_delta(double dx, double dy) {
343 /* We multiple our transformation matrix by a matrix:
345 * If we just had y movement, we would rotate about x axis:
346 * rotation X = [ 1 0 0 ]
349 * where cy and sy are sin and cos of y rotation
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)):
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
359 * adjustment R = [ cr sr 0 ]
361 * [ 0 0 1 ] or make_z_rotation(cr,sr)
363 * rotation Z = [ cz sz 0 ]
365 * [ 0 0 1 ] or make_z_rotation(cz,sz)
368 double rotx[D3][D3], adjr[D3][D3], rotz[D3][D3];
373 static double temp[D3][D3], change[D3][D3];
374 static GSL_MATRIX(temp);
375 static GSL_MATRIX(change);
377 printf("\nTRANSFORM %g, %g\n", dx,dy);
379 double dz= -drag_transform_conv_x_z * dx +
380 drag_transform_conv_y_z * dy;
382 dx *= (1 - fabs(drag_transform_conv_x_z));
383 dy *= (1 - fabs(drag_transform_conv_y_z));
385 double d= hypot(dx,dy);
387 printf(" dx,dy,dz = %g, %g, %g d = %g\n", dx,dy,dz, d);
389 if (hypot(d,dz) < 1e-6) return;
391 printf(" no xy rotation\n");
406 printf("\n d=%g cy,sy=%g,%g cr,sr=%g,%g\n\n", d,cy,sy,cr,sr);
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;
413 make_z_rotation(adjr,cr,sr);
416 GA( gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0,
419 pmatrix("X R", temp);
421 GA( gsl_blas_dgemm(CblasTrans,CblasNoTrans, 1.0,
427 make_z_rotation(rotz,cos(angz),sin(angz));
430 GA( gsl_blas_dgemm(CblasTrans,CblasNoTrans, 1.0,
431 &rotz_gsl,&change_gsl,
433 pmatrix("Z C", temp);
435 static double skew[D3][D3];
436 static GSL_MATRIX(skew);
438 GA( gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0,
439 &temp_gsl, &transform_gsl,
443 memcpy(&transform,&skew,sizeof(transform));
447 /* Now we want to normalise skew, the result becomes new transform */
448 double svd_v[D3][D3];
451 double sigma[D3], tau[D3];
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*
466 GA( gsl_linalg_SV_decomp(&skew_gsl, &svd_v_gsl, &sigma_gsl, &tau_gsl) );
468 pvector("Sigma",sigma);
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) );
476 pmatrix("U", transform);
478 printf("drag_rotate_delta...\n");
481 DRAG_SAVING(rotate, transform, drag_transform_prep(e));
483 static void drag_sizeadj_delta(double dx, double dy) {
484 sizeadj_scale *= pow(3.0, -dy);
487 DRAG_SAVING(sizeadj, sizeadj_scale, );
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);
495 DRAG_SAVING(3d, eyes_apart, );
497 static const Drag *drag= &drag_none;
499 static int drag_last_x, drag_last_y;
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);
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);
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);
524 printf("drag=%s press button=%lu start %d,%d\n",
525 drag->name, (unsigned long)e->button, e->x, e->y);
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);
538 static void event_motion(int x, int y) {
539 printf("drag=%s motion %d,%d\n", drag->name, x, y);
543 static void transform_preset_record(const char *fn, const char *fn_new) {
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");
552 static void transform_preset_playback(const char *fn) {
555 if (!f && errno==ENOENT) {
556 fprintf(stderr,"no preset %s\n",fn);
561 if (fread(transform,sizeof(transform),1,f) != 1) {
562 perror("read preset!");
570 static void event_key(XKeyEvent *e) {
573 char buf[10], buf_nomod[10];
576 r= XLookupString(e,buf,sizeof(buf)-1,&ks,0);
578 printf("XLookupString keycode=%u state=0x%x gave %d\n",
579 e->keycode, e->state, r);
583 if (!strcmp(buf,"q"))
585 else if (!strcmp(buf,"p"))
586 pause_updates= !pause_updates;
587 else if (!strcmp(buf,"w")) {
588 wireframe= !wireframe;
591 } else if (!strcmp(buf,"d")) {
592 eyes_apart= eyes_apart>0 ? eyes_apart_min : eyes_apart_preferred;
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);
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",
622 static void event_config(XConfigureEvent *e) {
623 if (e->width == wwidth && e->height == wheight)
626 wwidth= e->width; wheight= e->height;
627 wmaxdim= wwidth > wheight ? wwidth : wheight;
628 wmindim= wwidth < wheight ? wwidth : wheight;
630 XA( XSetWindowBackground(display,window,BlackPixel(display,x11screen)) );
631 for (currentbuffer=0; currentbuffer<2; currentbuffer++)
632 XA( XFreePixmap(display, doublebuffers[currentbuffer]) );
638 static void check_input(void) {
642 r= stat(input_filename, &newstab);
643 if (r<0) diee("could not check input");
645 #define CI(x) if (newstab.st_##x == input_stab.st_##x) ; else goto changed
657 static void topocheck(void) {
658 int v1,e,v2,eprime,v1prime, count;
661 FOR_VEDGE(v2,eprime,v1prime)
662 if (v1prime==v1) count++;
664 fprintf(stderr,"%02x -%d-> %02x reverse edge count = %d!\n",
666 FOR_VEDGE(v2,eprime,v1prime)
667 fprintf(stderr,"%02x -%d-> %02x -> %d -> %02x\n",
668 v1,e,v2,eprime,v1prime);
674 int main(int argc, const char *const *argv) {
675 static const int wantedevents= POLLIN|POLLPRI|POLLERR|POLLHUP;
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;
683 if (argc==1) { printf("topology self-consistent, ok\n"); exit(0); }
685 if (argc != 2 || argv[1][0]=='-') {
686 fputs("need filename\n",stderr); exit(8);
688 input_filename= argv[1];
691 K transform[k][k]= 1.0;
695 XMapWindow(display,window);
698 XA( XInternalConnectionNumbers(display, &xfds, &nxfds) );
699 if (polls_alloc <= nxfds) {
700 polls_alloc= nxfds + polls_alloc + 1;
701 polls= realloc(polls, sizeof(*polls) * polls_alloc);
702 if (!polls) diee("realloc for pollfds");
704 for (i=0; i<nxfds; i++) {
705 polls[i].fd= xfds[i];
706 polls[i].events= wantedevents;
711 polls[i].fd= ConnectionNumber(display);
712 polls[i].events= wantedevents;
714 r= poll(polls, nxfds+1, motion_deferred ? 0 : pause_updates ? -1 : 200);
716 if (errno==EINTR) continue;
720 for (i=0; i<nxfds; i++)
721 if (polls[i].revents)
722 XProcessInternalConnection(display, polls[i].fd);
724 r= XCheckMaskEvent(display,~0UL,&event);
726 if (motion_deferred) {
727 event_motion(motion_x, motion_y);
735 switch (event.type) {
738 case ButtonRelease: event_button(&event.xbutton); break;
740 case KeyPress: event_key(&event.xkey); break;
742 case ConfigureNotify: event_config(&event.xconfigure); break;
745 motion_x= event.xmotion.x;
746 motion_y= event.xmotion.y;
751 printf("unknown event type %u 0x%x\n", event.type,event.type);