commit before doing some hefty shapekey change, will break compilation
[blender-staging.git] / source / blender / nodes / intern / CMP_nodes / CMP_defocus.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. 
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2006 Blender Foundation.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include "../CMP_util.h"
31
32 /* ************ qdn: Defocus node ****************** */
33 static bNodeSocketType cmp_node_defocus_in[]= {
34         {       SOCK_RGBA, 1, "Image",                  0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
35         {       SOCK_VALUE, 1, "Z",                     0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
36         {       -1, 0, ""       }
37 };
38 static bNodeSocketType cmp_node_defocus_out[]= {
39         {       SOCK_RGBA, 0, "Image",                  0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
40         {       -1, 0, ""       }
41 };
42
43
44 // line coefs for point sampling & scancon. data.
45 typedef struct BokehCoeffs {
46         float x0, y0, dx, dy;
47         float ls_x, ls_y;
48         float min_x, min_y, max_x, max_y;
49 } BokehCoeffs;
50
51 // returns array of BokehCoeffs
52 // returns length of array in 'len_bkh',
53 // radius squared of inscribed disk in 'inradsq', needed in getWeight() test,
54 // BKH[8] is the data returned for the bokeh shape & bkh_b[4] is it's 2d bound
55 static void makeBokeh(char bktype, char ro, int* len_bkh, float* inradsq, BokehCoeffs BKH[8], float bkh_b[4])
56 {
57         float x0, x1, y0, y1, dx, dy, iDxy;
58         float w = MAX2(1e-5f, ro)*M_PI/180.f;   // never reported stangely enough, but a zero offset causes missing center line...
59         float wi = (360.f/bktype)*M_PI/180.f;
60         int i, ov, nv;
61         
62         // bktype must be at least 3 & <= 8
63         bktype = (bktype<3) ? 3 : ((bktype>8) ? 8 : bktype);
64         *len_bkh = bktype;
65         *inradsq = -1.f;
66
67         for (i=0; i<(*len_bkh); i++) {
68                 x0 = cos(w);
69                 y0 = sin(w);
70                 w += wi;
71                 x1 = cos(w);
72                 y1 = sin(w);
73                 if ((*inradsq)<0.f) {
74                         // radius squared of inscribed disk
75                         float idx=(x0+x1)*0.5f, idy=(y0+y1)*0.5f;
76                         *inradsq = idx*idx + idy*idy;
77                 }
78                 BKH[i].x0 = x0;
79                 BKH[i].y0 = y0;
80                 dx = x1-x0, dy = y1-y0;
81                 iDxy = 1.f / sqrt(dx*dx + dy*dy);
82                 dx *= iDxy;
83                 dy *= iDxy;
84                 BKH[i].dx = dx;
85                 BKH[i].dy = dy;
86         }
87
88         // precalc scanconversion data
89         // bokeh bound, not transformed, for scanconvert
90         bkh_b[0] = bkh_b[2] = 1e10f;    // xmin/ymin
91         bkh_b[1] = bkh_b[3] = -1e10f;   // xmax/ymax
92         ov = (*len_bkh) - 1;
93         for (nv=0; nv<(*len_bkh); nv++) {
94                 bkh_b[0] = MIN2(bkh_b[0], BKH[nv].x0);  // xmin
95                 bkh_b[1] = MAX2(bkh_b[1], BKH[nv].x0);  // xmax
96                 bkh_b[2] = MIN2(bkh_b[2], BKH[nv].y0);  // ymin
97                 bkh_b[3] = MAX2(bkh_b[3], BKH[nv].y0);  // ymax
98                 BKH[nv].min_x = MIN2(BKH[ov].x0, BKH[nv].x0);
99                 BKH[nv].max_x = MAX2(BKH[ov].x0, BKH[nv].x0);
100                 BKH[nv].min_y = MIN2(BKH[ov].y0, BKH[nv].y0);
101                 BKH[nv].max_y = MAX2(BKH[ov].y0, BKH[nv].y0);
102                 dy = BKH[nv].y0 - BKH[ov].y0;
103                 BKH[nv].ls_x = (BKH[nv].x0 - BKH[ov].x0) / ((dy==0.f) ? 1.f : dy);
104                 BKH[nv].ls_y = (BKH[nv].ls_x==0.f) ? 1.f : (1.f/BKH[nv].ls_x);
105                 ov = nv;
106         }
107 }
108
109 // test if u/v inside shape & returns weight value
110 static float getWeight(BokehCoeffs* BKH, int len_bkh, float u, float v, float rad, float inradsq)
111 {
112         BokehCoeffs* bc = BKH;
113         float cdist, irad = (rad==0.f) ? 1.f : (1.f/rad);
114         u *= irad;
115         v *= irad;
116  
117         // early out test1: if point outside outer unit disk, it cannot be inside shape
118         cdist = u*u + v*v;
119         if (cdist>1.f) return 0.f;
120         
121         // early out test2: if point inside or on inner disk, point must be inside shape
122         if (cdist<=inradsq) return 1.f;
123         
124         while (len_bkh--) {
125                 if ((bc->dy*(u - bc->x0) - bc->dx*(v - bc->y0)) > 0.f) return 0.f;
126                 bc++;
127         }
128         return 1.f;
129 }
130
131 // QMC.seq. for sampling, A.Keller, EMS
132 static float RI_vdC(unsigned int bits, unsigned int r)
133 {
134         bits = ( bits << 16) | ( bits >> 16);
135         bits = ((bits & 0x00ff00ff) << 8) | ((bits & 0xff00ff00) >> 8);
136         bits = ((bits & 0x0f0f0f0f) << 4) | ((bits & 0xf0f0f0f0) >> 4);
137         bits = ((bits & 0x33333333) << 2) | ((bits & 0xcccccccc) >> 2);
138         bits = ((bits & 0x55555555) << 1) | ((bits & 0xaaaaaaaa) >> 1);
139         bits ^= r;
140         return (float)((double)bits / 4294967296.0);
141 }
142
143 // single channel IIR gaussian filtering
144 // much faster than anything else, constant time independent of width
145 // should extend to multichannel and make this a node, could be useful
146 static void IIR_gauss_single(CompBuf* buf, float sigma)
147 {
148         double q, q2, sc, cf[4], tsM[9], tsu[3], tsv[3];
149         float *X, *Y, *W;
150         int i, x, y, sz;
151
152         // single channel only for now
153         if (buf->type != CB_VAL) return;
154
155         // <0.5 not valid, though can have a possibly useful sort of sharpening effect
156         if (sigma < 0.5) return;
157         
158         // see "Recursive Gabor Filtering" by Young/VanVliet
159         // all factors here in double.prec. Required, because for single.prec it seems to blow up if sigma > ~200
160         if (sigma >= 3.556)
161                 q = 0.9804*(sigma - 3.556) + 2.5091;
162         else // sigma >= 0.5
163                 q = (0.0561*sigma + 0.5784)*sigma - 0.2568;
164         q2 = q*q;
165         sc = (1.1668 + q)*(3.203729649  + (2.21566 + q)*q);
166         // no gabor filtering here, so no complex multiplies, just the regular coefs.
167         // all negated here, so as not to have to recalc Triggs/Sdika matrix
168         cf[1] = q*(5.788961737 + (6.76492 + 3.0*q)*q)/ sc;
169         cf[2] = -q2*(3.38246 + 3.0*q)/sc;
170         // 0 & 3 unchanged
171         cf[3] = q2*q/sc;
172         cf[0] = 1.0 - cf[1] - cf[2] - cf[3];
173
174         // Triggs/Sdika border corrections,
175         // it seems to work, not entirely sure if it is actually totally correct,
176         // Besides J.M.Geusebroek's anigauss.c (see http://www.science.uva.nl/~mark),
177         // found one other implementation by Cristoph Lampert,
178         // but neither seem to be quite the same, result seems to be ok sofar anyway.
179         // Extra scale factor here to not have to do it in filter,
180         // though maybe this had something to with the precision errors
181         sc = cf[0]/((1.0 + cf[1] - cf[2] + cf[3])*(1.0 - cf[1] - cf[2] - cf[3])*(1.0 + cf[2] + (cf[1] - cf[3])*cf[3]));
182         tsM[0] = sc*(-cf[3]*cf[1] + 1.0 - cf[3]*cf[3] - cf[2]);
183         tsM[1] = sc*((cf[3] + cf[1])*(cf[2] + cf[3]*cf[1]));
184         tsM[2] = sc*(cf[3]*(cf[1] + cf[3]*cf[2]));
185         tsM[3] = sc*(cf[1] + cf[3]*cf[2]);
186         tsM[4] = sc*(-(cf[2] - 1.0)*(cf[2] + cf[3]*cf[1]));
187         tsM[5] = sc*(-(cf[3]*cf[1] + cf[3]*cf[3] + cf[2] - 1.0)*cf[3]);
188         tsM[6] = sc*(cf[3]*cf[1] + cf[2] + cf[1]*cf[1] - cf[2]*cf[2]);
189         tsM[7] = sc*(cf[1]*cf[2] + cf[3]*cf[2]*cf[2] - cf[1]*cf[3]*cf[3] - cf[3]*cf[3]*cf[3] - cf[3]*cf[2] + cf[3]);
190         tsM[8] = sc*(cf[3]*(cf[1] + cf[3]*cf[2]));
191
192 #define YVV(L)\
193 {\
194         W[0] = cf[0]*X[0] + cf[1]*X[0] + cf[2]*X[0] + cf[3]*X[0];\
195         W[1] = cf[0]*X[1] + cf[1]*W[0] + cf[2]*X[0] + cf[3]*X[0];\
196         W[2] = cf[0]*X[2] + cf[1]*W[1] + cf[2]*W[0] + cf[3]*X[0];\
197         for (i=3; i<L; i++)\
198                 W[i] = cf[0]*X[i] + cf[1]*W[i-1] + cf[2]*W[i-2] + cf[3]*W[i-3];\
199         tsu[0] = W[L-1] - X[L-1];\
200         tsu[1] = W[L-2] - X[L-1];\
201         tsu[2] = W[L-3] - X[L-1];\
202         tsv[0] = tsM[0]*tsu[0] + tsM[1]*tsu[1] + tsM[2]*tsu[2] + X[L-1];\
203         tsv[1] = tsM[3]*tsu[0] + tsM[4]*tsu[1] + tsM[5]*tsu[2] + X[L-1];\
204         tsv[2] = tsM[6]*tsu[0] + tsM[7]*tsu[1] + tsM[8]*tsu[2] + X[L-1];\
205         Y[L-1] = cf[0]*W[L-1] + cf[1]*tsv[0] + cf[2]*tsv[1] + cf[3]*tsv[2];\
206         Y[L-2] = cf[0]*W[L-2] + cf[1]*Y[L-1] + cf[2]*tsv[0] + cf[3]*tsv[1];\
207         Y[L-3] = cf[0]*W[L-3] + cf[1]*Y[L-2] + cf[2]*Y[L-1] + cf[3]*tsv[0];\
208         for (i=L-4; i>=0; i--)\
209                 Y[i] = cf[0]*W[i] + cf[1]*Y[i+1] + cf[2]*Y[i+2] + cf[3]*Y[i+3];\
210 }
211
212         // intermediate buffers
213         sz = MAX2(buf->x, buf->y);
214         Y = MEM_callocN(sz*sizeof(float), "IIR_gauss Y buf");
215         W = MEM_callocN(sz*sizeof(float), "IIR_gauss W buf");
216         // H
217         for (y=0; y<buf->y; y++) {
218                 X = &buf->rect[y*buf->x];
219                 YVV(buf->x);
220                 memcpy(X, Y, sizeof(float)*buf->x);
221         }
222         // V
223         X = MEM_callocN(buf->y*sizeof(float), "IIR_gauss X buf");
224         for (x=0; x<buf->x; x++) {
225                 for (y=0; y<buf->y; y++)
226                         X[y] = buf->rect[x + y*buf->x];
227                 YVV(buf->y);
228                 for (y=0; y<buf->y; y++)
229                         buf->rect[x + y*buf->x] = Y[y];
230         }
231         MEM_freeN(X);
232
233         MEM_freeN(W);
234         MEM_freeN(Y);
235 #undef YVV
236 }
237
238 static void defocus_blur(bNode *node, CompBuf *new, CompBuf *img, CompBuf *zbuf, float inpval, int no_zbuf)
239 {
240         NodeDefocus *nqd = node->storage;
241         CompBuf *wts;           // weights buffer
242         CompBuf *crad;          // CoC radius buffer
243         BokehCoeffs BKH[8];     // bokeh shape data, here never > 8 pts.
244         float bkh_b[4] = {0};   // shape 2D bound
245         unsigned int p, px, p4, zp, cp, cp4;
246         float *ctcol, u, v, iZ, ct_crad, lwt, wt=0, cR2=0;
247         float dof_sp, maxfgc, bk_hn_theta=0, inradsq=0;
248         float cam_fdist=1, cam_invfdist=1, cam_lens=35;
249         int x, y, sx, sy, len_bkh=0;
250         float aspect, aperture;
251         int minsz;
252         //float bcrad, nmaxc, scf;
253         
254         // get some required params from the current scene camera
255         // (ton) this is wrong, needs fixed
256         Scene *scene= (Scene*)node->id;
257         Object* camob = (scene)? scene->camera: NULL;
258         if (camob && camob->type==OB_CAMERA) {
259                 Camera* cam = (Camera*)camob->data;
260                 cam_lens = cam->lens;
261                 cam_fdist = dof_camera(camob);
262                 if (cam_fdist==0.0) cam_fdist = 1e10f; /* if the dof is 0.0 then set it be be far away */ 
263                 cam_invfdist = 1.f/cam_fdist;
264         }
265
266         // guess work here.. best match with raytraced result
267         minsz = MIN2(img->x, img->y);
268         dof_sp = (float)minsz / (16.f / cam_lens);      // <- == aspect * MIN2(img->x, img->y) / tan(0.5f * fov);
269         
270         // aperture
271         aspect = (img->x > img->y) ? (img->y / (float)img->x) : (img->x / (float)img->y);
272         aperture = 0.5f*(cam_lens / (aspect*32.f)) / nqd->fstop;
273         
274         // if not disk, make bokeh coefficients and other needed data
275         if (nqd->bktype!=0) {
276                 makeBokeh(nqd->bktype, nqd->rotation, &len_bkh, &inradsq, BKH, bkh_b);
277                 bk_hn_theta = 0.5 * nqd->bktype * sin(2.0 * M_PI / nqd->bktype);        // weight factor
278         }
279         
280         // accumulated weights
281         wts = alloc_compbuf(img->x, img->y, CB_VAL, 1);
282         // CoC radius buffer
283         crad = alloc_compbuf(img->x, img->y, CB_VAL, 1);
284
285         // if 'no_zbuf' flag set (which is always set if input is not an image),
286         // values are instead interpreted directly as blur radius values
287         if (no_zbuf) {
288                 // to prevent *reaaallly* big radius values and impossible calculation times,
289                 // limit the maximum to half the image width or height, whichever is smaller
290                 float maxr = 0.5f*(float)MIN2(img->x, img->y);
291                 for (p=0; p<(unsigned int)(img->x*img->y); p++) {
292                         crad->rect[p] = zbuf ? (zbuf->rect[p]*nqd->scale) : inpval;
293                         // bug #5921, limit minimum
294                         crad->rect[p] = MAX2(1e-5f, crad->rect[p]);
295                         crad->rect[p] = MIN2(crad->rect[p], maxr);
296                         // if maxblur!=0, limit maximum
297                         if (nqd->maxblur != 0.f) crad->rect[p] = MIN2(crad->rect[p], nqd->maxblur);
298                 }
299         }
300         else {
301                 // actual zbuffer.
302                 // separate foreground from background CoC's
303                 // then blur background and blend in again with foreground,
304                 // improves the 'blurred foreground overlapping in-focus midground' sharp boundary problem.
305                 // wts buffer here used for blendmask
306                 maxfgc = 0.f; // maximum foreground CoC radius
307                 for (y=0; y<img->y; y++) {
308                         p = y * img->x;
309                         for (x=0; x<img->x; x++) {
310                                 px = p + x;
311                                 iZ = (zbuf->rect[px]==0.f) ? 0.f : (1.f/zbuf->rect[px]);
312                                 crad->rect[px] = 0.5f*(aperture*(dof_sp*(cam_invfdist - iZ) - 1.f));
313                                 if (crad->rect[px] <= 0.f) {
314                                         wts->rect[px] = 1.f;
315                                         crad->rect[px] = -crad->rect[px];
316                                         if (crad->rect[px] > maxfgc) maxfgc = crad->rect[px];
317                                 }
318                                 else crad->rect[px] = wts->rect[px] = 0;
319                         }
320                 }
321                 
322                 // fast blur...
323                 // bug #6656 part 1, probably when previous node_composite.c was split into separate files, it was not properly updated
324                 // to include recent cvs commits (well, at least not defocus node), so this part was missing...
325                 wt = aperture*128.f;
326                 IIR_gauss_single(crad, wt);
327                 IIR_gauss_single(wts, wt);
328                 
329                 // bug #6656 part 2a, although foreground blur is not based anymore on closest object,
330                 // the rescaling op below was still based on that anyway, and unlike the comment in below code,
331                 // the difference is therefore not always that small at all...
332                 // so for now commented out, not sure if this is going to cause other future problems, lets just wait and see...
333                 /*
334                 // find new maximum to scale it back to original
335                 // (could skip this, not strictly necessary, in general, difference is quite small, but just in case...)
336                 nmaxc = 0;
337                 for (p=0; p<(img->x*img->y); p++)
338                         if (crad->rect[p] > nmaxc) nmaxc = crad->rect[p];
339                 // rescale factor
340                 scf = (nmaxc==0.f) ? 1.f: (maxfgc / nmaxc);
341                 */
342
343                 // and blend...
344                 for (y=0; y<img->y; y++) {
345                         p = y*img->x;
346                         for (x=0; x<img->x; x++) {
347                                 px = p + x;
348                                 if (zbuf->rect[px]!=0.f) {
349                                         iZ = (zbuf->rect[px]==0.f) ? 0.f : (1.f/zbuf->rect[px]);
350                                         
351                                         // bug #6656 part 2b, do not rescale
352                                         /*
353                                         bcrad = 0.5f*fabs(aperture*(dof_sp*(cam_invfdist - iZ) - 1.f));
354                                         // scale crad back to original maximum and blend
355                                         crad->rect[px] = bcrad + wts->rect[px]*(scf*crad->rect[px] - bcrad);
356                                         */
357                                         crad->rect[px] = 0.5f*fabs(aperture*(dof_sp*(cam_invfdist - iZ) - 1.f));
358                                         
359                                         // 'bug' #6615, limit minimum radius to 1 pixel, not really a solution, but somewhat mitigates the problem
360                                         crad->rect[px] = MAX2(crad->rect[px], 0.5f);
361                                         // if maxblur!=0, limit maximum
362                                         if (nqd->maxblur != 0.f) crad->rect[px] = MIN2(crad->rect[px], nqd->maxblur);
363                                 }
364                                 else crad->rect[px] = 0.f;
365                                 // clear weights for next part
366                                 wts->rect[px] = 0.f;
367                         }
368                         // esc set by main calling process
369                         if(node->exec & NODE_BREAK)
370                                 break;
371                 }
372         }
373
374         //------------------------------------------------------------------
375         // main loop
376         for (y=0; y<img->y; y++) {
377                 // some sort of visual feedback would be nice, or at least this text in the renderwin header
378                 // but for now just print some info in the console every 8 scanlines.
379                 if (((y & 7)==0) || (y==(img->y-1))) {
380                         if(G.background==0) {
381                                 printf("\rdefocus: Processing Line %d of %d ... ", y+1, img->y);
382                                 fflush(stdout);
383                         }
384                 }
385                 // esc set by main calling process
386                 if(node->exec & NODE_BREAK)
387                         break;
388
389                 zp = y * img->x;
390                 for (x=0; x<img->x; x++) {
391                         cp = zp + x;
392                         cp4 = cp * img->type;
393
394                         // Circle of Confusion radius for current pixel
395                         cR2 = ct_crad = crad->rect[cp];
396                         // skip if zero (border render)
397                         if (ct_crad==0.f) {
398                                 // related to bug #5921, forgot output image when skipping 0 radius values
399                                 new->rect[cp4] = img->rect[cp4];
400                                 if (new->type != CB_VAL) {
401                                         new->rect[cp4+1] = img->rect[cp4+1];
402                                         new->rect[cp4+2] = img->rect[cp4+2];
403                                         new->rect[cp4+3] = img->rect[cp4+3];
404                                 }
405                                 continue;
406                         }
407                         cR2 *= cR2;
408                         
409                         // pixel color
410                         ctcol = &img->rect[cp4];
411                         
412                         if (!nqd->preview) {
413                                 int xs, xe, ys, ye;
414                                 float lwt, wtcol[4] = {0}, aacol[4] = {0};
415
416                                 // shape weight
417                                 if (nqd->bktype==0)     // disk
418                                         wt = 1.f/((float)M_PI*cR2);
419                                 else
420                                         wt = 1.f/(cR2*bk_hn_theta);
421
422                                 // weighted color
423                                 wtcol[0] = wt*ctcol[0];
424                                 if (new->type != CB_VAL) {
425                                         wtcol[1] = wt*ctcol[1];
426                                         wtcol[2] = wt*ctcol[2];
427                                         wtcol[3] = wt*ctcol[3];
428                                 }
429
430                                 // macro for background blur overlap test
431                                 // unfortunately, since this is done per pixel,
432                                 // it has a very significant negative impact on processing time...
433                                 // (eg. aa disk blur without test: 112 sec, vs with test: 176 sec...)
434                                 // iff center blur radius > threshold
435                                 // and if overlap pixel in focus, do nothing, else add color/weigbt
436                                 // (threshold constant is dependant on amount of blur)
437                                 #define TESTBG1(c, w) {\
438                                         if (ct_crad > nqd->bthresh) {\
439                                                 if (crad->rect[p] > nqd->bthresh) {\
440                                                         new->rect[p] += c[0];\
441                                                         wts->rect[p] += w;\
442                                                 }\
443                                         }\
444                                         else {\
445                                                 new->rect[p] += c[0];\
446                                                 wts->rect[p] += w;\
447                                         }\
448                                 }
449                                 #define TESTBG4(c, w) {\
450                                         if (ct_crad > nqd->bthresh) {\
451                                                 if (crad->rect[p] > nqd->bthresh) {\
452                                                         new->rect[p4] += c[0];\
453                                                         new->rect[p4+1] += c[1];\
454                                                         new->rect[p4+2] += c[2];\
455                                                         new->rect[p4+3] += c[3];\
456                                                         wts->rect[p] += w;\
457                                                 }\
458                                         }\
459                                         else {\
460                                                 new->rect[p4] += c[0];\
461                                                 new->rect[p4+1] += c[1];\
462                                                 new->rect[p4+2] += c[2];\
463                                                 new->rect[p4+3] += c[3];\
464                                                 wts->rect[p] += w;\
465                                         }\
466                                 }
467                                 if (nqd->bktype == 0) {
468                                         // Disk
469                                         int _x, i, j, di;
470                                         float Dj, T;
471                                         // AA pixel
472                                         #define AAPIX(a, b) {\
473                                                 int _ny = b;\
474                                                 if ((_ny >= 0) && (_ny < new->y)) {\
475                                                         int _nx = a;\
476                                                         if ((_nx >=0) && (_nx < new->x)) {\
477                                                                 p = _ny*new->x + _nx;\
478                                                                 if (new->type==CB_VAL) {\
479                                                                         TESTBG1(aacol, lwt);\
480                                                                 }\
481                                                                 else {\
482                                                                         p4 = p * new->type;\
483                                                                         TESTBG4(aacol, lwt);\
484                                                                 }\
485                                                         }\
486                                                 }\
487                                         }
488                                         // circle scanline
489                                         #define CSCAN(a, b) {\
490                                                 int _ny = y + b;\
491                                                 if ((_ny >= 0) && (_ny < new->y)) {\
492                                                         xs = x - a + 1;\
493                                                         if (xs < 0) xs = 0;\
494                                                         xe = x + a;\
495                                                         if (xe > new->x) xe = new->x;\
496                                                         p = _ny*new->x + xs;\
497                                                         if (new->type==CB_VAL) {\
498                                                                 for (_x=xs; _x<xe; _x++, p++) TESTBG1(wtcol, wt);\
499                                                         }\
500                                                         else {\
501                                                                 p4 = p * new->type;\
502                                                                 for (_x=xs; _x<xe; _x++, p++, p4+=new->type) TESTBG4(wtcol, wt);\
503                                                         }\
504                                                 }\
505                                         }
506                                         i = ceil(ct_crad);
507                                         j = 0;
508                                         T = 0;
509                                         while (i > j) {
510                                                 Dj = sqrt(cR2 - j*j);
511                                                 Dj -= floor(Dj);
512                                                 di = 0;
513                                                 if (Dj > T) { i--;  di = 1; }
514                                                 T = Dj;
515                                                 aacol[0] = wtcol[0]*Dj;
516                                                 if (new->type != CB_VAL) {
517                                                         aacol[1] = wtcol[1]*Dj;
518                                                         aacol[2] = wtcol[2]*Dj;
519                                                         aacol[3] = wtcol[3]*Dj;
520                                                 }
521                                                 lwt = wt*Dj;
522                                                 if (i!=j) {
523                                                         // outer pixels
524                                                         AAPIX(x+j, y+i);
525                                                         AAPIX(x+j, y-i);
526                                                         if (j) {
527                                                                 AAPIX(x-j, y+i); // BL
528                                                                 AAPIX(x-j, y-i); // TL
529                                                         }
530                                                         if (di) { // only when i changed, interior of outer section
531                                                                 CSCAN(j, i); // bottom
532                                                                 CSCAN(j, -i); // top
533                                                         }
534                                                 }
535                                                 // lower mid section
536                                                 AAPIX(x+i, y+j);
537                                                 if (i) AAPIX(x-i, y+j);
538                                                 CSCAN(i, j);
539                                                 // upper mid section
540                                                 if (j) {
541                                                         AAPIX(x+i, y-j);
542                                                         if (i) AAPIX(x-i, y-j);
543                                                         CSCAN(i, -j);
544                                                 }
545                                                 j++;
546                                         }
547                                         #undef CSCAN
548                                         #undef AAPIX
549                                 }
550                                 else {
551                                         // n-agonal
552                                         int ov, nv;
553                                         float mind, maxd, lwt;
554                                         ys = MAX2((int)floor(bkh_b[2]*ct_crad + y), 0);
555                                         ye = MIN2((int)ceil(bkh_b[3]*ct_crad + y), new->y - 1);
556                                         for (sy=ys; sy<=ye; sy++) {
557                                                 float fxs = 1e10f, fxe = -1e10f;
558                                                 float yf = (sy - y)/ct_crad;
559                                                 int found = 0;
560                                                 ov = len_bkh - 1;
561                                                 mind = maxd = 0;
562                                                 for (nv=0; nv<len_bkh; nv++) {
563                                                         if ((BKH[nv].max_y >= yf) && (BKH[nv].min_y <= yf)) {
564                                                                 float tx = BKH[ov].x0 + BKH[nv].ls_x*(yf - BKH[ov].y0);
565                                                                 if (tx < fxs) { fxs = tx;  mind = BKH[nv].ls_x; }
566                                                                 if (tx > fxe) { fxe = tx;  maxd = BKH[nv].ls_x; }
567                                                                 if (++found == 2) break;
568                                                         }
569                                                         ov = nv;
570                                                 }
571                                                 if (found) {
572                                                         fxs = fxs*ct_crad + x;
573                                                         fxe = fxe*ct_crad + x;
574                                                         xs = (int)floor(fxs), xe = (int)ceil(fxe);
575                                                         // AA hack for first and last x pixel, near vertical edges only
576                                                         if (fabs(mind) <= 1.f) {
577                                                                 if ((xs >= 0) && (xs < new->x)) {
578                                                                         lwt = 1.f-(fxs - xs);
579                                                                         aacol[0] = wtcol[0]*lwt;
580                                                                         p = xs + sy*new->x;
581                                                                         if (new->type==CB_VAL) {
582                                                                                 lwt *= wt;
583                                                                                 TESTBG1(aacol, lwt);
584                                                                         }
585                                                                         else {
586                                                                                 p4 = p * new->type;
587                                                                                 aacol[1] = wtcol[1]*lwt;
588                                                                                 aacol[2] = wtcol[2]*lwt;
589                                                                                 aacol[3] = wtcol[3]*lwt;
590                                                                                 lwt *= wt;
591                                                                                 TESTBG4(aacol, lwt);
592                                                                         }
593                                                                 }
594                                                         }
595                                                         if (fabs(maxd) <= 1.f) {
596                                                                 if ((xe >= 0) && (xe < new->x)) {
597                                                                         lwt = 1.f-(xe - fxe);
598                                                                         aacol[0] = wtcol[0]*lwt;
599                                                                         p = xe + sy*new->x;
600                                                                         if (new->type==CB_VAL) {
601                                                                                 lwt *= wt;
602                                                                                 TESTBG1(aacol, lwt);
603                                                                         }
604                                                                         else {
605                                                                                 p4 = p * new->type;
606                                                                                 aacol[1] = wtcol[1]*lwt;
607                                                                                 aacol[2] = wtcol[2]*lwt;
608                                                                                 aacol[3] = wtcol[3]*lwt;
609                                                                                 lwt *= wt;
610                                                                                 TESTBG4(aacol, lwt);
611                                                                         }
612                                                                 }
613                                                         }
614                                                         xs = MAX2(xs+1, 0);
615                                                         xe = MIN2(xe, new->x);
616                                                         // remaining interior scanline
617                                                         p = sy*new->x + xs;
618                                                         if (new->type==CB_VAL) {
619                                                                 for (sx=xs; sx<xe; sx++, p++) TESTBG1(wtcol, wt);
620                                                         }
621                                                         else {
622                                                                 p4 = p * new->type;
623                                                                 for (sx=xs; sx<xe; sx++, p++, p4+=new->type) TESTBG4(wtcol, wt);
624                                                         }
625                                                 }
626                                         }
627
628                                         // now traverse in opposite direction, y scanlines,
629                                         // but this time only draw the near horizontal edges,
630                                         // applying same AA hack as above
631                                         xs = MAX2((int)floor(bkh_b[0]*ct_crad + x), 0);
632                                         xe = MIN2((int)ceil(bkh_b[1]*ct_crad + x), img->x - 1);
633                                         for (sx=xs; sx<=xe; sx++) {
634                                                 float xf = (sx - x)/ct_crad;
635                                                 float fys = 1e10f, fye = -1e10f;
636                                                 int found = 0;
637                                                 ov = len_bkh - 1;
638                                                 mind = maxd = 0;
639                                                 for (nv=0; nv<len_bkh; nv++) {
640                                                         if ((BKH[nv].max_x >= xf) && (BKH[nv].min_x <= xf)) {
641                                                                 float ty = BKH[ov].y0 + BKH[nv].ls_y*(xf - BKH[ov].x0);
642                                                                 if (ty < fys) { fys = ty;  mind = BKH[nv].ls_y; }
643                                                                 if (ty > fye) { fye = ty;  maxd = BKH[nv].ls_y; }
644                                                                 if (++found == 2) break;
645                                                         }
646                                                         ov = nv;
647                                                 }
648                                                 if (found) {
649                                                         fys = fys*ct_crad + y;
650                                                         fye = fye*ct_crad + y;
651                                                         // near horizontal edges only, line slope <= 1
652                                                         if (fabs(mind) <= 1.f) {
653                                                                 int iys = (int)floor(fys);
654                                                                 if ((iys >= 0) && (iys < new->y)) {
655                                                                         lwt = 1.f - (fys - iys);
656                                                                         aacol[0] = wtcol[0]*lwt;
657                                                                         p = sx + iys*new->x;
658                                                                         if (new->type==CB_VAL) {
659                                                                                 lwt *= wt;
660                                                                                 TESTBG1(aacol, lwt);
661                                                                         }
662                                                                         else {
663                                                                                 p4 = p * new->type;
664                                                                                 aacol[1] = wtcol[1]*lwt;
665                                                                                 aacol[2] = wtcol[2]*lwt;
666                                                                                 aacol[3] = wtcol[3]*lwt;
667                                                                                 lwt *= wt;
668                                                                                 TESTBG4(aacol, lwt);
669                                                                         }
670                                                                 }
671                                                         }
672                                                         if (fabs(maxd) <= 1.f) {
673                                                                 int iye = ceil(fye);
674                                                                 if ((iye >= 0) && (iye < new->y)) {
675                                                                         lwt = 1.f - (iye - fye);
676                                                                         aacol[0] = wtcol[0]*lwt;
677                                                                         p = sx + iye*new->x;
678                                                                         if (new->type==CB_VAL) {
679                                                                                 lwt *= wt;
680                                                                                 TESTBG1(aacol, lwt);
681                                                                         }
682                                                                         else {
683                                                                                 p4 = p * new->type;
684                                                                                 aacol[1] = wtcol[1]*lwt;
685                                                                                 aacol[2] = wtcol[2]*lwt;
686                                                                                 aacol[3] = wtcol[3]*lwt;
687                                                                                 lwt *= wt;
688                                                                                 TESTBG4(aacol, lwt);
689                                                                         }
690                                                                 }
691                                                         }
692                                                 }
693                                         }
694
695                                 }
696                                 #undef TESTBG4
697                                 #undef TESTBG1
698
699                         }
700                         else {
701                                 // sampled, simple rejection sampling here, good enough
702                                 unsigned int maxsam, s, ui = BLI_rand()*BLI_rand();
703                                 float wcor, cpr = BLI_frand();
704                                 if (no_zbuf)
705                                         maxsam = nqd->samples;  // no zbuffer input, use sample value directly
706                                 else {
707                                         // depth adaptive sampling hack, the more out of focus, the more samples taken, 16 minimum.
708                                         maxsam = (int)(0.5f + nqd->samples*(1.f-(float)exp(-fabs(zbuf->rect[cp] - cam_fdist))));
709                                         if (maxsam < 16) maxsam = 16;
710                                 }
711                                 wcor = 1.f/(float)maxsam;
712                                 for (s=0; s<maxsam; ++s) {
713                                         u = ct_crad*(2.f*RI_vdC(s, ui) - 1.f);
714                                         v = ct_crad*(2.f*(s + cpr)/(float)maxsam - 1.f);
715                                         sx = (int)(x + u + 0.5f), sy = (int)(y + v + 0.5f);
716                                         if ((sx<0) || (sx >= new->x) || (sy<0) || (sy >= new->y)) continue;
717                                         p = sx + sy*new->x;
718                                         p4 = p * new->type;
719                                         if (nqd->bktype==0)     // Disk
720                                                 lwt = ((u*u + v*v)<=cR2) ? wcor : 0.f;
721                                         else    // AA not needed here
722                                                 lwt = wcor * getWeight(BKH, len_bkh, u, v, ct_crad, inradsq);
723                                         // prevent background bleeding onto in-focus pixels, user-option
724                                         if (ct_crad > nqd->bthresh) {  // if center blur > threshold
725                                                 if (crad->rect[p] > nqd->bthresh) { // if overlap pixel in focus, do nothing, else add color/weigbt
726                                                         new->rect[p4] += ctcol[0] * lwt;
727                                                         if (new->type != CB_VAL) {
728                                                                 new->rect[p4+1] += ctcol[1] * lwt;
729                                                                 new->rect[p4+2] += ctcol[2] * lwt;
730                                                                 new->rect[p4+3] += ctcol[3] * lwt;
731                                                         }
732                                                         wts->rect[p] += lwt;
733                                                 }
734                                         }
735                                         else {
736                                                 new->rect[p4] += ctcol[0] * lwt;
737                                                 if (new->type != CB_VAL) {
738                                                         new->rect[p4+1] += ctcol[1] * lwt;
739                                                         new->rect[p4+2] += ctcol[2] * lwt;
740                                                         new->rect[p4+3] += ctcol[3] * lwt;
741                                                 }
742                                                 wts->rect[p] += lwt;
743                                         }
744                                 }
745                         }
746
747                 }
748         }
749         
750         // finally, normalize
751         for (y=0; y<new->y; y++) {
752                 p = y * new->x;
753                 p4 = p * new->type;
754                 for (x=0; x<new->x; x++) {
755                         float dv = (wts->rect[p]==0.f) ? 1.f : (1.f/wts->rect[p]);
756                         new->rect[p4] *= dv;
757                         if (new->type!=CB_VAL) {
758                                 new->rect[p4+1] *= dv;
759                                 new->rect[p4+2] *= dv;
760                                 new->rect[p4+3] *= dv;
761                         }
762                         p++;
763                         p4 += new->type;
764                 }
765         }
766
767         free_compbuf(crad);
768         free_compbuf(wts);
769         
770         printf("Done\n");
771 }
772
773
774 static void node_composit_exec_defocus(void *data, bNode *node, bNodeStack **in, bNodeStack **out)
775 {
776         CompBuf *new, *old, *zbuf_use = NULL, *img = in[0]->data, *zbuf = in[1]->data;
777         NodeDefocus *nqd = node->storage;
778         int no_zbuf = nqd->no_zbuf;
779         
780         if ((img==NULL) || (out[0]->hasoutput==0)) return;
781         
782         // if image not valid type or fstop==infinite (128), nothing to do, pass in to out
783         if (((img->type!=CB_RGBA) && (img->type!=CB_VAL)) || ((no_zbuf==0) && (nqd->fstop==128.f))) {
784                 out[0]->data = pass_on_compbuf(img);
785                 return;
786         }
787         
788         if (zbuf!=NULL) {
789                 // Zbuf input, check to make sure, single channel, same size
790                 // doesn't have to be actual zbuffer, but must be value type
791                 if ((zbuf->x != img->x) || (zbuf->y != img->y)) {
792                         // could do a scale here instead...
793                         printf("Z input must be same size as image !\n");
794                         return;
795                 }
796                 zbuf_use = typecheck_compbuf(zbuf, CB_VAL);
797         }
798         else no_zbuf = 1;       // no zbuffer input
799                 
800         // ok, process
801         old = img;
802         if (nqd->gamco) {
803                 // gamma correct, blender func is simplified, fixed value & RGBA only,
804                 // should make user param. also depremul and premul afterwards, gamma
805                 // correction can't work with premul alpha
806                 old = dupalloc_compbuf(img);
807                 premul_compbuf(old, 1);
808                 gamma_correct_compbuf(old, 0);
809                 premul_compbuf(old, 0);
810         }
811         
812         new = alloc_compbuf(old->x, old->y, old->type, 1);
813         defocus_blur(node, new, old, zbuf_use, in[1]->vec[0]*nqd->scale, no_zbuf);
814         
815         if (nqd->gamco) {
816                 premul_compbuf(new, 1);
817                 gamma_correct_compbuf(new, 1);
818                 premul_compbuf(new, 0);
819                 free_compbuf(old);
820         }
821         if(node->exec & NODE_BREAK) {
822                 free_compbuf(new);
823                 new= NULL;
824         }       
825         out[0]->data = new;
826         if (zbuf_use && (zbuf_use != zbuf)) free_compbuf(zbuf_use);
827 }
828
829 static void node_composit_init_defocus(bNode* node)
830 {
831    /* qdn: defocus node */
832    NodeDefocus *nbd = MEM_callocN(sizeof(NodeDefocus), "node defocus data");
833    nbd->bktype = 0;
834    nbd->rotation = 0.f;
835    nbd->preview = 1;
836    nbd->gamco = 0;
837    nbd->samples = 16;
838    nbd->fstop = 128.f;
839    nbd->maxblur = 0;
840    nbd->bthresh = 1.f;
841    nbd->scale = 1.f;
842    nbd->no_zbuf = 1;
843    node->storage = nbd;
844 }
845
846 bNodeType cmp_node_defocus = {
847         /* *next,*prev */       NULL, NULL,
848         /* type code   */       CMP_NODE_DEFOCUS,
849         /* name        */       "Defocus",
850         /* width+range */       150, 120, 200,
851         /* class+opts  */       NODE_CLASS_OP_FILTER, NODE_OPTIONS,
852         /* input sock  */       cmp_node_defocus_in,
853         /* output sock */       cmp_node_defocus_out,
854         /* storage     */       "NodeDefocus",
855         /* execfunc    */       node_composit_exec_defocus,
856         /* butfunc     */       NULL,
857         /* initfunc    */       node_composit_init_defocus,
858         /* freestoragefunc    */        node_free_standard_storage,
859         /* copystoragefunc    */        node_copy_standard_storage,
860         /* id          */       NULL
861 };
862
863