foo
[dosdemo] / src / fract.c
1 #include <string.h>
2 #include <limits.h>
3 #include "demo.h"
4 #include "screen.h"
5 #include "gfxutil.h"
6
7 struct vec2x {
8         long x, y;
9 };
10
11 static int init(void);
12 static void destroy(void);
13 static void draw(void);
14 static int julia(long x, long y, long cx, long cy, int max_iter);
15
16 static struct screen scr = {
17         "fract",
18         init,
19         destroy,
20         0, 0,
21         draw
22 };
23
24 /*static long aspect_24x8 = (long)(1.3333333 * 256.0);*/
25 static long xscale_24x8 = (long)(1.3333333 * 1.2 * 256.0);
26 static long yscale_24x8 = (long)(1.2 * 256.0);
27 static int cx, cy;
28 static int max_iter = 50;
29
30 #define WALK_SIZE       20
31
32 struct screen *fract_screen(void)
33 {
34         return &scr;
35 }
36
37 static int init(void)
38 {
39         return 0;
40 }
41
42 static void destroy(void)
43 {
44 }
45
46 static void draw(void)
47 {
48         int i, j;
49         unsigned short *pixels = fb_pixels;
50
51         cx = mouse_x;
52         cy = mouse_y;
53
54         for(i=0; i<fb_height; i++) {
55                 for(j=0; j<fb_width; j++) {
56                         unsigned char pidx = julia(j, i, cx, cy, max_iter) & 0xff;
57                         *pixels++ = (pidx >> 3) | ((pidx >> 2) << 5) | ((pidx >> 3) << 11);
58                 }
59         }
60
61         pixels = fb_pixels;
62         pixels[mouse_y * fb_width + mouse_x] = 0xffe;
63         swap_buffers(0);
64 }
65
66 static long normalize_coord(long x, long range)
67 {
68         /* 2 * x / range - 1*/
69         return (x << 17) / range - 65536;
70 }
71
72 static int julia(long x, long y, long cx, long cy, int max_iter)
73 {
74         int i;
75
76         /* convert to fixed point roughly [-1, 1] */
77         x = (normalize_coord(x, fb_width) >> 8) * xscale_24x8;
78         y = (normalize_coord(y, fb_height) >> 8) * yscale_24x8;
79         cx = (normalize_coord(cx, fb_width) >> 8) * xscale_24x8;
80         cy = (normalize_coord(cy, fb_height) >> 8) * yscale_24x8;
81
82         for(i=0; i<max_iter; i++) {
83                 /* z_n = z_{n-1}**2 + c */
84                 long px = x >> 8;
85                 long py = y >> 8;
86
87                 if(px * px + py * py > (4 << 16)) {
88                         break;
89                 }
90                 x = px * px - py * py + cx;
91                 y = (px * py << 1) + cy;
92         }
93
94         return i < max_iter ? (256 * i / max_iter) : 0;
95 }