ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/cv/bsdfmesh.c
Revision: 2.10
Committed: Thu Sep 26 14:57:18 2013 UTC (10 years, 7 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.9: +10 -7 lines
Log Message:
Fixed bug related to qsort_r() allocating its own sorting memory

File Contents

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