ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/cv/bsdfrbf.c
(Generate patch)

Comparing ray/src/cv/bsdfrbf.c (file contents):
Revision 2.8 by greg, Wed Oct 2 20:38:26 2013 UTC vs.
Revision 2.21 by greg, Sat Mar 15 19:47:16 2014 UTC

# Line 7 | Line 7 | static const char RCSid[] = "$Id$";
7   *      G. Ward
8   */
9  
10 + /****************************************************************
11 + 1) Collect samples into a grid using the Shirley-Chiu
12 +        angular mapping from a hemisphere to a square.
13 +
14 + 2) Compute an adaptive quadtree by subdividing the grid so that
15 +        each leaf node has at least one sample up to as many
16 +        samples as fit nicely on a plane to within a certain
17 +        MSE tolerance.
18 +
19 + 3) Place one Gaussian lobe at each leaf node in the quadtree,
20 +        sizing it to have a radius equal to the leaf size and
21 +        a volume equal to the energy in that node.
22 + *****************************************************************/
23 +
24   #define _USE_MATH_DEFINES
25   #include <stdio.h>
26   #include <stdlib.h>
# Line 15 | Line 29 | static const char RCSid[] = "$Id$";
29   #include "bsdfrep.h"
30  
31   #ifndef RSCA
32 < #define RSCA            2.7             /* radius scaling factor (empirical) */
32 > #define RSCA            2.2             /* radius scaling factor (empirical) */
33   #endif
34 < #ifndef MAXFRAC
35 < #define MAXFRAC         0.5             /* maximum contribution to neighbor */
34 > #ifndef SMOOTH_MSE
35 > #define SMOOTH_MSE      5e-5            /* acceptable mean squared error */
36   #endif
37 < #ifndef NNEIGH
38 < #define NNEIGH          10              /* number of neighbors to consider */
37 > #ifndef SMOOTH_MSER
38 > #define SMOOTH_MSER     0.03            /* acceptable relative MSE */
39   #endif
40 <                                /* our loaded grid for this incident angle */
40 > #define MAX_RAD         (GRIDRES/8)     /* maximum lobe radius */
41 >
42 > #define RBFALLOCB       10              /* RBF allocation block size */
43 >
44 >                                /* our loaded grid or comparison DSFs */
45   GRIDVAL                 dsf_grid[GRIDRES][GRIDRES];
46  
47   /* Start new DSF input grid */
# Line 54 | Line 72 | add_bsdf_data(double theta_out, double phi_out, double
72          ovec[1] = sin((M_PI/180.)*phi_out) * ovec[2];
73          ovec[2] = sqrt(1. - ovec[2]*ovec[2]);
74  
75 <        if (val <= 0)                   /* truncate to zero */
58 <                val = 0;
59 <        else if (!isDSF)
75 >        if (!isDSF)
76                  val *= ovec[2];         /* convert from BSDF to DSF */
77  
78                                          /* update BSDF histogram */
# Line 65 | Line 81 | add_bsdf_data(double theta_out, double phi_out, double
81  
82          pos_from_vec(pos, ovec);
83  
84 <        dsf_grid[pos[0]][pos[1]].vsum += val;
85 <        dsf_grid[pos[0]][pos[1]].nval++;
84 >        dsf_grid[pos[0]][pos[1]].sum.v += val;
85 >        dsf_grid[pos[0]][pos[1]].sum.n++;
86   }
87  
88 < /* Compute radii for non-empty bins */
73 < /* (distance to furthest empty bin for which non-empty bin is the closest) */
88 > /* Compute minimum BSDF from histogram (does not clear) */
89   static void
75 compute_radii(void)
76 {
77        unsigned int    fill_grid[GRIDRES][GRIDRES];
78        unsigned short  fill_cnt[GRIDRES][GRIDRES];
79        FVECT           ovec0, ovec1;
80        double          ang2, lastang2;
81        int             r, i, j, jn, ii, jj, inear, jnear;
82
83        r = GRIDRES/2;                          /* proceed in zig-zag */
84        for (i = 0; i < GRIDRES; i++)
85            for (jn = 0; jn < GRIDRES; jn++) {
86                j = (i&1) ? jn : GRIDRES-1-jn;
87                if (dsf_grid[i][j].nval)        /* find empty grid pos. */
88                        continue;
89                ovec_from_pos(ovec0, i, j);
90                inear = jnear = -1;             /* find nearest non-empty */
91                lastang2 = M_PI*M_PI;
92                for (ii = i-r; ii <= i+r; ii++) {
93                    if (ii < 0) continue;
94                    if (ii >= GRIDRES) break;
95                    for (jj = j-r; jj <= j+r; jj++) {
96                        if (jj < 0) continue;
97                        if (jj >= GRIDRES) break;
98                        if (!dsf_grid[ii][jj].nval)
99                                continue;
100                        ovec_from_pos(ovec1, ii, jj);
101                        ang2 = 2. - 2.*DOT(ovec0,ovec1);
102                        if (ang2 >= lastang2)
103                                continue;
104                        lastang2 = ang2;
105                        inear = ii; jnear = jj;
106                    }
107                }
108                if (inear < 0) {
109                        fprintf(stderr,
110                                "%s: Could not find non-empty neighbor!\n",
111                                        progname);
112                        exit(1);
113                }
114                ang2 = sqrt(lastang2);
115                r = ANG2R(ang2);                /* record if > previous */
116                if (r > dsf_grid[inear][jnear].crad)
117                        dsf_grid[inear][jnear].crad = r;
118                                                /* next search radius */
119                r = ang2*(2.*GRIDRES/M_PI) + 3;
120            }
121                                                /* blur radii over hemisphere */
122        memset(fill_grid, 0, sizeof(fill_grid));
123        memset(fill_cnt, 0, sizeof(fill_cnt));
124        for (i = 0; i < GRIDRES; i++)
125            for (j = 0; j < GRIDRES; j++) {
126                if (!dsf_grid[i][j].crad)
127                        continue;               /* missing distance */
128                r = R2ANG(dsf_grid[i][j].crad)*(2.*RSCA*GRIDRES/M_PI);
129                for (ii = i-r; ii <= i+r; ii++) {
130                    if (ii < 0) continue;
131                    if (ii >= GRIDRES) break;
132                    for (jj = j-r; jj <= j+r; jj++) {
133                        if (jj < 0) continue;
134                        if (jj >= GRIDRES) break;
135                        if ((ii-i)*(ii-i) + (jj-j)*(jj-j) > r*r)
136                                continue;
137                        fill_grid[ii][jj] += dsf_grid[i][j].crad;
138                        fill_cnt[ii][jj]++;
139                    }
140                }
141            }
142                                                /* copy back blurred radii */
143        for (i = 0; i < GRIDRES; i++)
144            for (j = 0; j < GRIDRES; j++)
145                if (fill_cnt[i][j])
146                        dsf_grid[i][j].crad = fill_grid[i][j]/fill_cnt[i][j];
147 }
148
149 /* Cull points for more uniform distribution, leave all nval 0 or 1 */
150 static void
151 cull_values(void)
152 {
153        FVECT   ovec0, ovec1;
154        double  maxang, maxang2;
155        int     i, j, ii, jj, r;
156                                                /* simple greedy algorithm */
157        for (i = 0; i < GRIDRES; i++)
158            for (j = 0; j < GRIDRES; j++) {
159                if (!dsf_grid[i][j].nval)
160                        continue;
161                if (!dsf_grid[i][j].crad)
162                        continue;               /* shouldn't happen */
163                ovec_from_pos(ovec0, i, j);
164                maxang = 2.*R2ANG(dsf_grid[i][j].crad);
165                if (maxang > ovec0[2])          /* clamp near horizon */
166                        maxang = ovec0[2];
167                r = maxang*(2.*GRIDRES/M_PI) + 1;
168                maxang2 = maxang*maxang;
169                for (ii = i-r; ii <= i+r; ii++) {
170                    if (ii < 0) continue;
171                    if (ii >= GRIDRES) break;
172                    for (jj = j-r; jj <= j+r; jj++) {
173                        if (jj < 0) continue;
174                        if (jj >= GRIDRES) break;
175                        if (!dsf_grid[ii][jj].nval)
176                                continue;
177                        if ((ii == i) & (jj == j))
178                                continue;       /* don't get self-absorbed */
179                        ovec_from_pos(ovec1, ii, jj);
180                        if (2. - 2.*DOT(ovec0,ovec1) >= maxang2)
181                                continue;
182                                                /* absorb sum */
183                        dsf_grid[i][j].vsum += dsf_grid[ii][jj].vsum;
184                        dsf_grid[i][j].nval += dsf_grid[ii][jj].nval;
185                                                /* keep value, though */
186                        dsf_grid[ii][jj].vsum /= (float)dsf_grid[ii][jj].nval;
187                        dsf_grid[ii][jj].nval = 0;
188                    }
189                }
190            }
191                                                /* final averaging pass */
192        for (i = 0; i < GRIDRES; i++)
193            for (j = 0; j < GRIDRES; j++)
194                if (dsf_grid[i][j].nval > 1) {
195                        dsf_grid[i][j].vsum /= (float)dsf_grid[i][j].nval;
196                        dsf_grid[i][j].nval = 1;
197                }
198 }
199
200 /* Compute minimum BSDF from histogram and clear it */
201 static void
90   comp_bsdf_min()
91   {
92 <        int     cnt;
93 <        int     i, target;
92 >        unsigned long   cnt, target;
93 >        int             i;
94  
95          cnt = 0;
96          for (i = HISTLEN; i--; )
# Line 216 | Line 104 | comp_bsdf_min()
104          for (i = 0; cnt <= target; i++)
105                  cnt += bsdf_hist[i];
106          bsdf_min = histval(i-1);
219        memset(bsdf_hist, 0, sizeof(bsdf_hist));
107   }
108  
109 < /* Find n nearest sub-sampled neighbors to the given grid position */
109 > /* Determine if the given region is empty of grid samples */
110   static int
111 < get_neighbors(int neigh[][2], int n, const int i, const int j)
111 > empty_region(int x0, int x1, int y0, int y1)
112   {
113 <        int     k = 0;
114 <        int     r;
115 <                                                /* search concentric squares */
116 <        for (r = 1; r < GRIDRES; r++) {
117 <                int     ii, jj;
118 <                for (ii = i-r; ii <= i+r; ii++) {
119 <                        int     jstep = 1;
120 <                        if (ii < 0) continue;
121 <                        if (ii >= GRIDRES) break;
122 <                        if ((i-r < ii) & (ii < i+r))
123 <                                jstep = r<<1;
124 <                        for (jj = j-r; jj <= j+r; jj += jstep) {
125 <                                if (jj < 0) continue;
126 <                                if (jj >= GRIDRES) break;
127 <                                if (dsf_grid[ii][jj].nval) {
128 <                                        neigh[k][0] = ii;
129 <                                        neigh[k][1] = jj;
130 <                                        if (++k >= n)
131 <                                                return(n);
132 <                                }
133 <                        }
113 >        int     x, y;
114 >
115 >        for (x = x0; x < x1; x++)
116 >            for (y = y0; y < y1; y++)
117 >                if (dsf_grid[x][y].sum.n)
118 >                        return(0);
119 >        return(1);
120 > }
121 >
122 > /* Determine if the given region is smooth enough to be a single lobe */
123 > static int
124 > smooth_region(int x0, int x1, int y0, int y1)
125 > {
126 >        RREAL   rMtx[3][3];
127 >        FVECT   xvec;
128 >        double  A, B, C, nvs, sqerr;
129 >        int     x, y, n;
130 >                                        /* compute planar regression */
131 >        memset(rMtx, 0, sizeof(rMtx));
132 >        memset(xvec, 0, sizeof(xvec));
133 >        for (x = x0; x < x1; x++)
134 >            for (y = y0; y < y1; y++)
135 >                if ((n = dsf_grid[x][y].sum.n) > 0) {
136 >                        double  z = dsf_grid[x][y].sum.v;
137 >                        rMtx[0][0] += x*x*(double)n;
138 >                        rMtx[0][1] += x*y*(double)n;
139 >                        rMtx[0][2] += x*(double)n;
140 >                        rMtx[1][1] += y*y*(double)n;
141 >                        rMtx[1][2] += y*(double)n;
142 >                        rMtx[2][2] += (double)n;
143 >                        xvec[0] += x*z;
144 >                        xvec[1] += y*z;
145 >                        xvec[2] += z;
146                  }
147 <        }
148 <        return(k);
147 >        rMtx[1][0] = rMtx[0][1];
148 >        rMtx[2][0] = rMtx[0][2];
149 >        rMtx[2][1] = rMtx[1][2];
150 >        nvs = rMtx[2][2];
151 >        if (SDinvXform(rMtx, rMtx) != SDEnone)
152 >                return(1);              /* colinear values */
153 >        A = DOT(rMtx[0], xvec);
154 >        B = DOT(rMtx[1], xvec);
155 >        C = DOT(rMtx[2], xvec);
156 >        sqerr = 0.0;                    /* compute mean squared error */
157 >        for (x = x0; x < x1; x++)
158 >            for (y = y0; y < y1; y++)
159 >                if ((n = dsf_grid[x][y].sum.n) > 0) {
160 >                        double  d = A*x + B*y + C - dsf_grid[x][y].sum.v/n;
161 >                        sqerr += n*d*d;
162 >                }
163 >        if (sqerr <= nvs*SMOOTH_MSE)    /* below absolute MSE threshold? */
164 >                return(1);
165 >                                        /* OR below relative MSE threshold? */
166 >        return(sqerr*nvs <= xvec[2]*xvec[2]*SMOOTH_MSER);
167   }
168  
169 < /* Adjust coded radius for the given grid position based on neighborhood */
169 > /* Create new lobe based on integrated samples in region */
170   static int
171 < adj_coded_radius(const int i, const int j)
171 > create_lobe(RBFVAL *rvp, int x0, int x1, int y0, int y1)
172   {
173 <        const double    rad0 = R2ANG(dsf_grid[i][j].crad);
174 <        double          currad = RSCA * rad0;
175 <        int             neigh[NNEIGH][2];
176 <        int             n;
177 <        FVECT           our_dir;
173 >        double  vtot = 0.0;
174 >        int     nv = 0;
175 >        double  rad;
176 >        int     x, y;
177 >                                        /* compute average for region */
178 >        for (x = x0; x < x1; x++)
179 >            for (y = y0; y < y1; y++) {
180 >                vtot += dsf_grid[x][y].sum.v;
181 >                nv += dsf_grid[x][y].sum.n;
182 >            }
183 >        if (!nv) {
184 >                fprintf(stderr, "%s: internal - missing samples in create_lobe\n",
185 >                                progname);
186 >                exit(1);
187 >        }
188 >        if (vtot <= 0)                  /* only create positive lobes */
189 >                return(0);
190 >                                        /* peak value based on integral */
191 >        vtot *= (x1-x0)*(y1-y0)*(2.*M_PI/GRIDRES/GRIDRES)/(double)nv;
192 >        rad = (RSCA/(double)GRIDRES)*(x1-x0);
193 >        rvp->peak =  vtot / ((2.*M_PI) * rad*rad);
194 >        rvp->crad = ANG2R(rad);
195 >        rvp->gx = (x0+x1)>>1;
196 >        rvp->gy = (y0+y1)>>1;
197 >        return(1);
198 > }
199  
200 <        ovec_from_pos(our_dir, i, j);
201 <        n = get_neighbors(neigh, NNEIGH, i, j);
202 <        while (n--) {
203 <                FVECT   their_dir;
204 <                double  max_ratio, rad_ok2;
205 <                                                /* check our value at neighbor */
206 <                ovec_from_pos(their_dir, neigh[n][0], neigh[n][1]);
207 <                max_ratio = MAXFRAC * dsf_grid[neigh[n][0]][neigh[n][1]].vsum
208 <                                / dsf_grid[i][j].vsum;
209 <                if (max_ratio >= 1)
210 <                        continue;
211 <                rad_ok2 = (DOT(their_dir,our_dir) - 1.)/log(max_ratio);
212 <                if (rad_ok2 >= currad*currad)
213 <                        continue;               /* value fraction OK */
214 <                currad = sqrt(rad_ok2);         /* else reduce lobe radius */
215 <                if (currad <= rad0)             /* limit how small we'll go */
216 <                        return(dsf_grid[i][j].crad);
200 > /* Recursive function to build radial basis function representation */
201 > static int
202 > build_rbfrep(RBFVAL **arp, int *np, int x0, int x1, int y0, int y1)
203 > {
204 >        int     xmid = (x0+x1)>>1;
205 >        int     ymid = (y0+y1)>>1;
206 >        int     branched[4];
207 >        int     nadded, nleaves;
208 >                                        /* need to make this a leaf? */
209 >        if (empty_region(x0, xmid, y0, ymid) ||
210 >                        empty_region(xmid, x1, y0, ymid) ||
211 >                        empty_region(x0, xmid, ymid, y1) ||
212 >                        empty_region(xmid, x1, ymid, y1))
213 >                return(0);
214 >                                        /* add children (branches+leaves) */
215 >        if ((branched[0] = build_rbfrep(arp, np, x0, xmid, y0, ymid)) < 0)
216 >                return(-1);
217 >        if ((branched[1] = build_rbfrep(arp, np, xmid, x1, y0, ymid)) < 0)
218 >                return(-1);
219 >        if ((branched[2] = build_rbfrep(arp, np, x0, xmid, ymid, y1)) < 0)
220 >                return(-1);
221 >        if ((branched[3] = build_rbfrep(arp, np, xmid, x1, ymid, y1)) < 0)
222 >                return(-1);
223 >        nadded = branched[0] + branched[1] + branched[2] + branched[3];
224 >        nleaves = !branched[0] + !branched[1] + !branched[2] + !branched[3];
225 >        if (!nleaves)                   /* nothing but branches? */
226 >                return(nadded);
227 >                                        /* combine 4 leaves into 1? */
228 >        if ((nleaves == 4) & (x1-x0 <= MAX_RAD) &&
229 >                        smooth_region(x0, x1, y0, y1))
230 >                return(0);
231 >                                        /* need more array space? */
232 >        if ((*np+nleaves-1)>>RBFALLOCB != (*np-1)>>RBFALLOCB) {
233 >                *arp = (RBFVAL *)realloc(*arp,
234 >                                sizeof(RBFVAL)*(*np+nleaves-1+(1<<RBFALLOCB)));
235 >                if (*arp == NULL)
236 >                        return(-1);
237          }
238 <        return(ANG2R(currad));                  /* encode selected radius */
238 >                                        /* create lobes for leaves */
239 >        if (!branched[0] && create_lobe(*arp+*np, x0, xmid, y0, ymid)) {
240 >                ++(*np); ++nadded;
241 >        }
242 >        if (!branched[1] && create_lobe(*arp+*np, xmid, x1, y0, ymid)) {
243 >                ++(*np); ++nadded;
244 >        }
245 >        if (!branched[2] && create_lobe(*arp+*np, x0, xmid, ymid, y1)) {
246 >                ++(*np); ++nadded;
247 >        }
248 >        if (!branched[3] && create_lobe(*arp+*np, xmid, x1, ymid, y1)) {
249 >                ++(*np); ++nadded;
250 >        }
251 >        return(nadded);
252   }
253  
254   /* Count up filled nodes and build RBF representation from current grid */
255   RBFNODE *
256 < make_rbfrep(void)
256 > make_rbfrep()
257   {
287        int     niter = 16;
288        double  lastVar, thisVar = 100.;
289        int     nn;
258          RBFNODE *newnode;
259 <        RBFVAL  *itera;
260 <        int     i, j;
293 <                                /* compute RBF radii */
294 <        compute_radii();
295 <                                /* coagulate lobes */
296 <        cull_values();
297 <        nn = 0;                 /* count selected bins */
298 <        for (i = 0; i < GRIDRES; i++)
299 <            for (j = 0; j < GRIDRES; j++)
300 <                nn += dsf_grid[i][j].nval;
259 >        RBFVAL  *rbfarr;
260 >        int     nn;
261                                  /* compute minimum BSDF */
262          comp_bsdf_min();
263 <                                /* allocate RBF array */
264 <        newnode = (RBFNODE *)malloc(sizeof(RBFNODE) + sizeof(RBFVAL)*(nn-1));
263 >                                /* create RBF node list */
264 >        rbfarr = NULL; nn = 0;
265 >        if (build_rbfrep(&rbfarr, &nn, 0, GRIDRES, 0, GRIDRES) <= 0)
266 >                goto memerr;
267 >                                /* (re)allocate RBF array */
268 >        newnode = (RBFNODE *)realloc(rbfarr,
269 >                        sizeof(RBFNODE) + sizeof(RBFVAL)*(nn-1));
270          if (newnode == NULL)
271                  goto memerr;
272 +                                /* copy computed lobes into RBF node */
273 +        memmove(newnode->rbfa, newnode, sizeof(RBFVAL)*nn);
274          newnode->ord = -1;
275          newnode->next = NULL;
276          newnode->ejl = NULL;
# Line 311 | Line 278 | make_rbfrep(void)
278          newnode->invec[0] = cos((M_PI/180.)*phi_in_deg)*newnode->invec[2];
279          newnode->invec[1] = sin((M_PI/180.)*phi_in_deg)*newnode->invec[2];
280          newnode->invec[2] = input_orient*sqrt(1. - newnode->invec[2]*newnode->invec[2]);
281 <        newnode->vtotal = 0;
281 >        newnode->vtotal = .0;
282          newnode->nrbf = nn;
283 <        nn = 0;                 /* fill RBF array */
284 <        for (i = 0; i < GRIDRES; i++)
285 <            for (j = 0; j < GRIDRES; j++)
319 <                if (dsf_grid[i][j].nval) {
320 <                        newnode->rbfa[nn].peak = dsf_grid[i][j].vsum;
321 <                        newnode->rbfa[nn].crad = adj_coded_radius(i, j);
322 <                        newnode->rbfa[nn].gx = i;
323 <                        newnode->rbfa[nn].gy = j;
324 <                        ++nn;
325 <                }
326 <                                /* iterate to improve interpolation accuracy */
327 <        itera = (RBFVAL *)malloc(sizeof(RBFVAL)*newnode->nrbf);
328 <        if (itera == NULL)
329 <                goto memerr;
330 <        memcpy(itera, newnode->rbfa, sizeof(RBFVAL)*newnode->nrbf);
331 <        do {
332 <                double  dsum = 0, dsum2 = 0;
333 <                nn = 0;
334 <                for (i = 0; i < GRIDRES; i++)
335 <                    for (j = 0; j < GRIDRES; j++)
336 <                        if (dsf_grid[i][j].nval) {
337 <                                FVECT   odir;
338 <                                double  corr;
339 <                                ovec_from_pos(odir, i, j);
340 <                                itera[nn++].peak *= corr =
341 <                                        dsf_grid[i][j].vsum /
342 <                                                eval_rbfrep(newnode, odir);
343 <                                dsum += 1. - corr;
344 <                                dsum2 += (1.-corr)*(1.-corr);
345 <                        }
346 <                memcpy(newnode->rbfa, itera, sizeof(RBFVAL)*newnode->nrbf);
347 <                lastVar = thisVar;
348 <                thisVar = dsum2/(double)nn;
283 >                                /* compute sum for normalization */
284 >        while (nn-- > 0)
285 >                newnode->vtotal += rbf_volume(&newnode->rbfa[nn]);
286   #ifdef DEBUG
287 <                fprintf(stderr, "Avg., RMS error: %.1f%%  %.1f%%\n",
351 <                                        100.*dsum/(double)nn,
352 <                                        100.*sqrt(thisVar));
353 < #endif
354 <        } while (--niter > 0 && lastVar-thisVar > 0.02*lastVar);
355 <
356 <        free(itera);
357 <        nn = 0;                 /* compute sum for normalization */
358 <        while (nn < newnode->nrbf)
359 <                newnode->vtotal += rbf_volume(&newnode->rbfa[nn++]);
360 < #ifdef DEBUG
287 >        fprintf(stderr, "Built RBF with %d lobes\n", newnode->nrbf);
288          fprintf(stderr, "Integrated DSF at (%.1f,%.1f) deg. is %.2f\n",
289                          get_theta180(newnode->invec), get_phi360(newnode->invec),
290                          newnode->vtotal);

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines