/Users/lyon/j4p/src/net/rmi/rmiimage/MandelbrotCanvas.java
|
1 package net.rmi.rmiimage;
2
3 import java.awt.*;
4 import java.awt.image.IndexColorModel;
5 import java.awt.image.MemoryImageSource;
6
7 public
8 class MandelbrotCanvas extends Canvas {
9 Image image;
10
11 public void paint(Graphics g) {
12 if (image == null) {
13 image = getToolkit().createImage(
14 new MemoryImageSource(300, 200,
15 generateColorModel(), generatePixels(300, 200), 0, 300));
16 }
17 g.drawImage(image, 0, 0, this);
18 }
19
20 IndexColorModel generateColorModel() {
21 byte[] r = new byte[16];
22 byte[] g = new byte[16];
23 byte[] b = new byte[16];
24
25 r[0] = 0;
26 g[0] = 0;
27 b[0] = 0;
28 r[1] = 0;
29 g[1] = 0;
30 b[1] = (byte) 192;
31 r[2] = 0;
32 g[2] = 0;
33 b[2] = (byte) 255;
34 r[3] = 0;
35 g[3] = (byte) 192;
36 b[3] = 0;
37 r[4] = 0;
38 g[4] = (byte) 255;
39 b[4] = 0;
40 r[5] = 0;
41 g[5] = (byte) 192;
42 b[5] = (byte) 192;
43 r[6] = 0;
44 g[6] = (byte) 255;
45 b[6] = (byte) 255;
46 r[7] = (byte) 192;
47 g[7] = 0;
48 b[7] = 0;
49 r[8] = (byte) 255;
50 g[8] = 0;
51 b[8] = 0;
52 r[9] = (byte) 192;
53 g[9] = 0;
54 b[9] = (byte) 192;
55 r[10] = (byte) 255;
56 g[10] = 0;
57 b[10] = (byte) 255;
58 r[11] = (byte) 192;
59 g[11] = (byte) 192;
60 b[11] = 0;
61 r[12] = (byte) 255;
62 g[12] = (byte) 255;
63 b[12] = 0;
64 r[14] = (byte) 80;
65 g[14] = (byte) 80;
66 b[14] = (byte) 80;
67 r[14] = (byte) 192;
68 g[14] = (byte) 192;
69 b[14] = (byte) 192;
70 r[15] = (byte) 255;
71 g[15] = (byte) 255;
72 b[15] = (byte) 255;
73
74 return new IndexColorModel(4, 16, r, g, b);
75 }
76
77 final float xmin = -2.0f;
78 final float xmax = 1.2f;
79 final float ymin = -1.2f;
80 final float ymax = 1.2f;
81
82 byte[] generatePixels(int w, int h) {
83 byte[] pixels = new byte[w * h];
84 int pIx = 0;
85 float[] p = new float[w];
86 float q = ymin;
87 float dp = (xmax - xmin) / w;
88 float dq = (ymax - ymin) / h;
89
90 p[0] = xmin;
91 for (int i = 1; i < w; i++) {
92 p[i] = p[i - 1] + dp;
93 }
94
95 for (int r = 0; r < h; r++) {
96 for (int c = 0; c < w; c++) {
97 int color = 1;
98 float x = 0.0f;
99 float y = 0.0f;
100 float xsqr = 0.0f;
101 float ysqr = 0.0f;
102 do {
103 xsqr = x * x;
104 ysqr = y * y;
105 y = 2 * x * y + q;
106 x = xsqr - ysqr + p[c];
107 color++;
108 } while (color < 512 && xsqr + ysqr < 4);
109 pixels[pIx++] = (byte) (color % 16);
110 }
111 q += dq;
112 }
113 return pixels;
114 }
115 }
116