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.5 by greg, Thu Nov 8 23:32:30 2012 UTC vs.
Revision 2.24 by greg, Sat Mar 15 18:11:37 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) */
# Line 27 | Line 31 | 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 */
36  
37   #define pricerow(p,i)   ((p)->price + (i)*(p)->ncols)
# Line 119 | Line 124 | run_subprocess(void)
124                  if (pid < 0) {
125                          fprintf(stderr, "%s: cannot fork subprocess\n",
126                                          progname);
127 +                        await_children(nchild);
128                          exit(1);
129                  }
130                  ++nchild;                       /* subprocess started */
# Line 133 | Line 139 | run_subprocess(void)
139  
140   #endif  /* ! _WIN32 */
141  
142 + /* Compute normalized distribution scattering functions for comparison */
143 + static void
144 + compute_nDSFs(const RBFNODE *rbf0, const RBFNODE *rbf1)
145 + {
146 +        const double    nf0 = (GRIDRES*GRIDRES) / rbf0->vtotal;
147 +        const double    nf1 = (GRIDRES*GRIDRES) / rbf1->vtotal;
148 +        int             x, y;
149 +        FVECT           dv;
150 +
151 +        for (x = GRIDRES; x--; )
152 +            for (y = GRIDRES; y--; ) {
153 +                ovec_from_pos(dv, x, y);        /* cube root (brightness) */
154 +                dsf_grid[x][y].val[0] = pow(nf0*eval_rbfrep(rbf0, dv), .3333);
155 +                dsf_grid[x][y].val[1] = pow(nf1*eval_rbfrep(rbf1, dv), .3333);
156 +            }
157 + }      
158 +
159 + /* Compute neighborhood distance-squared (dissimilarity) */
160 + static double
161 + neighborhood_dist2(int x0, int y0, int x1, int y1)
162 + {
163 +        int     rad = GRIDRES>>5;
164 +        double  sum2 = 0.;
165 +        double  d;
166 +        int     p[4];
167 +        int     i, j;
168 +                                                /* check radius */
169 +        p[0] = x0; p[1] = y0; p[2] = x1; p[3] = y1;
170 +        for (i = 4; i--; ) {
171 +                if (p[i] < rad) rad = p[i];
172 +                if (GRIDRES-1-p[i] < rad) rad = GRIDRES-1-p[i];
173 +        }
174 +        for (i = -rad; i <= rad; i++)
175 +            for (j = -rad; j <= rad; j++) {
176 +                d = dsf_grid[x0+i][y0+j].val[0] -
177 +                        dsf_grid[x1+i][y1+j].val[1];
178 +                sum2 += d*d;
179 +            }
180 +        return(sum2 / (4*rad*(rad+1) + 1));
181 + }
182 +
183   /* Comparison routine needed for sorting price row */
184   static int
185   msrt_cmp(void *b, const void *p1, const void *p2)
186   {
187          PRICEMAT        *pm = (PRICEMAT *)b;
188 <        int             ri = ((const short *)p1 - pm->sord) / pm->ncols;
189 <        float           c1 = pricerow(pm,ri)[*(const short *)p1];
143 <        float           c2 = pricerow(pm,ri)[*(const short *)p2];
188 >        float           c1 = pm->prow[*(const short *)p1];
189 >        float           c2 = pm->prow[*(const short *)p2];
190  
191          if (c1 > c2) return(1);
192          if (c1 < c2) return(-1);
# Line 154 | Line 200 | price_routes(PRICEMAT *pm, const RBFNODE *from_rbf, co
200          FVECT   *vto = (FVECT *)malloc(sizeof(FVECT) * to_rbf->nrbf);
201          int     i, j;
202  
203 +        compute_nDSFs(from_rbf, to_rbf);
204          pm->nrows = from_rbf->nrbf;
205          pm->ncols = to_rbf->nrbf;
206          pm->price = (float *)malloc(sizeof(float) * pm->nrows*pm->ncols);
# Line 170 | Line 217 | price_routes(PRICEMAT *pm, const RBFNODE *from_rbf, co
217          for (i = from_rbf->nrbf; i--; ) {
218              const double        from_ang = R2ANG(from_rbf->rbfa[i].crad);
219              FVECT               vfrom;
220 +            short               *srow;
221              ovec_from_pos(vfrom, from_rbf->rbfa[i].gx, from_rbf->rbfa[i].gy);
222 +            pm->prow = pricerow(pm,i);
223 +            srow = psortrow(pm,i);
224              for (j = to_rbf->nrbf; j--; ) {
225 <                pricerow(pm,i)[j] = acos(DOT(vfrom, vto[j])) +
226 <                                fabs(R2ANG(to_rbf->rbfa[j].crad) - from_ang);
227 <                psortrow(pm,i)[j] = j;
225 >                double  d;                      /* quadratic cost function */
226 >                d = Acos(DOT(vfrom, vto[j]));
227 >                pm->prow[j] = d*d;
228 >                d = R2ANG(to_rbf->rbfa[j].crad) - from_ang;
229 >                pm->prow[j] += d*d;
230 >                                                /* neighborhood difference */
231 >                pm->prow[j] += NEIGH_FACT2 * neighborhood_dist2(
232 >                                from_rbf->rbfa[i].gx, from_rbf->rbfa[i].gy,
233 >                                to_rbf->rbfa[j].gx, to_rbf->rbfa[j].gy );
234 >                srow[j] = j;
235              }
236 <            qsort_r(psortrow(pm,i), pm->ncols, sizeof(short), pm, &msrt_cmp);
236 >            qsort_r(srow, pm->ncols, sizeof(short), pm, &msrt_cmp);
237          }
238          free(vto);
239   }
# Line 193 | Line 250 | free_routes(PRICEMAT *pm)
250   static double
251   min_cost(double amt2move, const double *avail, const PRICEMAT *pm, int s)
252   {
253 +        const short     *srow = psortrow(pm,s);
254 +        const float     *prow = pricerow(pm,s);
255          double          total_cost = 0;
256          int             j;
198
199        if (amt2move <= FTINY)                  /* pre-emptive check */
200                return(.0);
257                                                  /* move cheapest first */
258 <        for (j = 0; j < pm->ncols && amt2move > FTINY; j++) {
259 <                int     d = psortrow(pm,s)[j];
258 >        for (j = 0; (j < pm->ncols) & (amt2move > FTINY); j++) {
259 >                int     d = srow[j];
260                  double  amt = (amt2move < avail[d]) ? amt2move : avail[d];
261  
262 <                total_cost += amt * pricerow(pm,s)[d];
262 >                total_cost += amt * prow[d];
263                  amt2move -= amt;
264          }
265          return(total_cost);
266   }
267  
268 < /* Take a step in migration by choosing optimal bucket to transfer */
268 > typedef struct {
269 >        short   s, d;           /* source and destination */
270 >        float   dc;             /* discount to push inventory */
271 > } ROWSENT;              /* row sort entry */
272 >
273 > /* Compare entries by discounted moving price */
274 > static int
275 > rmovcmp(void *b, const void *p1, const void *p2)
276 > {
277 >        PRICEMAT        *pm = (PRICEMAT *)b;
278 >        const ROWSENT   *re1 = (const ROWSENT *)p1;
279 >        const ROWSENT   *re2 = (const ROWSENT *)p2;
280 >        double          price_diff;
281 >
282 >        if (re1->d < 0) return(re2->d >= 0);
283 >        if (re2->d < 0) return(-1);
284 >        price_diff = re1->dc*pricerow(pm,re1->s)[re1->d] -
285 >                        re2->dc*pricerow(pm,re2->s)[re2->d];
286 >        if (price_diff > 0) return(1);
287 >        if (price_diff < 0) return(-1);
288 >        return(0);
289 > }
290 >
291 > /* Take a step in migration by choosing reasonable bucket to transfer */
292   static double
293 < migration_step(MIGRATION *mig, double *src_rem, double *dst_rem, const PRICEMAT *pm)
293 > migration_step(MIGRATION *mig, double *src_rem, double *dst_rem, PRICEMAT *pm)
294   {
295 +        const int       max2check = 100;
296          const double    maxamt = 1./(double)pm->ncols;
297 <        const double    minamt = maxamt*5e-6;
297 >        const double    minamt = maxamt*1e-4;
298          double          *src_cost;
299 +        ROWSENT         *rord;
300          struct {
301                  int     s, d;   /* source and destination */
302 <                double  price;  /* price estimate per amount moved */
302 >                double  price;  /* cost per amount moved */
303                  double  amt;    /* amount we can move */
304          } cur, best;
305 <        int             i;
305 >        int             r2check, i, ri;
306 >        /*
307 >         * Check cheapest available routes only -- a higher adjusted
308 >         * destination price implies that another source is closer, so
309 >         * we can hold off considering more expensive options until
310 >         * some other (hopefully better) moves have been made.
311 >         * A discount based on source remaining is supposed to prioritize
312 >         * movement from large lobes, but it doesn't seem to do much,
313 >         * so we have it set to 1.0 at the moment.
314 >         */
315 > #define discount(qr)    1.0
316 >                                                /* most promising row order */
317 >        rord = (ROWSENT *)malloc(sizeof(ROWSENT)*pm->nrows);
318 >        if (rord == NULL)
319 >                goto memerr;
320 >        for (ri = pm->nrows; ri--; ) {
321 >            rord[ri].s = ri;
322 >            rord[ri].d = -1;
323 >            rord[ri].dc = 1.f;
324 >            if (src_rem[ri] <= minamt)          /* enough source material? */
325 >                    continue;
326 >            for (i = 0; i < pm->ncols; i++)
327 >                if (dst_rem[ rord[ri].d = psortrow(pm,ri)[i] ] > minamt)
328 >                        break;
329 >            if (i >= pm->ncols) {               /* moved all we can? */
330 >                free(rord);
331 >                return(.0);
332 >            }
333 >            rord[ri].dc = discount(src_rem[ri]);
334 >        }
335 >        if (pm->nrows > max2check)              /* sort if too many sources */
336 >                qsort_r(rord, pm->nrows, sizeof(ROWSENT), pm, &rmovcmp);
337                                                  /* allocate cost array */
338          src_cost = (double *)malloc(sizeof(double)*pm->nrows);
339 <        if (src_cost == NULL) {
340 <                fprintf(stderr, "%s: Out of memory in migration_step()\n",
229 <                                progname);
230 <                exit(1);
231 <        }
339 >        if (src_cost == NULL)
340 >                goto memerr;
341          for (i = pm->nrows; i--; )              /* starting costs for diff. */
342                  src_cost[i] = min_cost(src_rem[i], dst_rem, pm, i);
234
343                                                  /* find best source & dest. */
344          best.s = best.d = -1; best.price = FHUGE; best.amt = 0;
345 <        for (cur.s = pm->nrows; cur.s--; ) {
345 >        if ((r2check = pm->nrows) > max2check)
346 >                r2check = max2check;            /* put a limit on search */
347 >        for (ri = 0; ri < r2check; ri++) {      /* check each source row */
348              double      cost_others = 0;
349 <
350 <            if (src_rem[cur.s] <= minamt)
351 <                    continue;
352 <                                                /* examine cheapest dest. */
353 <            for (i = 0; i < pm->ncols; i++)
354 <                if (dst_rem[ cur.d = psortrow(pm,cur.s)[i] ] > minamt)
245 <                        break;
246 <            if (i >= pm->ncols)
247 <                break;
248 <            if ((cur.price = pricerow(pm,cur.s)[cur.d]) >= best.price)
249 <                continue;                       /* no point checking further */
349 >            cur.s = rord[ri].s;
350 >            if ((cur.d = rord[ri].d) < 0 ||
351 >                        rord[ri].dc*pricerow(pm,cur.s)[cur.d] >= best.price) {
352 >                if (pm->nrows > max2check) break;       /* sorted end */
353 >                continue;                       /* else skip this one */
354 >            }
355              cur.amt = (src_rem[cur.s] < dst_rem[cur.d]) ?
356                                  src_rem[cur.s] : dst_rem[cur.d];
357 <            if (cur.amt > maxamt) cur.amt = maxamt;
358 <            dst_rem[cur.d] -= cur.amt;          /* add up differential costs */
357 >                                                /* don't just leave smidgen */
358 >            if (cur.amt > maxamt*1.02) cur.amt = maxamt;
359 >            dst_rem[cur.d] -= cur.amt;          /* add up opportunity costs */
360              for (i = pm->nrows; i--; )
361                  if (i != cur.s)
362 <                        cost_others += min_cost(src_rem[i], dst_rem, pm, i)
362 >                    cost_others += min_cost(src_rem[i], dst_rem, pm, i)
363                                          - src_cost[i];
364              dst_rem[cur.d] += cur.amt;          /* undo trial move */
365 <            cur.price += cost_others/cur.amt;   /* adjust effective price */
365 >                                                /* discount effective price */
366 >            cur.price = ( pricerow(pm,cur.s)[cur.d] + cost_others/cur.amt ) *
367 >                                        rord[ri].dc;
368              if (cur.price < best.price)         /* are we better than best? */
369 <                    best = cur;
369 >                best = cur;
370          }
371 <        free(src_cost);                         /* finish up */
372 <
371 >        free(src_cost);                         /* clean up */
372 >        free(rord);
373          if ((best.s < 0) | (best.d < 0))        /* nothing left to move? */
374                  return(.0);
375                                                  /* else make the actual move */
# Line 269 | Line 377 | migration_step(MIGRATION *mig, double *src_rem, double
377          src_rem[best.s] -= best.amt;
378          dst_rem[best.d] -= best.amt;
379          return(best.amt);
380 + memerr:
381 +        fprintf(stderr, "%s: Out of memory in migration_step()\n", progname);
382 +        exit(1);
383 + #undef discount
384   }
385  
274 #ifdef DEBUG
275 static char *
276 thetaphi(const FVECT v)
277 {
278        static char     buf[128];
279        double          theta, phi;
280
281        theta = 180./M_PI*acos(v[2]);
282        phi = 180./M_PI*atan2(v[1],v[0]);
283        sprintf(buf, "(%.0f,%.0f)", theta, phi);
284
285        return(buf);
286 }
287 #endif
288
386   /* Compute and insert migration along directed edge (may fork child) */
387   static MIGRATION *
388   create_migration(RBFNODE *from_rbf, RBFNODE *to_rbf)
# Line 295 | Line 392 | create_migration(RBFNODE *from_rbf, RBFNODE *to_rbf)
392          MIGRATION       *newmig;
393          double          *src_rem, *dst_rem;
394          double          total_rem = 1., move_amt;
395 <        int             i;
395 >        int             i, j;
396                                                  /* check if exists already */
397          for (newmig = from_rbf->ejl; newmig != NULL;
398                          newmig = nextedge(from_rbf,newmig))
399                  if (newmig->rbfv[1] == to_rbf)
400                          return(NULL);
401                                                  /* else allocate */
402 + #ifdef DEBUG
403 +        fprintf(stderr, "Building path from (theta,phi) (%.1f,%.1f) ",
404 +                        get_theta180(from_rbf->invec),
405 +                        get_phi360(from_rbf->invec));
406 +        fprintf(stderr, "to (%.1f,%.1f) with %d x %d matrix\n",
407 +                        get_theta180(to_rbf->invec),
408 +                        get_phi360(to_rbf->invec),
409 +                        from_rbf->nrbf, to_rbf->nrbf);
410 + #endif
411          newmig = new_migration(from_rbf, to_rbf);
412          if (run_subprocess())
413                  return(newmig);                 /* child continues */
# Line 313 | Line 419 | create_migration(RBFNODE *from_rbf, RBFNODE *to_rbf)
419                                  progname);
420                  exit(1);
421          }
316 #ifdef DEBUG
317        fprintf(stderr, "Building path from (theta,phi) %s ",
318                        thetaphi(from_rbf->invec));
319        fprintf(stderr, "to %s with %d x %d matrix\n",
320                        thetaphi(to_rbf->invec),
321                        from_rbf->nrbf, to_rbf->nrbf);
322 #endif
422                                                  /* starting quantities */
423          memset(newmig->mtx, 0, sizeof(float)*from_rbf->nrbf*to_rbf->nrbf);
424          for (i = from_rbf->nrbf; i--; )
425                  src_rem[i] = rbf_volume(&from_rbf->rbfa[i]) / from_rbf->vtotal;
426 <        for (i = to_rbf->nrbf; i--; )
427 <                dst_rem[i] = rbf_volume(&to_rbf->rbfa[i]) / to_rbf->vtotal;
426 >        for (j = to_rbf->nrbf; j--; )
427 >                dst_rem[j] = rbf_volume(&to_rbf->rbfa[j]) / to_rbf->vtotal;
428 >
429          do {                                    /* move a bit at a time */
430                  move_amt = migration_step(newmig, src_rem, dst_rem, &pmtx);
431                  total_rem -= move_amt;
332 #ifdef DEBUG
333                if (!nchild)
334                        fprintf(stderr, "\r%.9f remaining...", total_rem);
335 #endif
432          } while ((total_rem > end_thresh) & (move_amt > 0));
433 < #ifdef DEBUG
338 <        if (!nchild) fputs("done.\n", stderr);
339 <        else fprintf(stderr, "finished with %.9f remaining\n", total_rem);
340 < #endif
433 >
434          for (i = from_rbf->nrbf; i--; ) {       /* normalize final matrix */
435 <            float       nf = rbf_volume(&from_rbf->rbfa[i]);
343 <            int         j;
435 >            double      nf = rbf_volume(&from_rbf->rbfa[i]);
436              if (nf <= FTINY) continue;
437              nf = from_rbf->vtotal / nf;
438              for (j = to_rbf->nrbf; j--; )
439 <                mtx_coef(newmig,i,j) *= nf;
439 >                mtx_coef(newmig,i,j) *= nf;     /* row now sums to 1.0 */
440          }
441          end_subprocess();                       /* exit here if subprocess */
442          free_routes(&pmtx);                     /* free working arrays */
# Line 379 | Line 471 | overlaps_tri(const RBFNODE *bv0, const RBFNODE *bv1, c
471          return(vother[im_rev] != NULL);
472   }
473  
474 < /* Find context hull vertex to complete triangle (oriented call) */
474 > /* Find convex hull vertex to complete triangle (oriented call) */
475   static RBFNODE *
476   find_chull_vert(const RBFNODE *rbf0, const RBFNODE *rbf1)
477   {
# Line 400 | Line 492 | find_chull_vert(const RBFNODE *rbf0, const RBFNODE *rb
492                  if (DOT(vp, vmid) <= FTINY)
493                          continue;               /* wrong orientation */
494                  area2 = .25*DOT(vp,vp);
495 <                VSUB(vp, rbf->invec, rbf0->invec);
495 >                VSUB(vp, rbf->invec, vmid);
496                  dprod = -DOT(vp, vejn);
497                  VSUM(vp, vp, vejn, dprod);      /* above guarantees non-zero */
498                  dprod = DOT(vp, vmid) / VLEN(vp);
# Line 456 | Line 548 | mesh_from_edge(MIGRATION *edge)
548                  }
549          }
550   }
551 +
552 + /* Add normal direction if missing */
553 + static void
554 + check_normal_incidence(void)
555 + {
556 +        static const FVECT      norm_vec = {.0, .0, 1.};
557 +        const int               saved_nprocs = nprocs;
558 +        RBFNODE                 *near_rbf, *mir_rbf, *rbf;
559 +        double                  bestd;
560 +        int                     n;
561 +
562 +
563 +        if (dsf_list == NULL)
564 +                return;                         /* XXX should be error? */
565 +        near_rbf = dsf_list;
566 +        bestd = input_orient*near_rbf->invec[2];
567 +        if (single_plane_incident) {            /* ordered plane incidence? */
568 +                if (bestd >= 1.-2.*FTINY)
569 +                        return;                 /* already have normal */
570 +        } else {
571 +                switch (inp_coverage) {
572 +                case INP_QUAD1:
573 +                case INP_QUAD2:
574 +                case INP_QUAD3:
575 +                case INP_QUAD4:
576 +                        break;                  /* quadrilateral symmetry? */
577 +                default:
578 +                        return;                 /* else we can interpolate */
579 +                }
580 +                for (rbf = near_rbf->next; rbf != NULL; rbf = rbf->next) {
581 +                        const double    d = input_orient*rbf->invec[2];
582 +                        if (d >= 1.-2.*FTINY)
583 +                                return;         /* seems we have normal */
584 +                        if (d > bestd) {
585 +                                near_rbf = rbf;
586 +                                bestd = d;
587 +                        }
588 +                }
589 +        }
590 +        if (mig_list != NULL) {                 /* need to be called first */
591 +                fprintf(stderr, "%s: Late call to check_normal_incidence()\n",
592 +                                progname);
593 +                exit(1);
594 +        }
595 + #ifdef DEBUG
596 +        fprintf(stderr, "Interpolating normal incidence by mirroring (%.1f,%.1f)\n",
597 +                        get_theta180(near_rbf->invec), get_phi360(near_rbf->invec));
598 + #endif
599 +                                                /* mirror nearest incidence */
600 +        n = sizeof(RBFNODE) + sizeof(RBFVAL)*(near_rbf->nrbf-1);
601 +        mir_rbf = (RBFNODE *)malloc(n);
602 +        if (mir_rbf == NULL)
603 +                goto memerr;
604 +        memcpy(mir_rbf, near_rbf, n);
605 +        mir_rbf->ord = near_rbf->ord - 1;       /* not used, I think */
606 +        mir_rbf->next = NULL;
607 +        mir_rbf->ejl = NULL;
608 +        rev_rbf_symmetry(mir_rbf, MIRROR_X|MIRROR_Y);
609 +        nprocs = 1;                             /* compute migration matrix */
610 +        if (create_migration(mir_rbf, near_rbf) == NULL)
611 +                exit(1);                        /* XXX should never happen! */
612 +                                                /* interpolate normal dist. */
613 +        rbf = e_advect_rbf(mig_list, norm_vec, 2*near_rbf->nrbf);
614 +        nprocs = saved_nprocs;                  /* final clean-up */
615 +        free(mir_rbf);
616 +        free(mig_list);
617 +        mig_list = near_rbf->ejl = NULL;
618 +        insert_dsf(rbf);                        /* insert interpolated normal */
619 +        return;
620 + memerr:
621 +        fprintf(stderr, "%s: Out of memory in check_normal_incidence()\n",
622 +                                progname);
623 +        exit(1);
624 + }
625          
626   /* Build our triangle mesh from recorded RBFs */
627   void
# Line 464 | Line 630 | build_mesh(void)
630          double          best2 = M_PI*M_PI;
631          RBFNODE         *shrt_edj[2];
632          RBFNODE         *rbf0, *rbf1;
633 +                                                /* add normal if needed */
634 +        check_normal_incidence();
635                                                  /* check if isotropic */
636          if (single_plane_incident) {
637                  for (rbf0 = dsf_list; rbf0 != NULL; rbf0 = rbf0->next)

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines