commit 681efd14212b569fe82a1ac492d36cea2a9585a5
parent 4dfcc258692340d2633304fae82dee14af880296
Author: glenda <glenda@device>
Date: Sun, 30 Oct 2022 22:16:44 +0000
cubes: triangular
Diffstat:
A | src/cubes/triangle.c | | | 135 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 135 insertions(+), 0 deletions(-)
diff --git a/src/cubes/triangle.c b/src/cubes/triangle.c
@@ -0,0 +1,135 @@
+#include <u.h>
+#include <libc.h>
+#include <draw.h>
+#include <event.h>
+#include <geometry.h>
+
+#define CSWidth 640
+#define CSHeight 640
+#define CSSize (CSWidth * CSHeight)
+
+u32int imgbuf[CSSize];
+int m[3][3];
+Point pts[3];
+Image *img;
+vlong n;
+char *s;
+
+void
+triangle(int i)
+{
+ int X = i % CSWidth;
+ int Y = i / CSWidth;
+
+ #define l(m) (m[0] * X + m[1] * Y + m[2])
+ #define istriag ((l(m[0]) > 0) && (l(m[1]) > 0) && (l(m[2]) > 0))
+ #define isline ((l(m[0]) <= 10) || (l(m[1]) <= 10) || (l(m[2]) <= 10))
+
+ imgbuf[i] = istriag ? 0x00ff7f00 : (imgbuf[i] / 2) &0xffff0000;
+
+
+ #undef l
+ #undef istriag
+ #undef isline
+}
+
+void
+vrender(void)
+{
+ int i;
+ for (i = 0; i < CSSize; i++) triangle(i);
+}
+
+void
+redraw(Image *)
+{
+ draw(screen, screen->r, display->white, nil, ZP);
+ draw(screen, screen->r, img, nil, ZP);
+
+ string(screen, screen->r.min, display->white, ZP, font, s);
+}
+
+void
+eresized(int new)
+{
+ if(new && getwindow(display, Refnone) < 0)
+ fprint(2,"can't reattach to window");
+ redraw(screen);
+}
+
+void
+randomize_pts(void)
+{
+ pts[0] = Pt(nrand(640), nrand(640));
+ pts[1] = Pt(nrand(640), nrand(640));
+ pts[2] = Pt(nrand(640), nrand(640));
+}
+
+void
+pts2linear(void)
+{
+#define lconv(m, u, w) \
+ m[0] = w.y - u.y, \
+ m[1] = u.x - w.x, \
+ m[2] = - m[0] * u.x - m[1] * u.y
+
+ lconv(m[0], pts[0], pts[1]);
+ lconv(m[1], pts[1], pts[2]);
+ lconv(m[2], pts[2], pts[0]);
+
+#undef lconv
+}
+
+void
+normalize(void)
+{
+#define l(m, u) (m[0] * u.x + m[1] * u.y + m[2])
+#define invert(m) m[0] = -m[0], m[1] = -m[1], m[2] = -m[2];
+
+ if (l(m[0], pts[2]) < 0) invert(m[0]);
+ if (l(m[1], pts[0]) < 0) invert(m[1]);
+ if (l(m[2], pts[1]) < 0) invert(m[2]);
+
+#undef l
+#undef invert
+}
+
+
+void
+main(void)
+{
+
+ srand(nsec());
+
+ n = nsec();
+ vrender();
+ n = nsec() - n;
+ s = smprint("render time %lld nsec", n);
+ initdraw(nil, 0, "cubes");
+ img = allocimage(display, Rect(0, 0, CSWidth, CSHeight), XRGB32, 0, DRed);
+
+ randomize_pts();
+ pts2linear();
+ normalize();
+ n = nsec(); vrender(); n = nsec() - n;
+ loadimage(img, img->r, (uchar *)imgbuf, CSSize * 4);
+ s = smprint("render time %lld nsec", n);
+ redraw(img);
+
+ Event e;
+ einit(Emouse);
+ int timer = etimer(0, 125);
+ for(;;) {
+ int key = event(&e);
+ if (key == timer) {
+
+ randomize_pts();
+ pts2linear();
+ normalize();
+ n = nsec(); vrender(); n = nsec() - n;
+ loadimage(img, img->r, (uchar *)imgbuf, CSSize * 4);
+ free(s); s = smprint("render time %lld nsec", n);
+ redraw(img);
+ }
+ }
+}