triangle.c (2318B)
1 #include <u.h> 2 #include <libc.h> 3 #include <draw.h> 4 #include <event.h> 5 #include <geometry.h> 6 7 #define CSWidth 640 8 #define CSHeight CSWidth 9 #define CSSize (CSWidth * CSHeight) 10 11 char imgbuf[CSSize]; 12 Point pts[3]; 13 int m[3][3]; 14 Image *img; 15 vlong n; 16 char *s; 17 18 void 19 vrender(void) 20 { 21 int X, Y; 22 char *i = imgbuf; 23 for (X = 0; X < CSWidth; X++) 24 for (Y = 0; Y < CSHeight; Y++, i++) { 25 26 #define l(m) (m[0] * X + m[1] * Y + m[2]) 27 #define istriag ((l(m[0]) >= 0) && (l(m[1]) >= 0) && (l(m[2]) >= 0)) 28 29 *i = istriag ? 0xff : 0x00; 30 31 #undef l 32 #undef istriag 33 } 34 } 35 36 void 37 redraw(Image *) 38 { 39 draw(screen, screen->r, display->white, nil, ZP); 40 draw(screen, screen->r, img, nil, ZP); 41 42 string(screen, screen->r.min, display->white, ZP, font, s); 43 } 44 45 void 46 eresized(int new) 47 { 48 if(new && getwindow(display, Refnone) < 0) 49 fprint(2,"can't reattach to window"); 50 redraw(screen); 51 } 52 53 void 54 randomize_pts(void) 55 { 56 pts[0] = Pt(nrand(CSWidth), nrand(CSWidth)); 57 pts[1] = Pt(nrand(CSWidth), nrand(CSWidth)); 58 pts[2] = Pt(nrand(CSWidth), nrand(CSWidth)); 59 } 60 61 void 62 pts2linear(void) 63 { 64 #define lconv(m, u, w) \ 65 m[0] = w.y - u.y, \ 66 m[1] = u.x - w.x, \ 67 m[2] = - m[0] * u.x - m[1] * u.y 68 69 lconv(m[0], pts[0], pts[1]); 70 lconv(m[1], pts[1], pts[2]); 71 lconv(m[2], pts[2], pts[0]); 72 73 #undef lconv 74 } 75 76 void 77 normalize(void) 78 { 79 #define l(m, u) (m[0] * u.x + m[1] * u.y + m[2]) 80 #define invert(m) m[0] = -m[0], m[1] = -m[1], m[2] = -m[2]; 81 82 if (l(m[0], pts[2]) < 0) invert(m[0]); 83 if (l(m[1], pts[0]) < 0) invert(m[1]); 84 if (l(m[2], pts[1]) < 0) invert(m[2]); 85 86 #undef l 87 #undef invert 88 } 89 90 91 void 92 main(void) 93 { 94 95 srand(nsec()); 96 97 n = nsec(); 98 vrender(); 99 n = nsec() - n; 100 s = smprint("render time %lld nsec", n); 101 initdraw(nil, 0, "cubes"); 102 img = allocimage(display, Rect(0, 0, CSWidth, CSHeight), CMAP8, 0, DRed); 103 104 randomize_pts(); 105 pts2linear(); 106 normalize(); 107 n = nsec(); vrender(); n = nsec() - n; 108 loadimage(img, img->r, (uchar *)imgbuf, CSSize * 4); 109 s = smprint("render time %lld nsec", n); 110 redraw(img); 111 112 Event e; 113 einit(Emouse); 114 int timer = etimer(0, 125); 115 for(;;) { 116 int key = event(&e); 117 if (key == timer) { 118 119 randomize_pts(); 120 pts2linear(); 121 normalize(); 122 n = nsec(); vrender(); n = nsec() - n; 123 loadimage(img, img->r, (uchar *)imgbuf, CSSize * 4); 124 free(s); s = smprint("render time %lld nsec", n); 125 redraw(img); 126 } 127 } 128 }