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.2 by greg, Sat Oct 20 07:02:00 2012 UTC vs.
Revision 2.18 by greg, Thu Mar 6 00:40:37 2014 UTC

# Line 23 | Line 23 | int                    nprocs = 1;
23                                  /* number of children (-1 in child) */
24   static int              nchild = 0;
25  
26 + typedef struct {
27 +        int             nrows, ncols;   /* array size (matches migration) */
28 +        float           *price;         /* migration prices */
29 +        short           *sord;          /* sort for each row, low to high */
30 +        float           *prow;          /* current price row */
31 + } PRICEMAT;                     /* sorted pricing matrix */
32 +
33 + #define pricerow(p,i)   ((p)->price + (i)*(p)->ncols)
34 + #define psortrow(p,i)   ((p)->sord + (i)*(p)->ncols)
35 +
36   /* Create a new migration holder (sharing memory for multiprocessing) */
37   static MIGRATION *
38   new_migration(RBFNODE *from_rbf, RBFNODE *to_rbf)
# Line 110 | Line 120 | run_subprocess(void)
120                  if (pid < 0) {
121                          fprintf(stderr, "%s: cannot fork subprocess\n",
122                                          progname);
123 +                        await_children(nchild);
124                          exit(1);
125                  }
126                  ++nchild;                       /* subprocess started */
# Line 124 | Line 135 | run_subprocess(void)
135  
136   #endif  /* ! _WIN32 */
137  
138 + /* 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 */
152 < static float *
153 < price_routes(const RBFNODE *from_rbf, const RBFNODE *to_rbf)
152 > static void
153 > price_routes(PRICEMAT *pm, const RBFNODE *from_rbf, const RBFNODE *to_rbf)
154   {
131        float   *pmtx = (float *)malloc(sizeof(float) *
132                                        from_rbf->nrbf * to_rbf->nrbf);
155          FVECT   *vto = (FVECT *)malloc(sizeof(FVECT) * to_rbf->nrbf);
156          int     i, j;
157  
158 <        if ((pmtx == NULL) | (vto == NULL)) {
158 >        pm->nrows = from_rbf->nrbf;
159 >        pm->ncols = to_rbf->nrbf;
160 >        pm->price = (float *)malloc(sizeof(float) * pm->nrows*pm->ncols);
161 >        pm->sord = (short *)malloc(sizeof(short) * pm->nrows*pm->ncols);
162 >        
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);
# Line 144 | Line 171 | price_routes(const RBFNODE *from_rbf, const RBFNODE *t
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 <            for (j = to_rbf->nrbf; j--; )
177 <                pmtx[i*to_rbf->nrbf + j] = acos(DOT(vfrom, vto[j])) +
178 <                                fabs(R2ANG(to_rbf->rbfa[j].crad) - from_ang);
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 = Acos(DOT(vfrom, vto[j]));
181 >                pm->prow[j] = d*d;
182 >                d = R2ANG(to_rbf->rbfa[j].crad) - from_ang;
183 >                pm->prow[j] += d*d;    
184 >                srow[j] = j;
185 >            }
186 >            qsort_r(srow, pm->ncols, sizeof(short), pm, &msrt_cmp);
187          }
188          free(vto);
153        return(pmtx);
189   }
190  
191 < /* Comparison routine needed for sorting price row */
192 < static const float      *price_arr;
193 < static int
159 < msrt_cmp(const void *p1, const void *p2)
191 > /* Free price matrix */
192 > static void
193 > free_routes(PRICEMAT *pm)
194   {
195 <        float   c1 = price_arr[*(const int *)p1];
196 <        float   c2 = price_arr[*(const int *)p2];
163 <
164 <        if (c1 > c2) return(1);
165 <        if (c1 < c2) return(-1);
166 <        return(0);
195 >        free(pm->price); pm->price = NULL;
196 >        free(pm->sord); pm->sord = NULL;
197   }
198  
199   /* Compute minimum (optimistic) cost for moving the given source material */
200   static double
201 < min_cost(double amt2move, const double *avail, const float *price, int n)
201 > min_cost(double amt2move, const double *avail, const PRICEMAT *pm, int s)
202   {
203 <        static int      *price_sort = NULL;
204 <        static int      n_alloc = 0;
203 >        const short     *srow = psortrow(pm,s);
204 >        const float     *prow = pricerow(pm,s);
205          double          total_cost = 0;
206 <        int             i;
177 <
178 <        if (amt2move <= FTINY)                  /* pre-emptive check */
179 <                return(0.);
180 <        if (n > n_alloc) {                      /* (re)allocate sort array */
181 <                if (n_alloc) free(price_sort);
182 <                price_sort = (int *)malloc(sizeof(int)*n);
183 <                if (price_sort == NULL) {
184 <                        fprintf(stderr, "%s: Out of memory in min_cost()\n",
185 <                                        progname);
186 <                        exit(1);
187 <                }
188 <                n_alloc = n;
189 <        }
190 <        for (i = n; i--; )
191 <                price_sort[i] = i;
192 <        price_arr = price;
193 <        qsort(price_sort, n, sizeof(int), &msrt_cmp);
206 >        int             j;
207                                                  /* move cheapest first */
208 <        for (i = 0; i < n && amt2move > FTINY; i++) {
209 <                int     d = price_sort[i];
208 >        for (j = 0; (j < pm->ncols) & (amt2move > FTINY); j++) {
209 >                int     d = srow[j];
210                  double  amt = (amt2move < avail[d]) ? amt2move : avail[d];
211  
212 <                total_cost += amt * price[d];
212 >                total_cost += amt * prow[d];
213                  amt2move -= amt;
214          }
215          return(total_cost);
216   }
217  
218 < /* Take a step in migration by choosing optimal bucket to transfer */
218 > typedef struct {
219 >        short   s, d;           /* source and destination */
220 >        float   dc;             /* discount to push inventory */
221 > } ROWSENT;              /* row sort entry */
222 >
223 > /* Compare entries by discounted moving price */
224 > static int
225 > rmovcmp(void *b, const void *p1, const void *p2)
226 > {
227 >        PRICEMAT        *pm = (PRICEMAT *)b;
228 >        const ROWSENT   *re1 = (const ROWSENT *)p1;
229 >        const ROWSENT   *re2 = (const ROWSENT *)p2;
230 >        double          price_diff;
231 >
232 >        if (re1->d < 0) return(re2->d >= 0);
233 >        if (re2->d < 0) return(-1);
234 >        price_diff = re1->dc*pricerow(pm,re1->s)[re1->d] -
235 >                        re2->dc*pricerow(pm,re2->s)[re2->d];
236 >        if (price_diff > 0) return(1);
237 >        if (price_diff < 0) return(-1);
238 >        return(0);
239 > }
240 >
241 > /* Take a step in migration by choosing reasonable bucket to transfer */
242   static double
243 < migration_step(MIGRATION *mig, double *src_rem, double *dst_rem, const float *pmtx)
243 > migration_step(MIGRATION *mig, double *src_rem, double *dst_rem, PRICEMAT *pm)
244   {
245 <        const double    maxamt = .1;
246 <        const double    minamt = maxamt*5e-6;
247 <        static double   *src_cost = NULL;
248 <        static int      n_alloc = 0;
245 >        const int       max2check = 100;
246 >        const double    maxamt = 1./(double)pm->ncols;
247 >        const double    minamt = maxamt*1e-4;
248 >        double          *src_cost;
249 >        ROWSENT         *rord;
250          struct {
251                  int     s, d;   /* source and destination */
252 <                double  price;  /* price estimate per amount moved */
252 >                double  price;  /* cost per amount moved */
253                  double  amt;    /* amount we can move */
254          } cur, best;
255 <        int             i;
256 <
257 <        if (mtx_nrows(mig) > n_alloc) {         /* allocate cost array */
258 <                if (n_alloc)
259 <                        free(src_cost);
260 <                src_cost = (double *)malloc(sizeof(double)*mtx_nrows(mig));
261 <                if (src_cost == NULL) {
262 <                        fprintf(stderr, "%s: Out of memory in migration_step()\n",
263 <                                        progname);
264 <                        exit(1);
265 <                }
266 <                n_alloc = mtx_nrows(mig);
255 >        int             r2check, i, ri;
256 >        /*
257 >         * Check cheapest available routes only -- a higher adjusted
258 >         * destination price implies that another source is closer, so
259 >         * we can hold off considering more expensive options until
260 >         * some other (hopefully better) moves have been made.
261 >         * A discount based on source remaining is supposed to prioritize
262 >         * movement from large lobes, but it doesn't seem to do much,
263 >         * so we have it set to 1.0 at the moment.
264 >         */
265 > #define discount(qr)    1.0
266 >                                                /* most promising row order */
267 >        rord = (ROWSENT *)malloc(sizeof(ROWSENT)*pm->nrows);
268 >        if (rord == NULL)
269 >                goto memerr;
270 >        for (ri = pm->nrows; ri--; ) {
271 >            rord[ri].s = ri;
272 >            rord[ri].d = -1;
273 >            rord[ri].dc = 1.f;
274 >            if (src_rem[ri] <= minamt)          /* enough source material? */
275 >                    continue;
276 >            for (i = 0; i < pm->ncols; i++)
277 >                if (dst_rem[ rord[ri].d = psortrow(pm,ri)[i] ] > minamt)
278 >                        break;
279 >            if (i >= pm->ncols) {               /* moved all we can? */
280 >                free(rord);
281 >                return(.0);
282 >            }
283 >            rord[ri].dc = discount(src_rem[ri]);
284          }
285 <        for (i = mtx_nrows(mig); i--; )         /* starting costs for diff. */
286 <                src_cost[i] = min_cost(src_rem[i], dst_rem,
287 <                                        pmtx+i*mtx_ncols(mig), mtx_ncols(mig));
288 <
285 >        if (pm->nrows > max2check)              /* sort if too many sources */
286 >                qsort_r(rord, pm->nrows, sizeof(ROWSENT), pm, &rmovcmp);
287 >                                                /* allocate cost array */
288 >        src_cost = (double *)malloc(sizeof(double)*pm->nrows);
289 >        if (src_cost == NULL)
290 >                goto memerr;
291 >        for (i = pm->nrows; i--; )              /* starting costs for diff. */
292 >                src_cost[i] = min_cost(src_rem[i], dst_rem, pm, i);
293                                                  /* find best source & dest. */
294          best.s = best.d = -1; best.price = FHUGE; best.amt = 0;
295 <        for (cur.s = mtx_nrows(mig); cur.s--; ) {
296 <            const float *price = pmtx + cur.s*mtx_ncols(mig);
295 >        if ((r2check = pm->nrows) > max2check)
296 >                r2check = max2check;            /* put a limit on search */
297 >        for (ri = 0; ri < r2check; ri++) {      /* check each source row */
298              double      cost_others = 0;
299 <            if (src_rem[cur.s] <= minamt)
300 <                    continue;
301 <            cur.d = -1;                         /* examine cheapest dest. */
302 <            for (i = mtx_ncols(mig); i--; )
303 <                if (dst_rem[i] > minamt &&
304 <                                (cur.d < 0 || price[i] < price[cur.d]))
246 <                        cur.d = i;
247 <            if (cur.d < 0)
248 <                    return(.0);
249 <            if ((cur.price = price[cur.d]) >= best.price)
250 <                    continue;                   /* no point checking further */
299 >            cur.s = rord[ri].s;
300 >            if ((cur.d = rord[ri].d) < 0 ||
301 >                        rord[ri].dc*pricerow(pm,cur.s)[cur.d] >= best.price) {
302 >                if (pm->nrows > max2check) break;       /* sorted end */
303 >                continue;                       /* else skip this one */
304 >            }
305              cur.amt = (src_rem[cur.s] < dst_rem[cur.d]) ?
306                                  src_rem[cur.s] : dst_rem[cur.d];
307 <            if (cur.amt > maxamt) cur.amt = maxamt;
308 <            dst_rem[cur.d] -= cur.amt;          /* add up differential costs */
309 <            for (i = mtx_nrows(mig); i--; )
307 >                                                /* don't just leave smidgen */
308 >            if (cur.amt > maxamt*1.02) cur.amt = maxamt;
309 >            dst_rem[cur.d] -= cur.amt;          /* add up opportunity costs */
310 >            for (i = pm->nrows; i--; )
311                  if (i != cur.s)
312 <                        cost_others += min_cost(src_rem[i], dst_rem,
258 <                                                price, mtx_ncols(mig))
312 >                    cost_others += min_cost(src_rem[i], dst_rem, pm, i)
313                                          - src_cost[i];
314              dst_rem[cur.d] += cur.amt;          /* undo trial move */
315 <            cur.price += cost_others/cur.amt;   /* adjust effective price */
315 >                                                /* discount effective price */
316 >            cur.price = ( pricerow(pm,cur.s)[cur.d] + cost_others/cur.amt ) *
317 >                                        rord[ri].dc;
318              if (cur.price < best.price)         /* are we better than best? */
319 <                    best = cur;
319 >                best = cur;
320          }
321 <        if ((best.s < 0) | (best.d < 0))
321 >        free(src_cost);                         /* clean up */
322 >        free(rord);
323 >        if ((best.s < 0) | (best.d < 0))        /* nothing left to move? */
324                  return(.0);
325 <                                                /* make the actual move */
325 >                                                /* else make the actual move */
326          mtx_coef(mig,best.s,best.d) += best.amt;
327          src_rem[best.s] -= best.amt;
328          dst_rem[best.d] -= best.amt;
329          return(best.amt);
330 + memerr:
331 +        fprintf(stderr, "%s: Out of memory in migration_step()\n", progname);
332 +        exit(1);
333 + #undef discount
334   }
335  
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
336   /* Compute and insert migration along directed edge (may fork child) */
337   static MIGRATION *
338   create_migration(RBFNODE *from_rbf, RBFNODE *to_rbf)
339   {
340          const double    end_thresh = 5e-6;
341 <        float           *pmtx;
341 >        PRICEMAT        pmtx;
342          MIGRATION       *newmig;
343          double          *src_rem, *dst_rem;
344          double          total_rem = 1., move_amt;
345 <        int             i;
345 >        int             i, j;
346                                                  /* check if exists already */
347          for (newmig = from_rbf->ejl; newmig != NULL;
348                          newmig = nextedge(from_rbf,newmig))
349                  if (newmig->rbfv[1] == to_rbf)
350                          return(NULL);
351                                                  /* else allocate */
352 + #ifdef DEBUG
353 +        fprintf(stderr, "Building path from (theta,phi) (%.1f,%.1f) ",
354 +                        get_theta180(from_rbf->invec),
355 +                        get_phi360(from_rbf->invec));
356 +        fprintf(stderr, "to (%.1f,%.1f) with %d x %d matrix\n",
357 +                        get_theta180(to_rbf->invec),
358 +                        get_phi360(to_rbf->invec),
359 +                        from_rbf->nrbf, to_rbf->nrbf);
360 + #endif
361          newmig = new_migration(from_rbf, to_rbf);
362          if (run_subprocess())
363                  return(newmig);                 /* child continues */
364 <        pmtx = price_routes(from_rbf, to_rbf);
364 >        price_routes(&pmtx, from_rbf, to_rbf);
365          src_rem = (double *)malloc(sizeof(double)*from_rbf->nrbf);
366          dst_rem = (double *)malloc(sizeof(double)*to_rbf->nrbf);
367          if ((src_rem == NULL) | (dst_rem == NULL)) {
# Line 313 | Line 369 | create_migration(RBFNODE *from_rbf, RBFNODE *to_rbf)
369                                  progname);
370                  exit(1);
371          }
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
372                                                  /* starting quantities */
373          memset(newmig->mtx, 0, sizeof(float)*from_rbf->nrbf*to_rbf->nrbf);
374          for (i = from_rbf->nrbf; i--; )
375                  src_rem[i] = rbf_volume(&from_rbf->rbfa[i]) / from_rbf->vtotal;
376 <        for (i = to_rbf->nrbf; i--; )
377 <                dst_rem[i] = rbf_volume(&to_rbf->rbfa[i]) / to_rbf->vtotal;
376 >        for (j = to_rbf->nrbf; j--; )
377 >                dst_rem[j] = rbf_volume(&to_rbf->rbfa[j]) / to_rbf->vtotal;
378 >
379          do {                                    /* move a bit at a time */
380 <                move_amt = migration_step(newmig, src_rem, dst_rem, pmtx);
380 >                move_amt = migration_step(newmig, src_rem, dst_rem, &pmtx);
381                  total_rem -= move_amt;
332 #ifdef DEBUG
333                if (!nchild)
334                        fprintf(stderr, "\r%.9f remaining...", total_rem);
335 #endif
382          } while ((total_rem > end_thresh) & (move_amt > 0));
383 < #ifdef DEBUG
338 <        if (!nchild) fputs("done.\n", stderr);
339 <        else fprintf(stderr, "finished with %.9f remaining\n", total_rem);
340 < #endif
383 >
384          for (i = from_rbf->nrbf; i--; ) {       /* normalize final matrix */
385 <            float       nf = rbf_volume(&from_rbf->rbfa[i]);
343 <            int         j;
385 >            double      nf = rbf_volume(&from_rbf->rbfa[i]);
386              if (nf <= FTINY) continue;
387              nf = from_rbf->vtotal / nf;
388              for (j = to_rbf->nrbf; j--; )
389 <                mtx_coef(newmig,i,j) *= nf;
389 >                mtx_coef(newmig,i,j) *= nf;     /* row now sums to 1.0 */
390          }
391          end_subprocess();                       /* exit here if subprocess */
392 <        free(pmtx);                             /* free working arrays */
392 >        free_routes(&pmtx);                     /* free working arrays */
393          free(src_rem);
394          free(dst_rem);
395          return(newmig);
# Line 379 | Line 421 | overlaps_tri(const RBFNODE *bv0, const RBFNODE *bv1, c
421          return(vother[im_rev] != NULL);
422   }
423  
424 < /* Find context hull vertex to complete triangle (oriented call) */
424 > /* Find convex hull vertex to complete triangle (oriented call) */
425   static RBFNODE *
426   find_chull_vert(const RBFNODE *rbf0, const RBFNODE *rbf1)
427   {
# Line 400 | Line 442 | find_chull_vert(const RBFNODE *rbf0, const RBFNODE *rb
442                  if (DOT(vp, vmid) <= FTINY)
443                          continue;               /* wrong orientation */
444                  area2 = .25*DOT(vp,vp);
445 <                VSUB(vp, rbf->invec, rbf0->invec);
445 >                VSUB(vp, rbf->invec, vmid);
446                  dprod = -DOT(vp, vejn);
447                  VSUM(vp, vp, vejn, dprod);      /* above guarantees non-zero */
448                  dprod = DOT(vp, vmid) / VLEN(vp);
# Line 456 | Line 498 | mesh_from_edge(MIGRATION *edge)
498                  }
499          }
500   }
501 +
502 + /* Add normal direction if missing */
503 + static void
504 + check_normal_incidence(void)
505 + {
506 +        static const FVECT      norm_vec = {.0, .0, 1.};
507 +        const int               saved_nprocs = nprocs;
508 +        RBFNODE                 *near_rbf, *mir_rbf, *rbf;
509 +        double                  bestd;
510 +        int                     n;
511 +
512 +        if (dsf_list == NULL)
513 +                return;                         /* XXX should be error? */
514 +        near_rbf = dsf_list;
515 +        bestd = input_orient*near_rbf->invec[2];
516 +        if (single_plane_incident) {            /* ordered plane incidence? */
517 +                if (bestd >= 1.-2.*FTINY)
518 +                        return;                 /* already have normal */
519 +        } else {
520 +                switch (inp_coverage) {
521 +                case INP_QUAD1:
522 +                case INP_QUAD2:
523 +                case INP_QUAD3:
524 +                case INP_QUAD4:
525 +                        break;                  /* quadrilateral symmetry? */
526 +                default:
527 +                        return;                 /* else we can interpolate */
528 +                }
529 +                for (rbf = near_rbf->next; rbf != NULL; rbf = rbf->next) {
530 +                        const double    d = input_orient*rbf->invec[2];
531 +                        if (d >= 1.-2.*FTINY)
532 +                                return;         /* seems we have normal */
533 +                        if (d > bestd) {
534 +                                near_rbf = rbf;
535 +                                bestd = d;
536 +                        }
537 +                }
538 +        }
539 +        if (mig_list != NULL) {                 /* need to be called first */
540 +                fprintf(stderr, "%s: Late call to check_normal_incidence()\n",
541 +                                progname);
542 +                exit(1);
543 +        }
544 + #ifdef DEBUG
545 +        fprintf(stderr, "Interpolating normal incidence by mirroring (%.1f,%.1f)\n",
546 +                        get_theta180(near_rbf->invec), get_phi360(near_rbf->invec));
547 + #endif
548 +                                                /* mirror nearest incidence */
549 +        n = sizeof(RBFNODE) + sizeof(RBFVAL)*(near_rbf->nrbf-1);
550 +        mir_rbf = (RBFNODE *)malloc(n);
551 +        if (mir_rbf == NULL)
552 +                goto memerr;
553 +        memcpy(mir_rbf, near_rbf, n);
554 +        mir_rbf->ord = near_rbf->ord - 1;       /* not used, I think */
555 +        mir_rbf->next = NULL;
556 +        rev_rbf_symmetry(mir_rbf, MIRROR_X|MIRROR_Y);
557 +        nprocs = 1;                             /* compute migration matrix */
558 +        if (mig_list != create_migration(mir_rbf, near_rbf))
559 +                exit(1);                        /* XXX should never happen! */
560 +                                                /* interpolate normal dist. */
561 +        rbf = e_advect_rbf(mig_list, norm_vec, 2*near_rbf->nrbf);
562 +        nprocs = saved_nprocs;                  /* final clean-up */
563 +        free(mir_rbf);
564 +        free(mig_list);
565 +        mig_list = near_rbf->ejl = NULL;
566 +        insert_dsf(rbf);                        /* insert interpolated normal */
567 +        return;
568 + memerr:
569 +        fprintf(stderr, "%s: Out of memory in check_normal_incidence()\n",
570 +                                progname);
571 +        exit(1);
572 + }
573          
574   /* Build our triangle mesh from recorded RBFs */
575   void
# Line 464 | Line 578 | build_mesh(void)
578          double          best2 = M_PI*M_PI;
579          RBFNODE         *shrt_edj[2];
580          RBFNODE         *rbf0, *rbf1;
581 +                                                /* add normal if needed */
582 +        check_normal_incidence();
583                                                  /* check if isotropic */
584          if (single_plane_incident) {
585                  for (rbf0 = dsf_list; rbf0 != NULL; rbf0 = rbf0->next)

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines