ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/cv/bsdfmesh.c
Revision: 2.6
Committed: Fri Nov 9 02:16:29 2012 UTC (11 years, 4 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.5: +15 -34 lines
Log Message:
Added data to complete XML file output

File Contents

# User Rev Content
1 greg 2.1 #ifndef lint
2 greg 2.6 static const char RCSid[] = "$Id: bsdfmesh.c,v 2.5 2012/11/08 23:32:30 greg Exp $";
3 greg 2.1 #endif
4     /*
5     * Create BSDF advection mesh from radial basis functions.
6     *
7     * G. Ward
8     */
9    
10     #ifndef _WIN32
11     #include <unistd.h>
12     #include <sys/wait.h>
13     #include <sys/mman.h>
14     #endif
15     #define _USE_MATH_DEFINES
16     #include <stdio.h>
17     #include <stdlib.h>
18     #include <string.h>
19     #include <math.h>
20     #include "bsdfrep.h"
21     /* number of processes to run */
22     int nprocs = 1;
23     /* number of children (-1 in child) */
24     static int nchild = 0;
25    
26 greg 2.3 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     } PRICEMAT; /* sorted pricing matrix */
31    
32     #define pricerow(p,i) ((p)->price + (i)*(p)->ncols)
33     #define psortrow(p,i) ((p)->sord + (i)*(p)->ncols)
34    
35 greg 2.2 /* Create a new migration holder (sharing memory for multiprocessing) */
36     static MIGRATION *
37     new_migration(RBFNODE *from_rbf, RBFNODE *to_rbf)
38     {
39     size_t memlen = sizeof(MIGRATION) +
40     sizeof(float)*(from_rbf->nrbf*to_rbf->nrbf - 1);
41     MIGRATION *newmig;
42     #ifdef _WIN32
43     if (nprocs > 1)
44     fprintf(stderr, "%s: warning - multiprocessing not supported\n",
45     progname);
46     nprocs = 1;
47     newmig = (MIGRATION *)malloc(memlen);
48     #else
49     if (nprocs <= 1) { /* single process? */
50     newmig = (MIGRATION *)malloc(memlen);
51     } else { /* else need to share memory */
52     newmig = (MIGRATION *)mmap(NULL, memlen, PROT_READ|PROT_WRITE,
53     MAP_ANON|MAP_SHARED, -1, 0);
54     if ((void *)newmig == MAP_FAILED)
55     newmig = NULL;
56     }
57     #endif
58     if (newmig == NULL) {
59     fprintf(stderr, "%s: cannot allocate new migration\n", progname);
60     exit(1);
61     }
62     newmig->rbfv[0] = from_rbf;
63     newmig->rbfv[1] = to_rbf;
64     /* insert in edge lists */
65     newmig->enxt[0] = from_rbf->ejl;
66     from_rbf->ejl = newmig;
67     newmig->enxt[1] = to_rbf->ejl;
68     to_rbf->ejl = newmig;
69     newmig->next = mig_list; /* push onto global list */
70     return(mig_list = newmig);
71     }
72    
73     #ifdef _WIN32
74     #define await_children(n) (void)(n)
75     #define run_subprocess() 0
76     #define end_subprocess() (void)0
77     #else
78    
79     /* Wait for the specified number of child processes to complete */
80     static void
81     await_children(int n)
82     {
83     int exit_status = 0;
84    
85     if (n > nchild)
86     n = nchild;
87     while (n-- > 0) {
88     int status;
89     if (wait(&status) < 0) {
90     fprintf(stderr, "%s: missing child(ren)!\n", progname);
91     nchild = 0;
92     break;
93     }
94     --nchild;
95     if (status) { /* something wrong */
96     if ((status = WEXITSTATUS(status)))
97     exit_status = status;
98     else
99     exit_status += !exit_status;
100     fprintf(stderr, "%s: subprocess died\n", progname);
101     n = nchild; /* wait for the rest */
102     }
103     }
104     if (exit_status)
105     exit(exit_status);
106     }
107    
108     /* Start child process if multiprocessing selected */
109     static pid_t
110     run_subprocess(void)
111     {
112     int status;
113     pid_t pid;
114    
115     if (nprocs <= 1) /* any children requested? */
116     return(0);
117     await_children(nchild + 1 - nprocs); /* free up child process */
118     if ((pid = fork())) {
119     if (pid < 0) {
120     fprintf(stderr, "%s: cannot fork subprocess\n",
121     progname);
122 greg 2.6 await_children(nchild);
123 greg 2.2 exit(1);
124     }
125     ++nchild; /* subprocess started */
126     return(pid);
127     }
128     nchild = -1;
129     return(0); /* put child to work */
130     }
131    
132     /* If we are in subprocess, call exit */
133     #define end_subprocess() if (nchild < 0) _exit(0); else
134    
135     #endif /* ! _WIN32 */
136    
137 greg 2.3 /* Comparison routine needed for sorting price row */
138     static int
139     msrt_cmp(void *b, const void *p1, const void *p2)
140     {
141     PRICEMAT *pm = (PRICEMAT *)b;
142     int ri = ((const short *)p1 - pm->sord) / pm->ncols;
143     float c1 = pricerow(pm,ri)[*(const short *)p1];
144     float c2 = pricerow(pm,ri)[*(const short *)p2];
145    
146     if (c1 > c2) return(1);
147     if (c1 < c2) return(-1);
148     return(0);
149     }
150    
151 greg 2.1 /* Compute (and allocate) migration price matrix for optimization */
152 greg 2.3 static void
153     price_routes(PRICEMAT *pm, const RBFNODE *from_rbf, const RBFNODE *to_rbf)
154 greg 2.1 {
155     FVECT *vto = (FVECT *)malloc(sizeof(FVECT) * to_rbf->nrbf);
156     int i, j;
157    
158 greg 2.3 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 greg 2.1 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     ovec_from_pos(vfrom, from_rbf->rbfa[i].gx, from_rbf->rbfa[i].gy);
175 greg 2.3 for (j = to_rbf->nrbf; j--; ) {
176     pricerow(pm,i)[j] = acos(DOT(vfrom, vto[j])) +
177 greg 2.1 fabs(R2ANG(to_rbf->rbfa[j].crad) - from_ang);
178 greg 2.3 psortrow(pm,i)[j] = j;
179     }
180     qsort_r(psortrow(pm,i), pm->ncols, sizeof(short), pm, &msrt_cmp);
181 greg 2.1 }
182     free(vto);
183     }
184    
185 greg 2.3 /* Free price matrix */
186     static void
187     free_routes(PRICEMAT *pm)
188 greg 2.1 {
189 greg 2.3 free(pm->price); pm->price = NULL;
190     free(pm->sord); pm->sord = NULL;
191 greg 2.1 }
192    
193     /* Compute minimum (optimistic) cost for moving the given source material */
194     static double
195 greg 2.3 min_cost(double amt2move, const double *avail, const PRICEMAT *pm, int s)
196 greg 2.1 {
197     double total_cost = 0;
198 greg 2.3 int j;
199 greg 2.1
200     if (amt2move <= FTINY) /* pre-emptive check */
201 greg 2.5 return(.0);
202 greg 2.1 /* move cheapest first */
203 greg 2.3 for (j = 0; j < pm->ncols && amt2move > FTINY; j++) {
204     int d = psortrow(pm,s)[j];
205 greg 2.1 double amt = (amt2move < avail[d]) ? amt2move : avail[d];
206    
207 greg 2.3 total_cost += amt * pricerow(pm,s)[d];
208 greg 2.1 amt2move -= amt;
209     }
210     return(total_cost);
211     }
212    
213     /* Take a step in migration by choosing optimal bucket to transfer */
214     static double
215 greg 2.3 migration_step(MIGRATION *mig, double *src_rem, double *dst_rem, const PRICEMAT *pm)
216 greg 2.1 {
217 greg 2.4 const double maxamt = 1./(double)pm->ncols;
218 greg 2.2 const double minamt = maxamt*5e-6;
219 greg 2.5 double *src_cost;
220 greg 2.1 struct {
221     int s, d; /* source and destination */
222     double price; /* price estimate per amount moved */
223     double amt; /* amount we can move */
224     } cur, best;
225     int i;
226 greg 2.5 /* allocate cost array */
227     src_cost = (double *)malloc(sizeof(double)*pm->nrows);
228     if (src_cost == NULL) {
229     fprintf(stderr, "%s: Out of memory in migration_step()\n",
230     progname);
231     exit(1);
232 greg 2.1 }
233 greg 2.3 for (i = pm->nrows; i--; ) /* starting costs for diff. */
234     src_cost[i] = min_cost(src_rem[i], dst_rem, pm, i);
235 greg 2.1
236     /* find best source & dest. */
237     best.s = best.d = -1; best.price = FHUGE; best.amt = 0;
238 greg 2.3 for (cur.s = pm->nrows; cur.s--; ) {
239 greg 2.1 double cost_others = 0;
240 greg 2.5
241 greg 2.2 if (src_rem[cur.s] <= minamt)
242 greg 2.1 continue;
243 greg 2.4 /* examine cheapest dest. */
244     for (i = 0; i < pm->ncols; i++)
245 greg 2.5 if (dst_rem[ cur.d = psortrow(pm,cur.s)[i] ] > minamt)
246 greg 2.4 break;
247     if (i >= pm->ncols)
248 greg 2.5 break;
249 greg 2.4 if ((cur.price = pricerow(pm,cur.s)[cur.d]) >= best.price)
250 greg 2.5 continue; /* no point checking further */
251 greg 2.1 cur.amt = (src_rem[cur.s] < dst_rem[cur.d]) ?
252     src_rem[cur.s] : dst_rem[cur.d];
253     if (cur.amt > maxamt) cur.amt = maxamt;
254     dst_rem[cur.d] -= cur.amt; /* add up differential costs */
255 greg 2.3 for (i = pm->nrows; i--; )
256 greg 2.1 if (i != cur.s)
257 greg 2.3 cost_others += min_cost(src_rem[i], dst_rem, pm, i)
258 greg 2.1 - src_cost[i];
259     dst_rem[cur.d] += cur.amt; /* undo trial move */
260     cur.price += cost_others/cur.amt; /* adjust effective price */
261     if (cur.price < best.price) /* are we better than best? */
262     best = cur;
263     }
264 greg 2.5 free(src_cost); /* finish up */
265    
266     if ((best.s < 0) | (best.d < 0)) /* nothing left to move? */
267 greg 2.1 return(.0);
268 greg 2.5 /* else make the actual move */
269 greg 2.2 mtx_coef(mig,best.s,best.d) += best.amt;
270 greg 2.1 src_rem[best.s] -= best.amt;
271     dst_rem[best.d] -= best.amt;
272     return(best.amt);
273     }
274    
275     /* Compute and insert migration along directed edge (may fork child) */
276     static MIGRATION *
277     create_migration(RBFNODE *from_rbf, RBFNODE *to_rbf)
278     {
279 greg 2.2 const double end_thresh = 5e-6;
280 greg 2.3 PRICEMAT pmtx;
281 greg 2.1 MIGRATION *newmig;
282     double *src_rem, *dst_rem;
283     double total_rem = 1., move_amt;
284 greg 2.6 int i, j;
285 greg 2.1 /* check if exists already */
286     for (newmig = from_rbf->ejl; newmig != NULL;
287     newmig = nextedge(from_rbf,newmig))
288     if (newmig->rbfv[1] == to_rbf)
289     return(NULL);
290     /* else allocate */
291     newmig = new_migration(from_rbf, to_rbf);
292     if (run_subprocess())
293     return(newmig); /* child continues */
294 greg 2.3 price_routes(&pmtx, from_rbf, to_rbf);
295 greg 2.1 src_rem = (double *)malloc(sizeof(double)*from_rbf->nrbf);
296     dst_rem = (double *)malloc(sizeof(double)*to_rbf->nrbf);
297     if ((src_rem == NULL) | (dst_rem == NULL)) {
298     fprintf(stderr, "%s: Out of memory in create_migration()\n",
299     progname);
300     exit(1);
301     }
302     #ifdef DEBUG
303 greg 2.6 fprintf(stderr, "Building path from (theta,phi) (%.0f,%.0f) ",
304     get_theta180(from_rbf->invec),
305     get_phi360(from_rbf->invec));
306     fprintf(stderr, "to (%.0f,%.0f) with %d x %d matrix\n",
307     get_theta180(to_rbf->invec),
308     get_phi360(to_rbf->invec),
309 greg 2.2 from_rbf->nrbf, to_rbf->nrbf);
310 greg 2.1 #endif
311     /* starting quantities */
312     memset(newmig->mtx, 0, sizeof(float)*from_rbf->nrbf*to_rbf->nrbf);
313     for (i = from_rbf->nrbf; i--; )
314     src_rem[i] = rbf_volume(&from_rbf->rbfa[i]) / from_rbf->vtotal;
315 greg 2.6 for (j = to_rbf->nrbf; j--; )
316     dst_rem[j] = rbf_volume(&to_rbf->rbfa[j]) / to_rbf->vtotal;
317    
318 greg 2.1 do { /* move a bit at a time */
319 greg 2.3 move_amt = migration_step(newmig, src_rem, dst_rem, &pmtx);
320 greg 2.1 total_rem -= move_amt;
321 greg 2.2 } while ((total_rem > end_thresh) & (move_amt > 0));
322 greg 2.6
323 greg 2.1 for (i = from_rbf->nrbf; i--; ) { /* normalize final matrix */
324 greg 2.6 double nf = rbf_volume(&from_rbf->rbfa[i]);
325 greg 2.1 if (nf <= FTINY) continue;
326     nf = from_rbf->vtotal / nf;
327     for (j = to_rbf->nrbf; j--; )
328 greg 2.6 mtx_coef(newmig,i,j) *= nf; /* row now sums to 1.0 */
329 greg 2.1 }
330     end_subprocess(); /* exit here if subprocess */
331 greg 2.3 free_routes(&pmtx); /* free working arrays */
332 greg 2.1 free(src_rem);
333     free(dst_rem);
334     return(newmig);
335     }
336    
337     /* Check if prospective vertex would create overlapping triangle */
338     static int
339     overlaps_tri(const RBFNODE *bv0, const RBFNODE *bv1, const RBFNODE *pv)
340     {
341     const MIGRATION *ej;
342     RBFNODE *vother[2];
343     int im_rev;
344     /* find shared edge in mesh */
345     for (ej = pv->ejl; ej != NULL; ej = nextedge(pv,ej)) {
346     const RBFNODE *tv = opp_rbf(pv,ej);
347     if (tv == bv0) {
348     im_rev = is_rev_tri(ej->rbfv[0]->invec,
349     ej->rbfv[1]->invec, bv1->invec);
350     break;
351     }
352     if (tv == bv1) {
353     im_rev = is_rev_tri(ej->rbfv[0]->invec,
354     ej->rbfv[1]->invec, bv0->invec);
355     break;
356     }
357     }
358     if (!get_triangles(vother, ej)) /* triangle on same side? */
359     return(0);
360     return(vother[im_rev] != NULL);
361     }
362    
363     /* Find context hull vertex to complete triangle (oriented call) */
364     static RBFNODE *
365     find_chull_vert(const RBFNODE *rbf0, const RBFNODE *rbf1)
366     {
367     FVECT vmid, vejn, vp;
368     RBFNODE *rbf, *rbfbest = NULL;
369     double dprod, area2, bestarea2 = FHUGE, bestdprod = -.5;
370    
371     VSUB(vejn, rbf1->invec, rbf0->invec);
372     VADD(vmid, rbf0->invec, rbf1->invec);
373     if (normalize(vejn) == 0 || normalize(vmid) == 0)
374     return(NULL);
375     /* XXX exhaustive search */
376     /* Find triangle with minimum rotation from perpendicular */
377     for (rbf = dsf_list; rbf != NULL; rbf = rbf->next) {
378     if ((rbf == rbf0) | (rbf == rbf1))
379     continue;
380     tri_orient(vp, rbf0->invec, rbf1->invec, rbf->invec);
381     if (DOT(vp, vmid) <= FTINY)
382     continue; /* wrong orientation */
383     area2 = .25*DOT(vp,vp);
384     VSUB(vp, rbf->invec, rbf0->invec);
385     dprod = -DOT(vp, vejn);
386     VSUM(vp, vp, vejn, dprod); /* above guarantees non-zero */
387     dprod = DOT(vp, vmid) / VLEN(vp);
388     if (dprod <= bestdprod + FTINY*(1 - 2*(area2 < bestarea2)))
389     continue; /* found better already */
390     if (overlaps_tri(rbf0, rbf1, rbf))
391     continue; /* overlaps another triangle */
392     rbfbest = rbf;
393     bestdprod = dprod; /* new one to beat */
394     bestarea2 = area2;
395     }
396     return(rbfbest);
397     }
398    
399     /* Create new migration edge and grow mesh recursively around it */
400     static void
401     mesh_from_edge(MIGRATION *edge)
402     {
403     MIGRATION *ej0, *ej1;
404     RBFNODE *tvert[2];
405    
406     if (edge == NULL)
407     return;
408     /* triangle on either side? */
409     get_triangles(tvert, edge);
410     if (tvert[0] == NULL) { /* grow mesh on right */
411     tvert[0] = find_chull_vert(edge->rbfv[0], edge->rbfv[1]);
412     if (tvert[0] != NULL) {
413     if (tvert[0]->ord > edge->rbfv[0]->ord)
414     ej0 = create_migration(edge->rbfv[0], tvert[0]);
415     else
416     ej0 = create_migration(tvert[0], edge->rbfv[0]);
417     if (tvert[0]->ord > edge->rbfv[1]->ord)
418     ej1 = create_migration(edge->rbfv[1], tvert[0]);
419     else
420     ej1 = create_migration(tvert[0], edge->rbfv[1]);
421     mesh_from_edge(ej0);
422     mesh_from_edge(ej1);
423     }
424     } else if (tvert[1] == NULL) { /* grow mesh on left */
425     tvert[1] = find_chull_vert(edge->rbfv[1], edge->rbfv[0]);
426     if (tvert[1] != NULL) {
427     if (tvert[1]->ord > edge->rbfv[0]->ord)
428     ej0 = create_migration(edge->rbfv[0], tvert[1]);
429     else
430     ej0 = create_migration(tvert[1], edge->rbfv[0]);
431     if (tvert[1]->ord > edge->rbfv[1]->ord)
432     ej1 = create_migration(edge->rbfv[1], tvert[1]);
433     else
434     ej1 = create_migration(tvert[1], edge->rbfv[1]);
435     mesh_from_edge(ej0);
436     mesh_from_edge(ej1);
437     }
438     }
439     }
440    
441     /* Build our triangle mesh from recorded RBFs */
442     void
443     build_mesh(void)
444     {
445     double best2 = M_PI*M_PI;
446     RBFNODE *shrt_edj[2];
447     RBFNODE *rbf0, *rbf1;
448     /* check if isotropic */
449     if (single_plane_incident) {
450     for (rbf0 = dsf_list; rbf0 != NULL; rbf0 = rbf0->next)
451     if (rbf0->next != NULL)
452     create_migration(rbf0, rbf0->next);
453     await_children(nchild);
454     return;
455     }
456     shrt_edj[0] = shrt_edj[1] = NULL; /* start w/ shortest edge */
457     for (rbf0 = dsf_list; rbf0 != NULL; rbf0 = rbf0->next)
458     for (rbf1 = rbf0->next; rbf1 != NULL; rbf1 = rbf1->next) {
459     double dist2 = 2. - 2.*DOT(rbf0->invec,rbf1->invec);
460     if (dist2 < best2) {
461     shrt_edj[0] = rbf0;
462     shrt_edj[1] = rbf1;
463     best2 = dist2;
464     }
465     }
466     if (shrt_edj[0] == NULL) {
467     fprintf(stderr, "%s: Cannot find shortest edge\n", progname);
468     exit(1);
469     }
470     /* build mesh from this edge */
471     if (shrt_edj[0]->ord < shrt_edj[1]->ord)
472     mesh_from_edge(create_migration(shrt_edj[0], shrt_edj[1]));
473     else
474     mesh_from_edge(create_migration(shrt_edj[1], shrt_edj[0]));
475     /* complete migrations */
476     await_children(nchild);
477     }