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

Comparing ray/src/cv/bsdfmesh.c (file contents):
Revision 2.15 by greg, Tue Feb 18 16:06:51 2014 UTC vs.
Revision 2.33 by greg, Fri Aug 22 05:38:44 2014 UTC

# Line 18 | Line 18 | static const char RCSid[] = "$Id$";
18   #include <string.h>
19   #include <math.h>
20   #include "bsdfrep.h"
21 +
22 + #ifndef NEIGH_FACT2
23 + #define NEIGH_FACT2     0.1     /* empirical neighborhood distance weight */
24 + #endif
25                                  /* number of processes to run */
26   int                     nprocs = 1;
27                                  /* number of children (-1 in child) */
28   static int              nchild = 0;
29  
30 < typedef struct {
31 <        int             nrows, ncols;   /* array size (matches migration) */
32 <        float           *price;         /* migration prices */
33 <        short           *sord;          /* sort for each row, low to high */
34 <        float           *prow;          /* current price row */
35 < } PRICEMAT;                     /* sorted pricing matrix */
30 > /* Compute average DSF value at the given radius from central vector */
31 > static double
32 > eval_DSFsurround(const RBFNODE *rbf, const FVECT outvec, const double rad)
33 > {
34 >        const int       ninc = 12;
35 >        const double    phinc = 2.*M_PI/ninc;
36 >        double          sum = 0;
37 >        int             n = 0;
38 >        FVECT           tvec;
39 >        int             i;
40 >                                                /* compute initial vector */
41 >        if (output_orient*outvec[2] >= 1.-FTINY) {
42 >                tvec[0] = tvec[2] = 0;
43 >                tvec[1] = 1;
44 >        } else {
45 >                tvec[0] = tvec[1] = 0;
46 >                tvec[2] = 1;
47 >        }
48 >        geodesic(tvec, outvec, tvec, rad, GEOD_RAD);
49 >                                                /* average surrounding DSF */
50 >        for (i = 0; i < ninc; i++) {
51 >                if (i) spinvector(tvec, tvec, outvec, phinc);
52 >                if (tvec[2] > 0 ^ output_orient > 0)
53 >                        continue;
54 >                sum += eval_rbfrep(rbf, tvec) * COSF(tvec[2]);
55 >                ++n;
56 >        }
57 >        if (n < 2)                              /* should never happen! */
58 >                return(sum);
59 >        return(sum/(double)n);
60 > }
61  
62 < #define pricerow(p,i)   ((p)->price + (i)*(p)->ncols)
63 < #define psortrow(p,i)   ((p)->sord + (i)*(p)->ncols)
62 > /* Estimate single-lobe radius for DSF at the given outgoing angle */
63 > static double
64 > est_DSFrad(const RBFNODE *rbf, const FVECT outvec)
65 > {
66 >        const double    rad_epsilon = 0.03;
67 >        const double    DSFtarget = 0.60653066 * eval_rbfrep(rbf,outvec) *
68 >                                                        COSF(outvec[2]);
69 >        double          inside_rad = rad_epsilon;
70 >        double          outside_rad = 0.5;
71 >        double          DSFinside = eval_DSFsurround(rbf, outvec, inside_rad);
72 >        double          DSFoutside = eval_DSFsurround(rbf, outvec, outside_rad);
73 > #define interp_rad      inside_rad + (outside_rad-inside_rad) * \
74 >                                (DSFtarget-DSFinside) / (DSFoutside-DSFinside)
75 >                                                /* Newton's method (sort of) */
76 >        do {
77 >                double  test_rad = interp_rad;
78 >                double  DSFtest;
79 >                if (test_rad >= outside_rad)
80 >                        return(test_rad);
81 >                if (test_rad <= inside_rad)
82 >                        return(test_rad*(test_rad>0));
83 >                DSFtest = eval_DSFsurround(rbf, outvec, test_rad);
84 >                if (DSFtest > DSFtarget) {
85 >                        inside_rad = test_rad;
86 >                        DSFinside = DSFtest;
87 >                } else {
88 >                        outside_rad = test_rad;
89 >                        DSFoutside = DSFtest;
90 >                }
91 >                if (DSFoutside >= DSFinside)
92 >                        return(test_rad);
93 >        } while (outside_rad-inside_rad > rad_epsilon);
94 >        return(interp_rad);
95 > #undef interp_rad
96 > }
97  
98 + /* Compute average BSDF peak from current DSF's */
99 + static void
100 + comp_bsdf_spec(void)
101 + {
102 +        double          peak_sum = 0;
103 +        double          rad_sum = 0;
104 +        int             n = 0;
105 +        RBFNODE         *rbf;
106 +        FVECT           sdv;
107 +
108 +        if (dsf_list == NULL) {
109 +                bsdf_spec_peak = 0;
110 +                bsdf_spec_rad = 0;
111 +                return;
112 +        }
113 +        for (rbf = dsf_list; rbf != NULL; rbf = rbf->next) {
114 +                sdv[0] = -rbf->invec[0];
115 +                sdv[1] = -rbf->invec[1];
116 +                sdv[2] = rbf->invec[2]*(2*(input_orient==output_orient) - 1);
117 +                peak_sum += eval_rbfrep(rbf, sdv);
118 +                rad_sum += est_DSFrad(rbf, sdv);
119 +                ++n;
120 +        }
121 +        bsdf_spec_peak = peak_sum/(double)n;
122 +        bsdf_spec_rad = rad_sum/(double)n;
123 + }
124 +
125   /* Create a new migration holder (sharing memory for multiprocessing) */
126   static MIGRATION *
127   new_migration(RBFNODE *from_rbf, RBFNODE *to_rbf)
# Line 135 | Line 224 | run_subprocess(void)
224  
225   #endif  /* ! _WIN32 */
226  
227 < /* Comparison routine needed for sorting price row */
139 < static int
140 < msrt_cmp(void *b, const void *p1, const void *p2)
141 < {
142 <        PRICEMAT        *pm = (PRICEMAT *)b;
143 <        float           c1 = pm->prow[*(const short *)p1];
144 <        float           c2 = pm->prow[*(const short *)p2];
145 <
146 <        if (c1 > c2) return(1);
147 <        if (c1 < c2) return(-1);
148 <        return(0);
149 < }
150 <
151 < /* Compute (and allocate) migration price matrix for optimization */
227 > /* Compute normalized distribution scattering functions for comparison */
228   static void
229 < price_routes(PRICEMAT *pm, const RBFNODE *from_rbf, const RBFNODE *to_rbf)
229 > compute_nDSFs(const RBFNODE *rbf0, const RBFNODE *rbf1)
230   {
231 <        FVECT   *vto = (FVECT *)malloc(sizeof(FVECT) * to_rbf->nrbf);
232 <        int     i, j;
231 >        const double    nf0 = (GRIDRES*GRIDRES) / rbf0->vtotal;
232 >        const double    nf1 = (GRIDRES*GRIDRES) / rbf1->vtotal;
233 >        int             x, y;
234 >        FVECT           dv;
235  
236 <        pm->nrows = from_rbf->nrbf;
237 <        pm->ncols = to_rbf->nrbf;
238 <        pm->price = (float *)malloc(sizeof(float) * pm->nrows*pm->ncols);
239 <        pm->sord = (short *)malloc(sizeof(short) * pm->nrows*pm->ncols);
240 <        
163 <        if ((pm->price == NULL) | (pm->sord == NULL) | (vto == NULL)) {
164 <                fprintf(stderr, "%s: Out of memory in migration_costs()\n",
165 <                                progname);
166 <                exit(1);
167 <        }
168 <        for (j = to_rbf->nrbf; j--; )           /* save repetitive ops. */
169 <                ovec_from_pos(vto[j], to_rbf->rbfa[j].gx, to_rbf->rbfa[j].gy);
170 <
171 <        for (i = from_rbf->nrbf; i--; ) {
172 <            const double        from_ang = R2ANG(from_rbf->rbfa[i].crad);
173 <            FVECT               vfrom;
174 <            short               *srow;
175 <            ovec_from_pos(vfrom, from_rbf->rbfa[i].gx, from_rbf->rbfa[i].gy);
176 <            pm->prow = pricerow(pm,i);
177 <            srow = psortrow(pm,i);
178 <            for (j = to_rbf->nrbf; j--; ) {
179 <                double          d;              /* quadratic cost function */
180 <                d = DOT(vfrom, vto[j]);
181 <                d = (d >= 1.) ? .0 : acos(d);
182 <                pm->prow[j] = d*d;
183 <                d = R2ANG(to_rbf->rbfa[j].crad) - from_ang;
184 <                pm->prow[j] += d*d;    
185 <                srow[j] = j;
236 >        for (x = GRIDRES; x--; )
237 >            for (y = GRIDRES; y--; ) {
238 >                ovec_from_pos(dv, x, y);        /* cube root (brightness) */
239 >                dsf_grid[x][y].val[0] = pow(nf0*eval_rbfrep(rbf0, dv), .3333);
240 >                dsf_grid[x][y].val[1] = pow(nf1*eval_rbfrep(rbf1, dv), .3333);
241              }
242 <            qsort_r(srow, pm->ncols, sizeof(short), pm, &msrt_cmp);
188 <        }
189 <        free(vto);
190 < }
242 > }      
243  
244 < /* Free price matrix */
193 < static void
194 < free_routes(PRICEMAT *pm)
195 < {
196 <        free(pm->price); pm->price = NULL;
197 <        free(pm->sord); pm->sord = NULL;
198 < }
199 <
200 < /* Compute minimum (optimistic) cost for moving the given source material */
244 > /* Compute neighborhood distance-squared (dissimilarity) */
245   static double
246 < min_cost(double amt2move, const double *avail, const PRICEMAT *pm, int s)
246 > neighborhood_dist2(int x0, int y0, int x1, int y1)
247   {
248 <        const short     *srow = psortrow(pm,s);
249 <        const float     *prow = pricerow(pm,s);
250 <        double          total_cost = 0;
251 <        int             j;
252 <                                                /* move cheapest first */
253 <        for (j = 0; (j < pm->ncols) & (amt2move > FTINY); j++) {
254 <                int     d = srow[j];
255 <                double  amt = (amt2move < avail[d]) ? amt2move : avail[d];
256 <
257 <                total_cost += amt * prow[d];
214 <                amt2move -= amt;
248 >        int     rad = GRIDRES>>5;
249 >        double  sum2 = 0.;
250 >        double  d;
251 >        int     p[4];
252 >        int     i, j;
253 >                                                /* check radius */
254 >        p[0] = x0; p[1] = y0; p[2] = x1; p[3] = y1;
255 >        for (i = 4; i--; ) {
256 >                if (p[i] < rad) rad = p[i];
257 >                if (GRIDRES-1-p[i] < rad) rad = GRIDRES-1-p[i];
258          }
259 <        return(total_cost);
259 >        for (i = -rad; i <= rad; i++)
260 >            for (j = -rad; j <= rad; j++) {
261 >                d = dsf_grid[x0+i][y0+j].val[0] -
262 >                        dsf_grid[x1+i][y1+j].val[1];
263 >                sum2 += d*d;
264 >            }
265 >        return(sum2 / (4*rad*(rad+1) + 1));
266   }
267  
268 < /* Compare entries by moving price */
269 < static int
270 < rmovcmp(void *b, const void *p1, const void *p2)
268 > /* Compute distance between two RBF lobes */
269 > double
270 > lobe_distance(RBFVAL *rbf1, RBFVAL *rbf2)
271   {
272 <        PRICEMAT        *pm = (PRICEMAT *)b;
273 <        const short     *ij1 = (const short *)p1;
274 <        const short     *ij2 = (const short *)p2;
275 <        float           price_diff;
276 <
277 <        if (ij1[1] < 0) return(ij2[1] >= 0);
278 <        if (ij2[1] < 0) return(-1);
279 <        price_diff = pricerow(pm,ij1[0])[ij1[1]] - pricerow(pm,ij2[0])[ij2[1]];
280 <        if (price_diff > 0) return(1);
281 <        if (price_diff < 0) return(-1);
282 <        return(0);
272 >        FVECT   vfrom, vto;
273 >        double  d, res;
274 >                                        /* quadratic cost function */
275 >        ovec_from_pos(vfrom, rbf1->gx, rbf1->gy);
276 >        ovec_from_pos(vto, rbf2->gx, rbf2->gy);
277 >        d = Acos(DOT(vfrom, vto));
278 >        res = d*d;
279 >        d = R2ANG(rbf2->crad) - R2ANG(rbf1->crad);
280 >        res += d*d;
281 >                                        /* neighborhood difference */
282 >        res += NEIGH_FACT2 * neighborhood_dist2( rbf1->gx, rbf1->gy,
283 >                                                rbf2->gx, rbf2->gy );
284 >        return(res);
285   }
286  
236 /* Take a step in migration by choosing reasonable bucket to transfer */
237 static double
238 migration_step(MIGRATION *mig, double *src_rem, double *dst_rem, PRICEMAT *pm)
239 {
240        const int       max2check = 100;
241        const double    maxamt = 1./(double)pm->ncols;
242        const double    minamt = maxamt*1e-4;
243        double          *src_cost;
244        short           (*rord)[2];
245        struct {
246                int     s, d;   /* source and destination */
247                double  price;  /* price estimate per amount moved */
248                double  amt;    /* amount we can move */
249        } cur, best;
250        int             r2check, i, ri;
251        /*
252         * Check cheapest available routes only -- a higher adjusted
253         * destination price implies that another source is closer, so
254         * we can hold off considering more expensive options until
255         * some other (hopefully better) moves have been made.
256         */
257                                                /* most promising row order */
258        rord = (short (*)[2])malloc(sizeof(short)*2*pm->nrows);
259        if (rord == NULL)
260                goto memerr;
261        for (ri = pm->nrows; ri--; ) {
262            rord[ri][0] = ri;
263            rord[ri][1] = -1;
264            if (src_rem[ri] <= minamt)          /* enough source material? */
265                    continue;
266            for (i = 0; i < pm->ncols; i++)
267                if (dst_rem[ rord[ri][1] = psortrow(pm,ri)[i] ] > minamt)
268                        break;
269            if (i >= pm->ncols) {               /* moved all we can? */
270                free(rord);
271                return(.0);
272            }
273        }
274        if (pm->nrows > max2check)              /* sort if too many sources */
275                qsort_r(rord, pm->nrows, sizeof(short)*2, pm, &rmovcmp);
276                                                /* allocate cost array */
277        src_cost = (double *)malloc(sizeof(double)*pm->nrows);
278        if (src_cost == NULL)
279                goto memerr;
280        for (i = pm->nrows; i--; )              /* starting costs for diff. */
281                src_cost[i] = min_cost(src_rem[i], dst_rem, pm, i);
282                                                /* find best source & dest. */
283        best.s = best.d = -1; best.price = FHUGE; best.amt = 0;
284        if ((r2check = pm->nrows) > max2check)
285                r2check = max2check;            /* put a limit on search */
286        for (ri = 0; ri < r2check; ri++) {      /* check each source row */
287            double      cost_others = 0;
288            cur.s = rord[ri][0];
289            if ((cur.d = rord[ri][1]) < 0 ||
290                        (cur.price = pricerow(pm,cur.s)[cur.d]) >= best.price) {
291                if (pm->nrows > max2check) break;       /* sorted end */
292                continue;                       /* else skip this one */
293            }
294            cur.amt = (src_rem[cur.s] < dst_rem[cur.d]) ?
295                                src_rem[cur.s] : dst_rem[cur.d];
296                                                /* don't just leave smidgen */
297            if (cur.amt > maxamt*1.02) cur.amt = maxamt;
298            dst_rem[cur.d] -= cur.amt;          /* add up opportunity costs */
299            for (i = pm->nrows; i--; )
300                if (i != cur.s)
301                    cost_others += min_cost(src_rem[i], dst_rem, pm, i)
302                                        - src_cost[i];
303            dst_rem[cur.d] += cur.amt;          /* undo trial move */
304            cur.price += cost_others/cur.amt;   /* adjust effective price */
305            if (cur.price < best.price)         /* are we better than best? */
306                best = cur;
307        }
308        free(src_cost);                         /* clean up */
309        free(rord);
310        if ((best.s < 0) | (best.d < 0))        /* nothing left to move? */
311                return(.0);
312                                                /* else make the actual move */
313        mtx_coef(mig,best.s,best.d) += best.amt;
314        src_rem[best.s] -= best.amt;
315        dst_rem[best.d] -= best.amt;
316        return(best.amt);
317 memerr:
318        fprintf(stderr, "%s: Out of memory in migration_step()\n", progname);
319        exit(1);
320 }
287  
288   /* Compute and insert migration along directed edge (may fork child) */
289   static MIGRATION *
290   create_migration(RBFNODE *from_rbf, RBFNODE *to_rbf)
291   {
326        const double    end_thresh = 5e-6;
327        PRICEMAT        pmtx;
292          MIGRATION       *newmig;
329        double          *src_rem, *dst_rem;
330        double          total_rem = 1., move_amt;
293          int             i, j;
294                                                  /* check if exists already */
295          for (newmig = from_rbf->ejl; newmig != NULL;
# Line 347 | Line 309 | create_migration(RBFNODE *from_rbf, RBFNODE *to_rbf)
309          newmig = new_migration(from_rbf, to_rbf);
310          if (run_subprocess())
311                  return(newmig);                 /* child continues */
350        price_routes(&pmtx, from_rbf, to_rbf);
351        src_rem = (double *)malloc(sizeof(double)*from_rbf->nrbf);
352        dst_rem = (double *)malloc(sizeof(double)*to_rbf->nrbf);
353        if ((src_rem == NULL) | (dst_rem == NULL)) {
354                fprintf(stderr, "%s: Out of memory in create_migration()\n",
355                                progname);
356                exit(1);
357        }
358                                                /* starting quantities */
359        memset(newmig->mtx, 0, sizeof(float)*from_rbf->nrbf*to_rbf->nrbf);
360        for (i = from_rbf->nrbf; i--; )
361                src_rem[i] = rbf_volume(&from_rbf->rbfa[i]) / from_rbf->vtotal;
362        for (j = to_rbf->nrbf; j--; )
363                dst_rem[j] = rbf_volume(&to_rbf->rbfa[j]) / to_rbf->vtotal;
312  
313 <        do {                                    /* move a bit at a time */
314 <                move_amt = migration_step(newmig, src_rem, dst_rem, &pmtx);
315 <                total_rem -= move_amt;
368 <        } while ((total_rem > end_thresh) & (move_amt > 0));
313 >                                                /* compute transport plan */
314 >        compute_nDSFs(from_rbf, to_rbf);
315 >        plan_transport(newmig);
316  
317          for (i = from_rbf->nrbf; i--; ) {       /* normalize final matrix */
318              double      nf = rbf_volume(&from_rbf->rbfa[i]);
# Line 375 | Line 322 | create_migration(RBFNODE *from_rbf, RBFNODE *to_rbf)
322                  mtx_coef(newmig,i,j) *= nf;     /* row now sums to 1.0 */
323          }
324          end_subprocess();                       /* exit here if subprocess */
378        free_routes(&pmtx);                     /* free working arrays */
379        free(src_rem);
380        free(dst_rem);
325          return(newmig);
326   }
327  
# Line 467 | Line 411 | mesh_from_edge(MIGRATION *edge)
411                                  ej1 = create_migration(tvert[0], edge->rbfv[1]);
412                          mesh_from_edge(ej0);
413                          mesh_from_edge(ej1);
414 +                        return;
415                  }
416 <        } else if (tvert[1] == NULL) {          /* grow mesh on left */
416 >        }
417 >        if (tvert[1] == NULL) {                 /* grow mesh on left */
418                  tvert[1] = find_chull_vert(edge->rbfv[1], edge->rbfv[0]);
419                  if (tvert[1] != NULL) {
420                          if (tvert[1]->ord > edge->rbfv[0]->ord)
# Line 489 | Line 435 | mesh_from_edge(MIGRATION *edge)
435   static void
436   check_normal_incidence(void)
437   {
438 <        const int       saved_nprocs = nprocs;
439 <        RBFNODE         *near_rbf, *mir_rbf, *rbf;
440 <        double          bestd;
441 <        int             n, i, j;
438 >        static FVECT            norm_vec = {.0, .0, 1.};
439 >        const int               saved_nprocs = nprocs;
440 >        RBFNODE                 *near_rbf, *mir_rbf, *rbf;
441 >        double                  bestd;
442 >        int                     n;
443  
444          if (dsf_list == NULL)
445                  return;                         /* XXX should be error? */
# Line 538 | Line 485 | check_normal_incidence(void)
485          memcpy(mir_rbf, near_rbf, n);
486          mir_rbf->ord = near_rbf->ord - 1;       /* not used, I think */
487          mir_rbf->next = NULL;
488 +        mir_rbf->ejl = NULL;
489          rev_rbf_symmetry(mir_rbf, MIRROR_X|MIRROR_Y);
490          nprocs = 1;                             /* compute migration matrix */
491 <        if (mig_list != create_migration(mir_rbf, near_rbf))
491 >        if (create_migration(mir_rbf, near_rbf) == NULL)
492                  exit(1);                        /* XXX should never happen! */
493 <        n = 0;                                  /* count migrating particles */
494 <        for (i = 0; i < mtx_nrows(mig_list); i++)
547 <            for (j = 0; j < mtx_ncols(mig_list); j++)
548 <                n += (mtx_coef(mig_list,i,j) > FTINY);
549 <        rbf = (RBFNODE *)malloc(sizeof(RBFNODE) + sizeof(RBFVAL)*(n-1));
550 <        if (rbf == NULL)
551 <                goto memerr;
552 <        rbf->next = NULL; rbf->ejl = NULL;
553 <        rbf->invec[0] = rbf->invec[1] = 0; rbf->invec[2] = 1.;
554 <        rbf->nrbf = n;
555 <        rbf->vtotal = .5 + .5*mig_list->rbfv[1]->vtotal/mig_list->rbfv[0]->vtotal;
556 <        n = 0;                                  /* advect RBF lobes halfway */
557 <        for (i = 0; i < mtx_nrows(mig_list); i++) {
558 <            const RBFVAL        *rbf0i = &mig_list->rbfv[0]->rbfa[i];
559 <            const float         peak0 = rbf0i->peak;
560 <            const double        rad0 = R2ANG(rbf0i->crad);
561 <            FVECT               v0;
562 <            float               mv;
563 <            ovec_from_pos(v0, rbf0i->gx, rbf0i->gy);
564 <            for (j = 0; j < mtx_ncols(mig_list); j++)
565 <                if ((mv = mtx_coef(mig_list,i,j)) > FTINY) {
566 <                        const RBFVAL    *rbf1j = &mig_list->rbfv[1]->rbfa[j];
567 <                        double          rad2;
568 <                        FVECT           v;
569 <                        int             pos[2];
570 <                        rad2 = R2ANG(rbf1j->crad);
571 <                        rad2 = .5*(rad0*rad0 + rad2*rad2);
572 <                        rbf->rbfa[n].peak = peak0 * mv * rbf->vtotal *
573 <                                                rad0*rad0/rad2;
574 <                        rbf->rbfa[n].crad = ANG2R(sqrt(rad2));
575 <                        ovec_from_pos(v, rbf1j->gx, rbf1j->gy);
576 <                        geodesic(v, v0, v, .5, GEOD_REL);
577 <                        pos_from_vec(pos, v);
578 <                        rbf->rbfa[n].gx = pos[0];
579 <                        rbf->rbfa[n].gy = pos[1];
580 <                        ++n;
581 <                }
582 <        }
583 <        rbf->vtotal *= mig_list->rbfv[0]->vtotal;
493 >        norm_vec[2] = input_orient;             /* interpolate normal dist. */
494 >        rbf = e_advect_rbf(mig_list, norm_vec, 0);
495          nprocs = saved_nprocs;                  /* final clean-up */
496          free(mir_rbf);
497          free(mig_list);
# Line 600 | Line 511 | build_mesh(void)
511          double          best2 = M_PI*M_PI;
512          RBFNODE         *shrt_edj[2];
513          RBFNODE         *rbf0, *rbf1;
514 +                                                /* average specular peak */
515 +        comp_bsdf_spec();
516                                                  /* add normal if needed */
517          check_normal_incidence();
518                                                  /* check if isotropic */

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines