root/trunk/dmpp/main.d

Revision 478, 21.9 kB (checked in by FeepingCreature, 1 month ago)
  • Brought DMPP up to speed
Line 
1 module main;
2 version(freetype) import SDL_ttf;
3 import std.math, std.string, std.stdio;
4 import tools.mersenne, tools.base;
5 import qd, SDL_ttf;
6
7 alias Mersenne Random;
8
9 int SDL_SaveBMP(SDL_Surface *surface, char []file) {
10   return SDL_SaveBMP_RW(surface, SDL_RWFromFile(toStringz(file), "wb\0".ptr), 1);
11 }
12
13 struct rect(T, U) {
14   T x, y;
15   U w, h;
16   string toString() { return format("rect (", x, ", ", y, ")[", w, ", ", h, "]"); }
17 }
18
19 bool maybe() { return ((rand&1)==0); }
20 T max(T)(T a, T b) { return (a>b?a:b); }
21
22 struct arguments {
23   string[string] args;
24   bool has(string s) { return (s in args)!=null; }
25   string opIndex(string id) { return args[id]; }
26   string need(string what) {
27     if (!(what in args)) throw new Exception("Required parameter "~what~" not provided");
28     return args[what];
29   }
30   void opCall(string[] args) {
31     string last;
32     void push(string what) { if (!last.length) return; this.args[last]=what; last=""; }
33     foreach (arg; args) {
34       if (!arg.length) continue;
35       if (arg[0]=='-') { push(""); last=arg[1..$]; }
36       else push(arg);
37     }
38     push("");
39   }
40 }
41
42 struct point(T) { T x, y; }
43 struct pair(T) { T a, b; }
44
45 struct converter(T, U) {
46   private rect!(T, T) origin;
47   private rect!(U, U) target;
48   private point!(real) ratio;
49   void opCall(rect!(T,T) start, rect!(U,U) end) {
50     origin=start; target=end;
51     ratio.x=(target.w*1.0)/(origin.w*1.0);
52     ratio.y=(target.h*1.0)/(origin.h*1.0);
53   }
54   complex!(U) toFn(point!(T) p) {
55     complex!(U) np = void;
56     np.re=cast(U)((p.x-origin.x)*ratio.x+target.x);
57     np.im=cast(U)((p.y-origin.y)*ratio.y+target.y);
58     return np;
59   }
60   point!(T) undo(complex!(U) p) {
61     point!(T) up = void; /// undone point
62     up.x=cast(T)((p.re-target.x)/ratio.x+origin.x);
63     up.y=cast(T)((p.im-target.y)/ratio.y+origin.y);
64     return up;
65   }
66   bool isIn(complex!(U) c) {
67     static bool between(U v, U b, U t) { return ((v<b)&&(v>t)) || ((v<t)&&(v>b)); }
68     return (between(c.re, target.x, target.x+target.w) && between(c.im, target.y, target.y+target.h));
69   }
70 }
71
72 struct complex(T) {
73   T re, im;
74   static complex!(T) opCall(T re, T im) { complex!(T) result = void; result.re = re; result.im = im; return result; }
75   complex!(T) opMul(complex!(T) b) {
76     complex result = void;
77     result.re=cast(T)(re*b.re-im*b.im);
78     result.im=cast(T)(re*b.im+im*b.re);
79     return result;
80   }
81   complex!(T) opAdd(complex!(T) b) {
82     complex!(T) result = void;
83     result.re=cast(T)(re+b.re); result.im=cast(T)(im+b.im);
84     return result;
85   }
86   complex!(T) opDiv(complex!(T) b) {
87     complex!(T) result = void;
88     T sqs=cast(T)(b.re*b.re+b.im*b.im);
89     result.re=cast(T)((re*b.re+im*b.im)/sqs); result.im=cast(T)((im*b.re-re*b.im)/sqs);
90     return result;
91   }
92   void opAddAssign(complex!(T) b) {
93     re=cast(T)(re+b.re); im=cast(T)(im+b.im);
94   }
95   void opMulAssign(complex!(T) b) {
96     T tre=cast(T)(re*b.re-im*b.im);
97     im=cast(T)(im*b.re+re*b.im);
98     re=tre;
99   }
100 }
101
102 alias float myval;
103 alias complex!(myval) mycomplex;
104
105 void swap(T)(inout T a, inout T b) { T c=a; a=b; b=c; }
106
107 struct FuncWrapper {
108   myval a, b, c, d, e, f;
109   void function(inout myval re, inout myval im) fn;
110   myval[3] col;
111   public myval p;
112   static FuncWrapper opCall(myval _a, myval _b, myval _c, myval _d, myval _e, myval _f, void function(inout myval re, inout myval im) _fn, myval[] _col, myval _p) {
113     FuncWrapper fw; with(fw) {
114       fw.a=_a; fw.b=_b; fw.c=_c; fw.d=_d; fw.e=_e; fw.f=_f;
115       fw.fn=_fn;
116       col[]=_col[];
117       p=_p;
118     }
119     return fw;
120   }
121   static FuncWrapper opCall(void function(inout myval re, inout myval im) _fn, uint seed, int factor=1) {
122     auto rnd=new Random; rnd.seed(seed);
123     myval getval() {
124       auto v=rnd();
125       myval res=(((v*1.0)/typeof(v).max));
126       /*res=res>0.5?res*res:-1.0-res*res;
127       res*=1.5;
128       return res;*/
129       return (res-0.5)*2.0;
130     }
131     myval[3] col; foreach (inout c; col) c=(rnd()*1.0)/(1.0*typeof(rnd()).max);
132     static void normalize(inout myval r, inout myval g, inout myval b, myval to) {
133       myval factor=to/(r*0.299+g*0.587+b*0.114);
134       r*=factor; g*=factor; b*=factor;
135     }
136     static void boost(inout myval r, inout myval g, inout myval b, myval by) {
137       static void _boost(inout myval lowest, inout myval highest, myval factor) {
138         lowest=lowest*factor;
139         highest=1-(1-highest)*factor;
140       }
141       /// w as in _walue_
142       static ubyte max(myval[3] w) { ubyte m=0; if (w[1]>w[0]) { m=1; if (w[2]>w[1]) m=2; } else if (w[2]>w[0]) m=2; return m; }
143       static ubyte min(myval[3] w) { ubyte m=0; if (w[1]<w[0]) { m=1; if (w[2]<w[1]) m=2; } else if (w[2]<w[0]) m=2; return m; }
144       auto high=max([r,g,b]); auto low=min([r,g,b]);
145       _boost(*[&r,&g,&b][min([r,g,b])], *[&r,&g,&b][max([r,g,b])], by);
146     }
147     normalize(col[0], col[1], col[2], 1.0);
148     boost(col[0], col[1], col[2], 0.5);
149     if (factor==-1) factor=(rnd()%2)+10;
150     auto res=opCall(getval, getval, getval, getval, getval, getval, _fn, col, factor);
151     return res;
152   }
153   void opCall(ref mycomplex p) {
154     myval nre=a*p.re+b*p.im+c;
155     myval nim=d*p.re+e*p.im+f;
156     fn(nre, nim);
157     p.re=nre; p.im=nim;
158   }
159 }
160
161 void function(inout myval re, inout myval im) fns[];
162 char[][] fnames;
163 myval rsq(myval re, myval im) { return re*re+im*im; }
164 /// This is actually faster than doing a switch. I benchmarked it.
165 void setupFns() {
166   fnames~="00-Linear";
167   fns~=function void(inout myval re, inout myval im) {};
168  
169   fnames~="01-Sinusoidal";
170   fns~=function void(inout myval re, inout myval im) { re=sin(re); im=sin(im); };
171  
172   fnames~="02-Spherical";
173   fns~=function void(inout myval re, inout myval im) { myval rs=re*re+im*im; re/=rs; im/=rs; };
174  
175   fnames~="03-Swirl";
176   fns~=function void(inout myval re, inout myval im)
177   { myval r=sqrt(rsq(re, im)); myval a=atan2(im, re); a+=r; re=r*cos(a); im=r*sin(a); };
178  
179   fnames~="04-Horseshoe";
180   fns~=function void(inout myval re, inout myval im)
181   {
182     myval a=atan2(re, im);
183     myval c1=sin(a); myval c2=cos(a);
184     myval nre=c1*re - c2*im;
185     im=c2*re + c1*im;
186     re=nre;
187   };
188  
189   fnames~="05-Polar";
190   fns~=function void(inout myval re, inout myval im)
191   { myval r=1.0/sqrt(rsq(re, im)); re=atan2(im, re)/PI; im=r-1.0; };
192    
193   fnames~="06-Handkerchief";
194   fns~=function void(inout myval re, inout myval im)
195   { myval r=sqrt(rsq(re,im)); myval a=atan2(im, re); re=r*sin(a+r); im=r*cos(a-r); };
196  
197   fnames~="07-Heart";
198   fns~=function void(inout myval re, inout myval im)
199   { myval r=sqrt(rsq(re,im)); myval a=atan2(im, re); a*=r; re=r*sin(a); im=-r*cos(a); };
200  
201   fnames~="08-Disc";
202   fns~=function void(inout myval re, inout myval im)
203   { myval r=sqrt(rsq(re, im)); myval a=atan2(im, re); a/=PI; r*=PI; re=a*sin(r); im=a*cos(r); };
204  
205   fnames~="09-Spiral";
206   fns~=function void(inout myval re, inout myval im)
207   { myval r=sqrt(rsq(re,im)); myval a=atan2(im, re); re=(cos(a)+sin(r))/r; im=(sin(a)-cos(r))/r; };
208  
209   fnames~="10-Hyperbolic";
210   fns~=function void(inout myval re, inout myval im)
211   { myval r=sqrt(rsq(re,im)); myval a=atan2(im, re); re=sin(a)/r; im=cos(a)*r; };
212  
213   fnames~="11-Diamond";
214   fns~=function void(inout myval re, inout myval im)
215   { myval r=sqrt(rsq(re,im)); myval a=atan2(im, re); re=sin(a)*cos(r); im=cos(a)*sin(r); };
216  
217   fnames~="12-Ex";
218   fns~=function void(inout myval re, inout myval im)
219   { myval r=sqrt(rsq(re,im)); myval a=atan2(im, re); re=r*pow(sin(a+r), 3); im=r*pow(cos(a-r), 3); };
220  
221   fnames~="13-Julia";
222   fns~=function void(inout myval re, inout myval im)
223   { myval r=sqrt(rsq(re,im)); myval a=atan2(im, re); r=sqrt(r); a/=2.0; re=r*cos(a); im=r*sin(a); };
224  
225   writefln("Set up ", fns.length, " functions.");
226 }
227
228 int lookup(FuncWrapper f) {
229   foreach (i, fn; fns) if (fn is f.fn) return i;
230   writefln("Lookup failed. Throwing SIGFPE.");
231   int e=0; e=1/e; throw new Exception("Lookup failed");
232 }
233
234 void logfn (FuncWrapper f) {
235   writefln("Function ", fnames[lookup(f)], ":\n  x = p.x * ", f.a, " + p.y * ", f.b, " + ", f.c,
236     ";\n  y = p.x * ", f.d, " + p.y * ", f.e, " + ", f.f, ";"c);
237   writefln("Color: R", f.col[0], " G", f.col[1], " B", f.col[2]);
238 }
239
240 void logfn(FuncWrapper[] fs) {
241   foreach (fw; fs) logfn(fw);
242 }
243
244 import std.c.stdlib:malloc, free;
245 final class fractal {
246   alias rect!(myval, myval) myrect;
247   static struct pixel { myval[3] col; }
248   pixel[] buffer; int w, h;
249   FuncWrapper[] fws;
250   myrect range;
251   converter!(ushort, myval) conv;
252   ulong itercount;
253   void cleanup() {
254     foreach (inout col; buffer) with(col) { foreach (inout c; col) c=0; }
255     conv(rect!(ushort, ushort)(cast(ushort)0, cast(ushort)0, cast(ushort)w, cast(ushort)h), range); // Init
256     itercount=0;
257   }
258   this(int _w, int _h, FuncWrapper[] _fws, myrect _range) {
259     w=_w; h=_h;
260     buffer=(cast(pixel*)malloc(w*h*pixel.sizeof))[0..w*h];
261     fws=_fws; range=_range;
262     logfn(fws);
263     cleanup;
264   }
265   ~this() { free(buffer.ptr); buffer=null; }
266   bool addpixel(mycomplex cp, myval[3] pixcol) {
267     if (!conv.isIn(cp)) return false;
268     auto pp=conv.undo(cp);
269     auto index=pp.x*h+pp.y;
270     // if ((index<0)||(index>=buffer.length)) *(cast(int*)null)=0;
271     for (int i = 0; i < 3; ++i) buffer[index].col[i] += pixcol[i];
272     return true;
273   }
274   void iterate(ulong count) {
275     /// Prescale the probability values to 0..maxint range
276     if (!fws.length) return;
277     ushort[] probability; ushort running_max=0;
278     float psum=0.0; foreach (fw; fws) psum+=fw.p;
279     // any rationale for this? float rndscale=(ushort.max*0.5)/psum;
280     float rndscale=ushort.max/psum;
281     ushort probsum=0;
282     foreach (fw; fws) {
283       running_max+=cast(ushort)(fw.p*rndscale);
284       probability~=running_max; probsum+=running_max;
285     }
286     assert(probability[$-1] > ushort.max * 0.9); // guard against overflow
287     mycomplex n;
288     void resetpoint() {
289       //n.re=0; n.im=0;
290       n.re=((rand()*1.0)/typeof(rand()).max)*2.0-1.0;
291       n.im=((rand()*1.0)/typeof(rand()).max)*2.0-1.0;
292       //for (int i=0; i<20; ++i) fws[rnd.next%fws.length](n);
293     }
294     resetpoint;
295     myval[3] col; foreach (inout c; col) c=0;
296     /// Initialize the point
297     int e=0;
298     while (count) {
299       /// 500000 is close to 524.288, which is 2^19
300       if (!(count&524287)) writefln(count, "...");
301       auto r = rand(), prerandom = cast(ushort) r; r >>= 16;
302       // things are done twice to make full use of the uint
303       if (prerandom >= probability[$-1]) continue; // highly unlikely
304       int choice=0; while (probability[choice]<prerandom) choice++;
305       auto func = fws[choice]; func(n);
306       for (int i = 0; i < 3; ++i) col[i] = (col[i] + func.col[i]) / 2f;
307       if (addpixel(n, col)) itercount++;
308       prerandom = cast(ushort) r;
309       if (prerandom >= probability[$-1]) continue; // still highly unlikely
310       choice=0; while (probability[choice]<prerandom) choice++;
311       func = fws[choice]; func(n);
312       for (int i = 0; i < 3; ++i) col[i] = (col[i] + func.col[i]) / 2f;
313       if (addpixel(n, col)) itercount++;
314       count -= 2;
315     }
316   }
317   Area render(config c, Area target=null) {
318     auto dg={
319       myval ipp=(itercount*1.0)/((buffer.length)*1.0); // iterations per pixel
320       size_t i=0;
321       for (ushort x=0; x<w; x+=c.dispscale) { if (!(x&255)) writefln("Column ", x);
322         for (ushort y=0; y<h; y+=c.dispscale) {
323           //myval tf(myval v) { return pow(log(v*c.brightness+1.0), c.gamma); } // Transform function
324           myval tf(myval v) { return pow(log(v+1) / log(sqrt(2f))*c.brightness, c.gamma); } // Transform function
325           myval factor=1.0/ipp; // Scaling factor
326           static ubyte cap(uint v, ubyte c) { if (v>c) return c; return cast(ubyte)v; } // Self-explanatory
327           ubyte[3] fcol; // "f" colors
328           foreach (ix, cv; buffer[i].col) fcol[ix]=cap(cast(uint)(tf(cv*factor)*/*bness**/256.0), 255);
329           auto col=rgb(fcol);
330           pset(x/c.dispscale, y/c.dispscale, (c.invert?col.invert:col));
331           i+=c.dispscale;
332         }
333         i+=h*(c.dispscale-1);
334       }
335     };
336     if (target) screen.With(target) = dg();
337     else screen.With(c.res[0]/c.dispscale, c.res[1]/c.dispscale) = { dg(); target = display; };
338     return target;
339   }
340 }
341
342 FuncWrapper[] seedgen(uint seed, char[] argstr) {
343   FuncWrapper[] fws;
344   auto rand=new Random; rand.seed(seed);
345   auto amount=rand()%6;
346   if (argstr.length) {
347     foreach (fract; split(argstr, ",")) {
348       while (fract[0]==' ') fract=fract[1..$]; while (fract[$-1]==' ') fract=fract[0..$-1];
349       auto params=split(fract, " "); assert(params.length==7, "Must be seven params to fractal");
350       float[6] coeffs; foreach (i, str; params[1..$]) coeffs[i]=atof(str);
351       auto fn=FuncWrapper(fns[cast(uint)atoi(params[0])], rand());
352       with (fn) { a=coeffs[0]; b=coeffs[1]; c=coeffs[2]; d=coeffs[3]; e=coeffs[4]; f=coeffs[5]; }