ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambient.c
Revision: 2.97
Committed: Fri Aug 21 18:21:05 2015 UTC (8 years, 8 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.96: +2 -2 lines
Log Message:
Hopefull fix to deadlock issues under Mac OS X 10.10.x (Yosemite)

File Contents

# User Rev Content
1 greg 2.97 static const char RCSid[] = "$Id: ambient.c,v 2.96 2015/07/29 18:57:03 rschregle Exp $";
2 greg 1.1 /*
3     * ambient.c - routines dealing with ambient (inter-reflected) component.
4 greg 2.47 *
5     * Declarations of external symbols in ambient.h
6     */
7    
8 greg 2.48 #include "copyright.h"
9 greg 1.1
10 schorsch 2.52 #include <string.h>
11    
12 schorsch 2.50 #include "platform.h"
13 greg 1.1 #include "ray.h"
14 greg 1.8 #include "otypes.h"
15 schorsch 2.56 #include "resolu.h"
16 greg 1.14 #include "ambient.h"
17 greg 1.1 #include "random.h"
18 greg 2.94 #include "pmapamb.h"
19 greg 1.1
20 greg 2.32 #ifndef OCTSCALE
21 greg 2.29 #define OCTSCALE 1.0 /* ceil((valid rad.)/(cube size)) */
22 greg 2.32 #endif
23 greg 1.1
24 greg 2.27 extern char *shm_boundary; /* memory sharing boundary */
25 greg 2.26
26 greg 2.57 #ifndef MAXASET
27 greg 2.67 #define MAXASET 4095 /* maximum number of elements in ambient set */
28 greg 2.57 #endif
29 greg 2.12 OBJECT ambset[MAXASET+1]={0}; /* ambient include/exclude set */
30 greg 1.1
31 greg 2.12 double maxarad; /* maximum ambient radius */
32     double minarad; /* minimum ambient radius */
33 greg 1.1
34 greg 2.12 static AMBTREE atrunk; /* our ambient trunk node */
35 greg 1.1
36     static FILE *ambfp = NULL; /* ambient file pointer */
37 greg 2.16 static int nunflshed = 0; /* number of unflushed ambient values */
38 greg 1.1
39 greg 2.26 #ifndef SORT_THRESH
40 greg 2.49 #ifdef SMLMEM
41 greg 2.71 #define SORT_THRESH ((16L<<20)/sizeof(AMBVAL))
42 greg 2.49 #else
43 greg 2.71 #define SORT_THRESH ((64L<<20)/sizeof(AMBVAL))
44 greg 2.26 #endif
45     #endif
46     #ifndef SORT_INTVL
47 greg 2.41 #define SORT_INTVL (SORT_THRESH<<1)
48 greg 2.26 #endif
49 greg 2.28 #ifndef MAX_SORT_INTVL
50 greg 2.41 #define MAX_SORT_INTVL (SORT_INTVL<<6)
51 greg 2.28 #endif
52 greg 2.26
53 greg 2.74
54 gregl 2.43 static double avsum = 0.; /* computed ambient value sum (log) */
55     static unsigned int navsum = 0; /* number of values in avsum */
56 greg 2.35 static unsigned int nambvals = 0; /* total number of indirect values */
57     static unsigned int nambshare = 0; /* number of values from file */
58 greg 2.27 static unsigned long ambclock = 0; /* ambient access clock */
59     static unsigned long lastsort = 0; /* time of last value sort */
60 greg 2.26 static long sortintvl = SORT_INTVL; /* time until next sort */
61 greg 2.47 static FILE *ambinp = NULL; /* auxiliary file for input */
62     static long lastpos = -1; /* last flush position */
63 greg 2.26
64     #define MAXACLOCK (1L<<30) /* clock turnover value */
65 greg 2.27 /*
66     * Track access times unless we are sharing ambient values
67     * through memory on a multiprocessor, when we want to avoid
68 greg 2.35 * claiming our own memory (copy on write). Go ahead anyway
69     * if more than two thirds of our values are unshared.
70 gregl 2.43 * Compile with -Dtracktime=0 to turn this code off.
71 greg 2.27 */
72 gregl 2.43 #ifndef tracktime
73 greg 2.35 #define tracktime (shm_boundary == NULL || nambvals > 3*nambshare)
74 gregl 2.43 #endif
75 greg 2.26
76 greg 2.12 #define AMBFLUSH (BUFSIZ/AMBVALSIZ)
77 greg 2.6
78 greg 2.47 #define newambval() (AMBVAL *)malloc(sizeof(AMBVAL))
79     #define freeav(av) free((void *)av);
80 greg 1.1
81 schorsch 2.56 static void initambfile(int creat);
82     static void avsave(AMBVAL *av);
83     static AMBVAL *avstore(AMBVAL *aval);
84     static AMBTREE *newambtree(void);
85     static void freeambtree(AMBTREE *atp);
86    
87 greg 2.71 typedef void unloadtf_t(AMBVAL *);
88 schorsch 2.56 static unloadtf_t avinsert;
89     static unloadtf_t av2list;
90 greg 2.71 static unloadtf_t avfree;
91 schorsch 2.56 static void unloadatree(AMBTREE *at, unloadtf_t *f);
92    
93     static int aposcmp(const void *avp1, const void *avp2);
94     static int avlmemi(AMBVAL *avaddr);
95     static void sortambvals(int always);
96    
97 greg 2.19 #ifdef F_SETLKW
98 schorsch 2.56 static void aflock(int typ);
99 greg 2.19 #endif
100 greg 1.1
101 greg 2.7
102 greg 2.71 void
103 schorsch 2.56 setambres( /* set ambient resolution */
104     int ar
105     )
106 greg 2.3 {
107 greg 2.21 ambres = ar < 0 ? 0 : ar; /* may be done already */
108 greg 2.3 /* set min & max radii */
109     if (ar <= 0) {
110 greg 2.25 minarad = 0;
111 greg 2.89 maxarad = thescene.cusize*0.2;
112 greg 2.3 } else {
113     minarad = thescene.cusize / ar;
114 greg 2.83 maxarad = 64.0 * minarad; /* heuristic */
115 greg 2.89 if (maxarad > thescene.cusize*0.2)
116     maxarad = thescene.cusize*0.2;
117 greg 2.3 }
118 greg 2.25 if (minarad <= FTINY)
119 greg 2.83 minarad = 10.0*FTINY;
120 greg 2.25 if (maxarad <= minarad)
121 greg 2.83 maxarad = 64.0 * minarad;
122 greg 2.3 }
123    
124    
125 greg 2.71 void
126 schorsch 2.56 setambacc( /* set ambient accuracy */
127     double newa
128     )
129 greg 2.20 {
130 greg 2.84 static double olda; /* remember previous setting here */
131 greg 2.82
132     newa *= (newa > 0);
133     if (fabs(newa - olda) >= .05*(newa + olda)) {
134 greg 2.84 ambacc = newa;
135 greg 2.74 if (nambvals > 0)
136     sortambvals(1); /* rebuild tree */
137     }
138 greg 2.20 }
139    
140    
141 greg 2.71 void
142 schorsch 2.56 setambient(void) /* initialize calculation */
143 greg 1.1 {
144 gwlarson 2.46 int readonly = 0;
145 greg 2.66 long flen;
146 greg 2.12 AMBVAL amb;
147 greg 2.47 /* make sure we're fresh */
148     ambdone();
149 greg 2.3 /* init ambient limits */
150     setambres(ambres);
151 greg 2.82 setambacc(ambacc);
152 greg 2.47 if (ambfile == NULL || !ambfile[0])
153 greg 2.19 return;
154 greg 2.20 if (ambacc <= FTINY) {
155 greg 2.21 sprintf(errmsg, "zero ambient accuracy so \"%s\" not opened",
156 greg 2.47 ambfile);
157 greg 2.20 error(WARNING, errmsg);
158     return;
159     }
160 greg 2.3 /* open ambient file */
161 greg 2.47 if ((ambfp = fopen(ambfile, "r+")) == NULL)
162     readonly = (ambfp = fopen(ambfile, "r")) != NULL;
163 gwlarson 2.46 if (ambfp != NULL) {
164     initambfile(0); /* file exists */
165 greg 2.66 lastpos = ftell(ambfp);
166 greg 2.19 while (readambval(&amb, ambfp))
167 greg 2.88 avstore(&amb);
168 gwlarson 2.46 nambshare = nambvals; /* share loaded values */
169     if (readonly) {
170     sprintf(errmsg,
171     "loaded %u values from read-only ambient file",
172     nambvals);
173     error(WARNING, errmsg);
174     fclose(ambfp); /* close file so no writes */
175     ambfp = NULL;
176     return; /* avoid ambsync() */
177     }
178     /* align file pointer */
179 greg 2.66 lastpos += (long)nambvals*AMBVALSIZ;
180 greg 2.55 flen = lseek(fileno(ambfp), (off_t)0, SEEK_END);
181 greg 2.66 if (flen != lastpos) {
182 greg 2.42 sprintf(errmsg,
183 greg 2.37 "ignoring last %ld values in ambient file (corrupted)",
184 greg 2.66 (flen - lastpos)/AMBVALSIZ);
185 greg 2.42 error(WARNING, errmsg);
186 greg 2.66 fseek(ambfp, lastpos, SEEK_SET);
187 schorsch 2.51 #ifndef _WIN32 /* XXX we need a replacement for that one */
188 greg 2.66 ftruncate(fileno(ambfp), (off_t)lastpos);
189 schorsch 2.51 #endif
190 greg 2.37 }
191 greg 2.47 } else if ((ambfp = fopen(ambfile, "w+")) != NULL) {
192 gwlarson 2.46 initambfile(1); /* else create new file */
193 greg 2.68 fflush(ambfp);
194 greg 2.66 lastpos = ftell(ambfp);
195 gwlarson 2.46 } else {
196 greg 2.47 sprintf(errmsg, "cannot open ambient file \"%s\"", ambfile);
197 greg 2.19 error(SYSTEM, errmsg);
198 greg 2.16 }
199 greg 2.97 #if 0
200 greg 2.71 flockfile(ambfp); /* application-level lock */
201     #endif
202 greg 2.68 #ifdef F_SETLKW
203     aflock(F_UNLCK); /* release file */
204     #endif
205 greg 1.8 }
206    
207    
208 greg 2.71 void
209 schorsch 2.56 ambdone(void) /* close ambient file and free memory */
210 greg 2.47 {
211     if (ambfp != NULL) { /* close ambient file */
212     ambsync();
213     fclose(ambfp);
214     ambfp = NULL;
215     if (ambinp != NULL) {
216     fclose(ambinp);
217     ambinp = NULL;
218     }
219     lastpos = -1;
220     }
221     /* free ambient tree */
222 greg 2.71 unloadatree(&atrunk, &avfree);
223 greg 2.47 /* reset state variables */
224     avsum = 0.;
225     navsum = 0;
226     nambvals = 0;
227     nambshare = 0;
228     ambclock = 0;
229     lastsort = 0;
230     sortintvl = SORT_INTVL;
231     }
232    
233    
234 greg 2.71 void
235 schorsch 2.56 ambnotify( /* record new modifier */
236     OBJECT obj
237     )
238 greg 1.8 {
239 greg 1.11 static int hitlimit = 0;
240 greg 2.70 OBJREC *o;
241     char **amblp;
242 greg 1.8
243 greg 2.47 if (obj == OVOID) { /* starting over */
244     ambset[0] = 0;
245     hitlimit = 0;
246     return;
247     }
248     o = objptr(obj);
249 greg 1.11 if (hitlimit || !ismodifier(o->otype))
250 greg 1.8 return;
251     for (amblp = amblist; *amblp != NULL; amblp++)
252     if (!strcmp(o->oname, *amblp)) {
253 greg 1.11 if (ambset[0] >= MAXASET) {
254     error(WARNING, "too many modifiers in ambient list");
255     hitlimit++;
256     return; /* should this be fatal? */
257     }
258 greg 1.8 insertelem(ambset, obj);
259     return;
260 greg 1.1 }
261     }
262    
263 greg 2.71 /************ THE FOLLOWING ROUTINES DIFFER BETWEEN NEW & OLD ***************/
264    
265 greg 2.91 #ifndef OLDAMB
266 greg 2.71
267 greg 2.72 #define tfunc(lwr, x, upr) (((x)-(lwr))/((upr)-(lwr)))
268 greg 1.1
269 greg 2.86 static int plugaleak(RAY *r, AMBVAL *ap, FVECT anorm, double ang);
270 greg 2.72 static double sumambient(COLOR acol, RAY *r, FVECT rn, int al,
271     AMBTREE *at, FVECT c0, double s);
272     static int makeambient(COLOR acol, RAY *r, FVECT rn, int al);
273 greg 2.92 static int extambient(COLOR cr, AMBVAL *ap, FVECT pv, FVECT nv,
274 greg 2.72 FVECT uvw[3]);
275 greg 2.71
276     void
277     multambient( /* compute ambient component & multiply by coef. */
278     COLOR aval,
279     RAY *r,
280     FVECT nrm
281     )
282     {
283     static int rdepth = 0; /* ambient recursion */
284 greg 2.94 COLOR acol, caustic;
285 greg 2.71 int ok;
286     double d, l;
287    
288 greg 2.94 /* PMAP: Factor in ambient from photon map, if enabled and ray is
289     * ambient. Return as all ambient components accounted for, else
290     * continue. */
291     if (ambPmap(aval, r, rdepth))
292     return;
293    
294     /* PMAP: Factor in specular-diffuse ambient (caustics) from photon
295     * map, if enabled and ray is primary, else caustic is zero. Continue
296     * with RADIANCE ambient calculation */
297     copycolor(caustic, aval);
298     ambPmapCaustic(caustic, r, rdepth);
299    
300 greg 2.71 if (ambdiv <= 0) /* no ambient calculation */
301     goto dumbamb;
302     /* check number of bounces */
303     if (rdepth >= ambounce)
304     goto dumbamb;
305     /* check ambient list */
306     if (ambincl != -1 && r->ro != NULL &&
307     ambincl != inset(ambset, r->ro->omod))
308     goto dumbamb;
309    
310     if (ambacc <= FTINY) { /* no ambient storage */
311     copycolor(acol, aval);
312     rdepth++;
313 greg 2.86 ok = doambient(acol, r, r->rweight,
314     NULL, NULL, NULL, NULL, NULL);
315 greg 2.71 rdepth--;
316     if (!ok)
317     goto dumbamb;
318     copycolor(aval, acol);
319 greg 2.94
320     /* PMAP: add in caustic */
321     addcolor(aval, caustic);
322 greg 2.71 return;
323     }
324    
325     if (tracktime) /* sort to minimize thrashing */
326     sortambvals(0);
327     /* interpolate ambient value */
328     setcolor(acol, 0.0, 0.0, 0.0);
329     d = sumambient(acol, r, nrm, rdepth,
330     &atrunk, thescene.cuorg, thescene.cusize);
331 greg 2.94
332 greg 2.71 if (d > FTINY) {
333     d = 1.0/d;
334     scalecolor(acol, d);
335     multcolor(aval, acol);
336 greg 2.94
337     /* PMAP: add in caustic */
338     addcolor(aval, caustic);
339 greg 2.71 return;
340     }
341 greg 2.94
342 greg 2.71 rdepth++; /* need to cache new value */
343     ok = makeambient(acol, r, nrm, rdepth-1);
344     rdepth--;
345 greg 2.94
346 greg 2.71 if (ok) {
347 greg 2.73 multcolor(aval, acol); /* computed new value */
348 greg 2.94
349     /* PMAP: add in caustic */
350     addcolor(aval, caustic);
351 greg 2.71 return;
352     }
353 greg 2.94
354 greg 2.71 dumbamb: /* return global value */
355     if ((ambvwt <= 0) | (navsum == 0)) {
356     multcolor(aval, ambval);
357 greg 2.94
358     /* PMAP: add in caustic */
359     addcolor(aval, caustic);
360 greg 2.71 return;
361     }
362 greg 2.94
363     l = bright(ambval); /* average in computations */
364 greg 2.71 if (l > FTINY) {
365     d = (log(l)*(double)ambvwt + avsum) /
366     (double)(ambvwt + navsum);
367     d = exp(d) / l;
368     scalecolor(aval, d);
369     multcolor(aval, ambval); /* apply color of ambval */
370     } else {
371     d = exp( avsum / (double)navsum );
372     scalecolor(aval, d); /* neutral color */
373     }
374     }
375    
376    
377 greg 2.86 /* Plug a potential leak where ambient cache value is occluded */
378     static int
379     plugaleak(RAY *r, AMBVAL *ap, FVECT anorm, double ang)
380     {
381     const double cost70sq = 0.1169778; /* cos(70deg)^2 */
382     RAY rtst;
383     FVECT vdif;
384     double normdot, ndotd, nadotd;
385     double a, b, c, t[2];
386    
387     ang += 2.*PI*(ang < 0); /* check direction flags */
388     if ( !(ap->corral>>(int)(ang*(16./PI)) & 1) )
389     return(0);
390     /*
391     * Generate test ray, targeting 20 degrees above sample point plane
392     * along surface normal from cache position. This should be high
393     * enough to miss local geometry we don't really care about.
394     */
395     VSUB(vdif, ap->pos, r->rop);
396     normdot = DOT(anorm, r->ron);
397     ndotd = DOT(vdif, r->ron);
398     nadotd = DOT(vdif, anorm);
399     a = normdot*normdot - cost70sq;
400     b = 2.0*(normdot*ndotd - nadotd*cost70sq);
401     c = ndotd*ndotd - DOT(vdif,vdif)*cost70sq;
402     if (quadratic(t, a, b, c) != 2)
403     return(1); /* should rarely happen */
404     if (t[1] <= FTINY)
405     return(0); /* should fail behind test */
406     rayorigin(&rtst, SHADOW, r, NULL);
407     VSUM(rtst.rdir, vdif, anorm, t[1]); /* further dist. > plane */
408     rtst.rmax = normalize(rtst.rdir); /* short ray test */
409     while (localhit(&rtst, &thescene)) { /* check for occluder */
410     if (rtst.ro->omod != OVOID &&
411     (rtst.clipset == NULL ||
412     !inset(rtst.clipset, rtst.ro->omod)))
413     return(1); /* plug light leak */
414     VCOPY(rtst.rorg, rtst.rop); /* skip invisible surface */
415     rtst.rmax -= rtst.rot;
416     rayclear(&rtst);
417     }
418     return(0); /* seems we're OK */
419     }
420    
421    
422     static double
423 greg 2.72 sumambient( /* get interpolated ambient value */
424 greg 2.71 COLOR acol,
425     RAY *r,
426     FVECT rn,
427     int al,
428     AMBTREE *at,
429     FVECT c0,
430     double s
431     )
432 greg 2.80 { /* initial limit is 10 degrees plus ambacc radians */
433     const double minangle = 10.0 * PI/180.;
434 greg 2.84 double maxangle = minangle + ambacc;
435 greg 2.71 double wsum = 0.0;
436     FVECT ck0;
437     int i, j;
438     AMBVAL *av;
439 greg 2.83
440     if (at->kid != NULL) { /* sum children first */
441     s *= 0.5;
442     for (i = 0; i < 8; i++) {
443     for (j = 0; j < 3; j++) {
444     ck0[j] = c0[j];
445     if (1<<j & i)
446     ck0[j] += s;
447     if (r->rop[j] < ck0[j] - OCTSCALE*s)
448     break;
449     if (r->rop[j] > ck0[j] + (1.0+OCTSCALE)*s)
450     break;
451     }
452     if (j == 3)
453     wsum += sumambient(acol, r, rn, al,
454     at->kid+i, ck0, s);
455     }
456     /* good enough? */
457 greg 2.84 if (wsum >= 0.05 && s > minarad*10.0)
458 greg 2.83 return(wsum);
459     }
460 greg 2.84 /* adjust maximum angle */
461     if (at->alist != NULL && (at->alist->lvl <= al) & (r->rweight < 0.6))
462     maxangle = (maxangle - PI/2.)*pow(r->rweight,0.13) + PI/2.;
463 greg 2.71 /* sum this node */
464     for (av = at->alist; av != NULL; av = av->next) {
465 greg 2.86 double u, v, d, delta_r2, delta_t2;
466 greg 2.71 COLOR ct;
467     FVECT uvw[3];
468     /* record access */
469     if (tracktime)
470     av->latick = ambclock;
471     /*
472 greg 2.72 * Ambient level test
473 greg 2.71 */
474 greg 2.87 if (av->lvl > al || /* list sorted, so this works */
475     (av->lvl == al) & (av->weight < 0.9*r->rweight))
476 greg 2.71 break;
477     /*
478 greg 2.72 * Direction test using unperturbed normal
479 greg 2.71 */
480     decodedir(uvw[2], av->ndir);
481     d = DOT(uvw[2], r->ron);
482     if (d <= 0.0) /* >= 90 degrees */
483     continue;
484     delta_r2 = 2.0 - 2.0*d; /* approx. radians^2 */
485     if (delta_r2 >= maxangle*maxangle)
486     continue;
487     /*
488 greg 2.81 * Modified ray behind test
489     */
490 greg 2.85 VSUB(ck0, r->rop, av->pos);
491 greg 2.81 d = DOT(ck0, uvw[2]);
492 greg 2.84 if (d < -minarad*ambacc-.001)
493 greg 2.81 continue;
494     d /= av->rad[0];
495     delta_t2 = d*d;
496 greg 2.84 if (delta_t2 >= ambacc*ambacc)
497 greg 2.81 continue;
498     /*
499 greg 2.72 * Elliptical radii test based on Hessian
500 greg 2.71 */
501     decodedir(uvw[0], av->udir);
502     VCROSS(uvw[1], uvw[2], uvw[0]);
503 greg 2.86 d = (u = DOT(ck0, uvw[0])) / av->rad[0];
504 greg 2.81 delta_t2 += d*d;
505 greg 2.86 d = (v = DOT(ck0, uvw[1])) / av->rad[1];
506 greg 2.71 delta_t2 += d*d;
507 greg 2.84 if (delta_t2 >= ambacc*ambacc)
508 greg 2.71 continue;
509     /*
510 greg 2.86 * Test for potential light leak
511     */
512     if (av->corral && plugaleak(r, av, uvw[2], atan2a(v,u)))
513     continue;
514     /*
515 greg 2.72 * Extrapolate value and compute final weight (hat function)
516 greg 2.71 */
517 greg 2.92 if (!extambient(ct, av, r->rop, rn, uvw))
518     continue;
519 greg 2.71 d = tfunc(maxangle, sqrt(delta_r2), 0.0) *
520 greg 2.84 tfunc(ambacc, sqrt(delta_t2), 0.0);
521 greg 2.71 scalecolor(ct, d);
522     addcolor(acol, ct);
523 greg 2.72 wsum += d;
524 greg 2.71 }
525     return(wsum);
526     }
527    
528    
529 greg 2.86 static int
530 greg 2.71 makeambient( /* make a new ambient value for storage */
531     COLOR acol,
532     RAY *r,
533     FVECT rn,
534     int al
535     )
536     {
537     AMBVAL amb;
538 greg 2.72 FVECT uvw[3];
539 greg 2.71 int i;
540    
541     amb.weight = 1.0; /* compute weight */
542     for (i = al; i-- > 0; )
543     amb.weight *= AVGREFL;
544     if (r->rweight < 0.1*amb.weight) /* heuristic override */
545     amb.weight = 1.25*r->rweight;
546     setcolor(acol, AVGREFL, AVGREFL, AVGREFL);
547     /* compute ambient */
548 greg 2.86 i = doambient(acol, r, amb.weight,
549     uvw, amb.rad, amb.gpos, amb.gdir, &amb.corral);
550 greg 2.71 scalecolor(acol, 1./AVGREFL); /* undo assumed reflectance */
551 greg 2.76 if (i <= 0 || amb.rad[0] <= FTINY) /* no Hessian or zero radius */
552 greg 2.73 return(i);
553 greg 2.71 /* store value */
554     VCOPY(amb.pos, r->rop);
555     amb.ndir = encodedir(r->ron);
556 greg 2.72 amb.udir = encodedir(uvw[0]);
557 greg 2.71 amb.lvl = al;
558     copycolor(amb.val, acol);
559     /* insert into tree */
560     avsave(&amb); /* and save to file */
561 greg 2.72 if (rn != r->ron) { /* texture */
562     VCOPY(uvw[2], r->ron);
563     extambient(acol, &amb, r->rop, rn, uvw);
564     }
565 greg 2.71 return(1);
566     }
567    
568    
569 greg 2.92 static int
570 greg 2.71 extambient( /* extrapolate value at pv, nv */
571     COLOR cr,
572     AMBVAL *ap,
573     FVECT pv,
574 greg 2.72 FVECT nv,
575     FVECT uvw[3]
576 greg 2.71 )
577     {
578 greg 2.93 const double min_d = 0.05;
579 greg 2.72 static FVECT my_uvw[3];
580     FVECT v1;
581     int i;
582     double d = 1.0; /* zeroeth order */
583    
584     if (uvw == NULL) { /* need local coordinates? */
585     decodedir(my_uvw[2], ap->ndir);
586     decodedir(my_uvw[0], ap->udir);
587     VCROSS(my_uvw[1], my_uvw[2], my_uvw[0]);
588     uvw = my_uvw;
589     }
590 greg 2.71 for (i = 3; i--; ) /* gradient due to translation */
591     d += (pv[i] - ap->pos[i]) *
592     (ap->gpos[0]*uvw[0][i] + ap->gpos[1]*uvw[1][i]);
593    
594     VCROSS(v1, uvw[2], nv); /* gradient due to rotation */
595     for (i = 3; i--; )
596     d += v1[i] * (ap->gdir[0]*uvw[0][i] + ap->gdir[1]*uvw[1][i]);
597    
598 greg 2.93 if (d < min_d) /* should not use if we can avoid it */
599     d = min_d;
600 greg 2.71 copycolor(cr, ap->val);
601     scalecolor(cr, d);
602 greg 2.93 return(d > min_d);
603 greg 2.71 }
604    
605    
606     static void
607     avinsert( /* insert ambient value in our tree */
608     AMBVAL *av
609     )
610     {
611     AMBTREE *at;
612     AMBVAL *ap;
613     AMBVAL avh;
614     FVECT ck0;
615     double s;
616     int branch;
617     int i;
618    
619     if (av->rad[0] <= FTINY)
620     error(CONSISTENCY, "zero ambient radius in avinsert");
621     at = &atrunk;
622     VCOPY(ck0, thescene.cuorg);
623     s = thescene.cusize;
624 greg 2.84 while (s*(OCTSCALE/2) > av->rad[1]*ambacc) {
625 greg 2.71 if (at->kid == NULL)
626     if ((at->kid = newambtree()) == NULL)
627     error(SYSTEM, "out of memory in avinsert");
628     s *= 0.5;
629     branch = 0;
630     for (i = 0; i < 3; i++)
631     if (av->pos[i] > ck0[i] + s) {
632     ck0[i] += s;
633     branch |= 1 << i;
634     }
635     at = at->kid + branch;
636     }
637     avh.next = at->alist; /* order by increasing level */
638     for (ap = &avh; ap->next != NULL; ap = ap->next)
639 greg 2.87 if ( ap->next->lvl > av->lvl ||
640     (ap->next->lvl == av->lvl) &
641     (ap->next->weight <= av->weight) )
642 greg 2.71 break;
643     av->next = ap->next;
644     ap->next = (AMBVAL*)av;
645     at->alist = avh.next;
646     }
647    
648    
649     #else /* ! NEWAMB */
650    
651 greg 2.72 static double sumambient(COLOR acol, RAY *r, FVECT rn, int al,
652     AMBTREE *at, FVECT c0, double s);
653     static double makeambient(COLOR acol, RAY *r, FVECT rn, int al);
654     static void extambient(COLOR cr, AMBVAL *ap, FVECT pv, FVECT nv);
655    
656 greg 2.71
657     void
658 greg 2.58 multambient( /* compute ambient component & multiply by coef. */
659     COLOR aval,
660 greg 2.70 RAY *r,
661 schorsch 2.56 FVECT nrm
662     )
663 greg 1.1 {
664     static int rdepth = 0; /* ambient recursion */
665 greg 2.94 COLOR acol, caustic;
666 gregl 2.43 double d, l;
667 greg 1.1
668 greg 2.94 /* PMAP: Factor in ambient from global photon map (if enabled) and return
669     * as all ambient components accounted for */
670 rschregle 2.95 if (ambPmap(aval, r, rdepth))
671 greg 2.94 return;
672    
673     /* PMAP: Otherwise factor in ambient from caustic photon map
674 rschregle 2.96 * (ambPmapCaustic() returns zero if caustic photons disabled) and
675 greg 2.94 * continue with RADIANCE ambient calculation */
676     copycolor(caustic, aval);
677 rschregle 2.95 ambPmapCaustic(caustic, r, rdepth);
678 greg 2.94
679 greg 1.1 if (ambdiv <= 0) /* no ambient calculation */
680     goto dumbamb;
681     /* check number of bounces */
682 greg 1.16 if (rdepth >= ambounce)
683 greg 1.1 goto dumbamb;
684     /* check ambient list */
685     if (ambincl != -1 && r->ro != NULL &&
686     ambincl != inset(ambset, r->ro->omod))
687     goto dumbamb;
688    
689     if (ambacc <= FTINY) { /* no ambient storage */
690 greg 2.61 copycolor(acol, aval);
691 greg 1.16 rdepth++;
692 greg 2.61 d = doambient(acol, r, r->rweight, NULL, NULL);
693 greg 1.16 rdepth--;
694 greg 2.32 if (d <= FTINY)
695 greg 1.1 goto dumbamb;
696 greg 2.94 copycolor(aval, acol);
697    
698     /* PMAP: add in caustic */
699     addcolor(aval, caustic);
700 greg 1.16 return;
701 greg 1.1 }
702 greg 2.40
703     if (tracktime) /* sort to minimize thrashing */
704     sortambvals(0);
705 greg 2.61 /* interpolate ambient value */
706 greg 1.1 setcolor(acol, 0.0, 0.0, 0.0);
707 greg 2.61 d = sumambient(acol, r, nrm, rdepth,
708 greg 1.16 &atrunk, thescene.cuorg, thescene.cusize);
709 greg 2.94
710 greg 2.32 if (d > FTINY) {
711 greg 2.61 d = 1.0/d;
712     scalecolor(acol, d);
713 greg 2.58 multcolor(aval, acol);
714 greg 2.94
715     /* PMAP: add in caustic */
716     addcolor(aval, caustic);
717 greg 2.32 return;
718 greg 1.16 }
719 greg 2.94
720 greg 2.33 rdepth++; /* need to cache new value */
721 greg 2.61 d = makeambient(acol, r, nrm, rdepth-1);
722 greg 2.32 rdepth--;
723 greg 2.94
724 greg 2.58 if (d > FTINY) {
725     multcolor(aval, acol); /* got new value */
726 greg 2.94
727     /* PMAP: add in caustic */
728     addcolor(aval, caustic);
729 greg 1.16 return;
730 greg 2.58 }
731 greg 2.94
732 greg 1.1 dumbamb: /* return global value */
733 greg 2.58 if ((ambvwt <= 0) | (navsum == 0)) {
734     multcolor(aval, ambval);
735 greg 2.94
736     /* PMAP: add in caustic */
737     addcolor(aval, caustic);
738 greg 2.32 return;
739 greg 2.58 }
740 greg 2.94
741 gregl 2.43 l = bright(ambval); /* average in computations */
742     if (l > FTINY) {
743     d = (log(l)*(double)ambvwt + avsum) /
744     (double)(ambvwt + navsum);
745     d = exp(d) / l;
746 greg 2.58 scalecolor(aval, d);
747     multcolor(aval, ambval); /* apply color of ambval */
748 gregl 2.43 } else {
749     d = exp( avsum / (double)navsum );
750 greg 2.58 scalecolor(aval, d); /* neutral color */
751 gregl 2.43 }
752 greg 1.1 }
753    
754    
755 greg 2.72 static double
756 schorsch 2.56 sumambient( /* get interpolated ambient value */
757     COLOR acol,
758 greg 2.70 RAY *r,
759 schorsch 2.56 FVECT rn,
760     int al,
761     AMBTREE *at,
762     FVECT c0,
763     double s
764     )
765 greg 1.1 {
766 greg 2.12 double d, e1, e2, wt, wsum;
767 greg 1.1 COLOR ct;
768     FVECT ck0;
769     int i;
770 greg 2.70 int j;
771     AMBVAL *av;
772 greg 2.29
773     wsum = 0.0;
774 greg 1.7 /* do this node */
775 greg 1.1 for (av = at->alist; av != NULL; av = av->next) {
776 greg 2.47 double rn_dot = -2.0;
777 greg 2.26 if (tracktime)
778 greg 2.40 av->latick = ambclock;
779 greg 1.1 /*
780 greg 1.16 * Ambient level test.
781 greg 1.1 */
782 greg 2.87 if (av->lvl > al || /* list sorted, so this works */
783     (av->lvl == al) & (av->weight < 0.9*r->rweight))
784 greg 2.23 break;
785 greg 1.1 /*
786     * Ambient radius test.
787     */
788 greg 2.70 VSUB(ck0, av->pos, r->rop);
789     e1 = DOT(ck0, ck0) / (av->rad * av->rad);
790 greg 1.1 if (e1 > ambacc*ambacc*1.21)
791     continue;
792     /*
793 greg 2.47 * Direction test using closest normal.
794 greg 1.1 */
795 greg 2.47 d = DOT(av->dir, r->ron);
796     if (rn != r->ron) {
797     rn_dot = DOT(av->dir, rn);
798     if (rn_dot > 1.0-FTINY)
799     rn_dot = 1.0-FTINY;
800     if (rn_dot >= d-FTINY) {
801     d = rn_dot;
802     rn_dot = -2.0;
803     }
804     }
805     e2 = (1.0 - d) * r->rweight;
806 greg 2.70 if (e2 < 0.0)
807     e2 = 0.0;
808     else if (e1 + e2 > ambacc*ambacc*1.21)
809 greg 1.1 continue;
810     /*
811     * Ray behind test.
812     */
813     d = 0.0;
814     for (j = 0; j < 3; j++)
815     d += (r->rop[j] - av->pos[j]) *
816     (av->dir[j] + r->ron[j]);
817 greg 1.18 if (d*0.5 < -minarad*ambacc-.001)
818 greg 1.1 continue;
819     /*
820     * Jittering final test reduces image artifacts.
821     */
822 greg 2.47 e1 = sqrt(e1);
823     e2 = sqrt(e2);
824     wt = e1 + e2;
825 greg 2.31 if (wt > ambacc*(.9+.2*urand(9015+samplendx)))
826 greg 1.1 continue;
827 greg 2.47 /*
828     * Recompute directional error using perturbed normal
829     */
830     if (rn_dot > 0.0) {
831     e2 = sqrt((1.0 - rn_dot)*r->rweight);
832     wt = e1 + e2;
833     }
834 greg 1.1 if (wt <= 1e-3)
835     wt = 1e3;
836     else
837     wt = 1.0 / wt;
838     wsum += wt;
839 greg 2.34 extambient(ct, av, r->rop, rn);
840 greg 1.1 scalecolor(ct, wt);
841     addcolor(acol, ct);
842 greg 1.7 }
843     if (at->kid == NULL)
844     return(wsum);
845     /* do children */
846     s *= 0.5;
847     for (i = 0; i < 8; i++) {
848     for (j = 0; j < 3; j++) {
849     ck0[j] = c0[j];
850     if (1<<j & i)
851     ck0[j] += s;
852     if (r->rop[j] < ck0[j] - OCTSCALE*s)
853     break;
854     if (r->rop[j] > ck0[j] + (1.0+OCTSCALE)*s)
855     break;
856     }
857     if (j == 3)
858 greg 2.61 wsum += sumambient(acol, r, rn, al,
859 greg 2.59 at->kid+i, ck0, s);
860 greg 1.1 }
861     return(wsum);
862     }
863    
864    
865 greg 2.72 static double
866 greg 2.61 makeambient( /* make a new ambient value for storage */
867 schorsch 2.56 COLOR acol,
868 greg 2.58 RAY *r,
869 schorsch 2.56 FVECT rn,
870     int al
871     )
872 greg 1.1 {
873 greg 2.12 AMBVAL amb;
874 greg 1.14 FVECT gp, gd;
875 greg 2.60 int i;
876    
877 greg 2.61 amb.weight = 1.0; /* compute weight */
878     for (i = al; i-- > 0; )
879 greg 2.60 amb.weight *= AVGREFL;
880 greg 2.61 if (r->rweight < 0.1*amb.weight) /* heuristic override */
881 greg 2.62 amb.weight = 1.25*r->rweight;
882 greg 2.61 setcolor(acol, AVGREFL, AVGREFL, AVGREFL);
883 greg 1.16 /* compute ambient */
884 greg 2.61 amb.rad = doambient(acol, r, amb.weight, gp, gd);
885     if (amb.rad <= FTINY) {
886     setcolor(acol, 0.0, 0.0, 0.0);
887 greg 1.1 return(0.0);
888 greg 2.61 }
889     scalecolor(acol, 1./AVGREFL); /* undo assumed reflectance */
890     /* store value */
891 greg 1.1 VCOPY(amb.pos, r->rop);
892     VCOPY(amb.dir, r->ron);
893 greg 1.16 amb.lvl = al;
894 greg 1.1 copycolor(amb.val, acol);
895 greg 1.14 VCOPY(amb.gpos, gp);
896     VCOPY(amb.gdir, gd);
897 greg 1.1 /* insert into tree */
898 greg 2.7 avsave(&amb); /* and save to file */
899 greg 2.34 if (rn != r->ron)
900     extambient(acol, &amb, r->rop, rn); /* texture */
901 greg 1.1 return(amb.rad);
902 greg 1.15 }
903    
904    
905 greg 2.72 static void
906 schorsch 2.56 extambient( /* extrapolate value at pv, nv */
907     COLOR cr,
908 greg 2.70 AMBVAL *ap,
909 schorsch 2.56 FVECT pv,
910     FVECT nv
911     )
912 greg 1.15 {
913 gwlarson 2.45 FVECT v1;
914 greg 2.70 int i;
915 greg 2.12 double d;
916 greg 1.15
917     d = 1.0; /* zeroeth order */
918     /* gradient due to translation */
919     for (i = 0; i < 3; i++)
920     d += ap->gpos[i]*(pv[i]-ap->pos[i]);
921     /* gradient due to rotation */
922 gwlarson 2.45 VCROSS(v1, ap->dir, nv);
923     d += DOT(ap->gdir, v1);
924 greg 1.15 if (d <= 0.0) {
925     setcolor(cr, 0.0, 0.0, 0.0);
926     return;
927     }
928     copycolor(cr, ap->val);
929     scalecolor(cr, d);
930 greg 1.1 }
931    
932    
933 greg 2.47 static void
934 greg 2.71 avinsert( /* insert ambient value in our tree */
935     AMBVAL *av
936     )
937     {
938     AMBTREE *at;
939     AMBVAL *ap;
940     AMBVAL avh;
941     FVECT ck0;
942     double s;
943     int branch;
944     int i;
945    
946     if (av->rad <= FTINY)
947     error(CONSISTENCY, "zero ambient radius in avinsert");
948     at = &atrunk;
949     VCOPY(ck0, thescene.cuorg);
950     s = thescene.cusize;
951     while (s*(OCTSCALE/2) > av->rad*ambacc) {
952     if (at->kid == NULL)
953     if ((at->kid = newambtree()) == NULL)
954     error(SYSTEM, "out of memory in avinsert");
955     s *= 0.5;
956     branch = 0;
957     for (i = 0; i < 3; i++)
958     if (av->pos[i] > ck0[i] + s) {
959     ck0[i] += s;
960     branch |= 1 << i;
961     }
962     at = at->kid + branch;
963     }
964     avh.next = at->alist; /* order by increasing level */
965     for (ap = &avh; ap->next != NULL; ap = ap->next)
966 greg 2.87 if ( ap->next->lvl > av->lvl ||
967     (ap->next->lvl == av->lvl) &
968     (ap->next->weight <= av->weight) )
969 greg 2.71 break;
970     av->next = ap->next;
971     ap->next = (AMBVAL*)av;
972     at->alist = avh.next;
973     }
974    
975     #endif /* ! NEWAMB */
976    
977     /************* FOLLOWING ROUTINES SAME FOR NEW & OLD METHODS ***************/
978    
979     static void
980 schorsch 2.56 initambfile( /* initialize ambient file */
981 greg 2.68 int cre8
982 schorsch 2.56 )
983 greg 2.9 {
984 greg 2.47 extern char *progname, *octname;
985     static char *mybuf = NULL;
986 greg 2.9
987 greg 2.19 #ifdef F_SETLKW
988 greg 2.69 aflock(cre8 ? F_WRLCK : F_RDLCK);
989 greg 2.19 #endif
990 schorsch 2.50 SET_FILE_BINARY(ambfp);
991 greg 2.47 if (mybuf == NULL)
992     mybuf = (char *)bmalloc(BUFSIZ+8);
993     setbuf(ambfp, mybuf);
994 greg 2.68 if (cre8) { /* new file */
995 greg 2.24 newheader("RADIANCE", ambfp);
996 greg 2.41 fprintf(ambfp, "%s -av %g %g %g -aw %d -ab %d -aa %g ",
997 greg 2.9 progname, colval(ambval,RED),
998     colval(ambval,GRN), colval(ambval,BLU),
999 greg 2.41 ambvwt, ambounce, ambacc);
1000 greg 2.47 fprintf(ambfp, "-ad %d -as %d -ar %d ",
1001     ambdiv, ambssamp, ambres);
1002     if (octname != NULL)
1003 greg 2.68 fputs(octname, ambfp);
1004     fputc('\n', ambfp);
1005 greg 2.9 fprintf(ambfp, "SOFTWARE= %s\n", VersionID);
1006 greg 2.47 fputnow(ambfp);
1007 greg 2.9 fputformat(AMBFMT, ambfp);
1008 greg 2.68 fputc('\n', ambfp);
1009 greg 2.9 putambmagic(ambfp);
1010 greg 2.17 } else if (checkheader(ambfp, AMBFMT, NULL) < 0 || !hasambmagic(ambfp))
1011     error(USER, "bad ambient file");
1012 greg 2.9 }
1013    
1014    
1015 greg 2.47 static void
1016 schorsch 2.56 avsave( /* insert and save an ambient value */
1017     AMBVAL *av
1018     )
1019 greg 1.1 {
1020 greg 2.88 avstore(av);
1021 greg 1.1 if (ambfp == NULL)
1022     return;
1023 greg 2.5 if (writambval(av, ambfp) < 0)
1024 greg 1.1 goto writerr;
1025 greg 2.16 if (++nunflshed >= AMBFLUSH)
1026 greg 2.7 if (ambsync() == EOF)
1027 greg 1.1 goto writerr;
1028     return;
1029     writerr:
1030 greg 2.47 error(SYSTEM, "error writing to ambient file");
1031 greg 1.1 }
1032    
1033    
1034 greg 2.20 static AMBVAL *
1035 greg 2.88 avstore( /* allocate memory and save aval */
1036 greg 2.70 AMBVAL *aval
1037 schorsch 2.56 )
1038 greg 2.20 {
1039 greg 2.70 AMBVAL *av;
1040 gregl 2.43 double d;
1041 greg 2.20
1042     if ((av = newambval()) == NULL)
1043     error(SYSTEM, "out of memory in avstore");
1044 schorsch 2.53 *av = *aval;
1045 greg 2.26 av->latick = ambclock;
1046     av->next = NULL;
1047     nambvals++;
1048 gregl 2.43 d = bright(av->val);
1049     if (d > FTINY) { /* add to log sum for averaging */
1050     avsum += log(d);
1051     navsum++;
1052     }
1053 greg 2.88 avinsert(av); /* insert in our cache tree */
1054 greg 2.20 return(av);
1055     }
1056    
1057    
1058 greg 2.26 #define ATALLOCSZ 512 /* #/8 trees to allocate at once */
1059    
1060     static AMBTREE *atfreelist = NULL; /* free ambient tree structures */
1061    
1062    
1063 greg 2.47 static AMBTREE *
1064 schorsch 2.56 newambtree(void) /* allocate 8 ambient tree structs */
1065 greg 2.26 {
1066 greg 2.70 AMBTREE *atp, *upperlim;
1067 greg 2.26
1068     if (atfreelist == NULL) { /* get more nodes */
1069 greg 2.47 atfreelist = (AMBTREE *)malloc(ATALLOCSZ*8*sizeof(AMBTREE));
1070 greg 2.26 if (atfreelist == NULL)
1071     return(NULL);
1072     /* link new free list */
1073     upperlim = atfreelist + 8*(ATALLOCSZ-1);
1074     for (atp = atfreelist; atp < upperlim; atp += 8)
1075     atp->kid = atp + 8;
1076     atp->kid = NULL;
1077     }
1078     atp = atfreelist;
1079     atfreelist = atp->kid;
1080 schorsch 2.52 memset((char *)atp, '\0', 8*sizeof(AMBTREE));
1081 greg 2.26 return(atp);
1082     }
1083    
1084    
1085 greg 2.47 static void
1086 schorsch 2.56 freeambtree( /* free 8 ambient tree structs */
1087     AMBTREE *atp
1088     )
1089 greg 2.26 {
1090     atp->kid = atfreelist;
1091     atfreelist = atp;
1092     }
1093    
1094    
1095 greg 2.47 static void
1096 schorsch 2.56 unloadatree( /* unload an ambient value tree */
1097 greg 2.70 AMBTREE *at,
1098 schorsch 2.56 unloadtf_t *f
1099     )
1100 greg 2.20 {
1101 greg 2.70 AMBVAL *av;
1102     int i;
1103 greg 2.20 /* transfer values at this node */
1104     for (av = at->alist; av != NULL; av = at->alist) {
1105     at->alist = av->next;
1106 greg 2.26 (*f)(av);
1107 greg 2.20 }
1108 greg 2.21 if (at->kid == NULL)
1109     return;
1110 greg 2.20 for (i = 0; i < 8; i++) /* transfer and free children */
1111 greg 2.26 unloadatree(at->kid+i, f);
1112 greg 2.20 freeambtree(at->kid);
1113 greg 2.26 at->kid = NULL;
1114     }
1115    
1116    
1117 greg 2.39 static struct avl {
1118     AMBVAL *p;
1119     unsigned long t;
1120     } *avlist1; /* ambient value list with ticks */
1121     static AMBVAL **avlist2; /* memory positions for sorting */
1122 greg 2.26 static int i_avlist; /* index for lists */
1123    
1124 schorsch 2.56 static int alatcmp(const void *av1, const void *av2);
1125 greg 2.26
1126 schorsch 2.56 static void
1127 greg 2.71 avfree(AMBVAL *av)
1128     {
1129     free(av);
1130     }
1131    
1132     static void
1133 schorsch 2.56 av2list(
1134 greg 2.71 AMBVAL *av
1135 schorsch 2.56 )
1136 greg 2.26 {
1137 greg 2.27 #ifdef DEBUG
1138 greg 2.26 if (i_avlist >= nambvals)
1139     error(CONSISTENCY, "too many ambient values in av2list1");
1140 greg 2.27 #endif
1141 schorsch 2.56 avlist1[i_avlist].p = avlist2[i_avlist] = (AMBVAL*)av;
1142 greg 2.71 avlist1[i_avlist++].t = av->latick;
1143 greg 2.26 }
1144    
1145    
1146     static int
1147 schorsch 2.56 alatcmp( /* compare ambient values for MRA */
1148     const void *av1,
1149     const void *av2
1150     )
1151 greg 2.26 {
1152 greg 2.70 long lc = ((struct avl *)av2)->t - ((struct avl *)av1)->t;
1153 greg 2.38 return(lc<0 ? -1 : lc>0 ? 1 : 0);
1154 greg 2.26 }
1155    
1156    
1157 greg 2.47 /* GW NOTE 2002/10/3:
1158     * I used to compare AMBVAL pointers, but found that this was the
1159     * cause of a serious consistency error with gcc, since the optimizer
1160     * uses some dangerous trick in pointer subtraction that
1161     * assumes pointers differ by exact struct size increments.
1162     */
1163 greg 2.26 static int
1164 schorsch 2.56 aposcmp( /* compare ambient value positions */
1165     const void *avp1,
1166     const void *avp2
1167     )
1168 greg 2.26 {
1169 greg 2.70 long diff = *(char * const *)avp1 - *(char * const *)avp2;
1170 greg 2.47 if (diff < 0)
1171     return(-1);
1172     return(diff > 0);
1173 greg 2.26 }
1174    
1175 greg 2.71
1176 greg 2.27 static int
1177 schorsch 2.56 avlmemi( /* find list position from address */
1178     AMBVAL *avaddr
1179     )
1180 greg 2.27 {
1181 greg 2.70 AMBVAL **avlpp;
1182 greg 2.27
1183     avlpp = (AMBVAL **)bsearch((char *)&avaddr, (char *)avlist2,
1184 greg 2.71 nambvals, sizeof(AMBVAL *), &aposcmp);
1185 greg 2.27 if (avlpp == NULL)
1186     error(CONSISTENCY, "address not found in avlmemi");
1187     return(avlpp - avlist2);
1188     }
1189    
1190    
1191 greg 2.47 static void
1192 schorsch 2.56 sortambvals( /* resort ambient values */
1193     int always
1194     )
1195 greg 2.26 {
1196     AMBTREE oldatrunk;
1197     AMBVAL tav, *tap, *pnext;
1198 greg 2.70 int i, j;
1199 greg 2.28 /* see if it's time yet */
1200 greg 2.40 if (!always && (ambclock++ < lastsort+sortintvl ||
1201 greg 2.28 nambvals < SORT_THRESH))
1202     return;
1203 greg 2.26 /*
1204     * The idea here is to minimize memory thrashing
1205     * in VM systems by improving reference locality.
1206     * We do this by periodically sorting our stored ambient
1207     * values in memory in order of most recently to least
1208     * recently accessed. This ordering was chosen so that new
1209     * ambient values (which tend to be less important) go into
1210     * higher memory with the infrequently accessed values.
1211     * Since we expect our values to need sorting less
1212     * frequently as the process continues, we double our
1213     * waiting interval after each call.
1214     * This routine is also called by setambacc() with
1215     * the "always" parameter set to 1 so that the ambient
1216     * tree will be rebuilt with the new accuracy parameter.
1217     */
1218 greg 2.27 if (tracktime) { /* allocate pointer arrays to sort */
1219 greg 2.26 avlist2 = (AMBVAL **)malloc(nambvals*sizeof(AMBVAL *));
1220 greg 2.39 avlist1 = (struct avl *)malloc(nambvals*sizeof(struct avl));
1221     } else {
1222     avlist2 = NULL;
1223     avlist1 = NULL;
1224     }
1225     if (avlist1 == NULL) { /* no time tracking -- rebuild tree? */
1226     if (avlist2 != NULL)
1227 greg 2.47 free((void *)avlist2);
1228 greg 2.27 if (always) { /* rebuild without sorting */
1229 schorsch 2.53 oldatrunk = atrunk;
1230 greg 2.27 atrunk.alist = NULL;
1231     atrunk.kid = NULL;
1232 greg 2.71 unloadatree(&oldatrunk, &avinsert);
1233 greg 2.27 }
1234 greg 2.26 } else { /* sort memory by last access time */
1235     /*
1236     * Sorting memory is tricky because it isn't contiguous.
1237     * We have to sort an array of pointers by MRA and also
1238     * by memory position. We then copy values in "loops"
1239     * to minimize memory hits. Nevertheless, we will visit
1240 greg 2.27 * everyone at least twice, and this is an expensive process
1241 greg 2.26 * when we're thrashing, which is when we need to do it.
1242     */
1243 greg 2.27 #ifdef DEBUG
1244 greg 2.29 sprintf(errmsg, "sorting %u ambient values at ambclock=%lu...",
1245     nambvals, ambclock);
1246 greg 2.27 eputs(errmsg);
1247     #endif
1248     i_avlist = 0;
1249 greg 2.71 unloadatree(&atrunk, &av2list); /* empty current tree */
1250 greg 2.27 #ifdef DEBUG
1251     if (i_avlist < nambvals)
1252     error(CONSISTENCY, "missing ambient values in sortambvals");
1253     #endif
1254 greg 2.90 qsort((char *)avlist1, nambvals, sizeof(struct avl), alatcmp);
1255     qsort((char *)avlist2, nambvals, sizeof(AMBVAL *), aposcmp);
1256 greg 2.26 for (i = 0; i < nambvals; i++) {
1257 greg 2.39 if (avlist1[i].p == NULL)
1258 greg 2.26 continue;
1259     tap = avlist2[i];
1260 schorsch 2.53 tav = *tap;
1261 greg 2.39 for (j = i; (pnext = avlist1[j].p) != tap;
1262 greg 2.27 j = avlmemi(pnext)) {
1263 schorsch 2.53 *(avlist2[j]) = *pnext;
1264 greg 2.26 avinsert(avlist2[j]);
1265 greg 2.39 avlist1[j].p = NULL;
1266 greg 2.26 }
1267 schorsch 2.53 *(avlist2[j]) = tav;
1268 greg 2.26 avinsert(avlist2[j]);
1269 greg 2.39 avlist1[j].p = NULL;
1270 greg 2.26 }
1271 greg 2.47 free((void *)avlist1);
1272     free((void *)avlist2);
1273 greg 2.28 /* compute new sort interval */
1274     sortintvl = ambclock - lastsort;
1275 greg 2.32 if (sortintvl >= MAX_SORT_INTVL/2)
1276 greg 2.28 sortintvl = MAX_SORT_INTVL;
1277     else
1278 greg 2.26 sortintvl <<= 1; /* wait twice as long next */
1279 greg 2.27 #ifdef DEBUG
1280     eputs("done\n");
1281     #endif
1282 greg 2.26 }
1283     if (ambclock >= MAXACLOCK)
1284     ambclock = MAXACLOCK/2;
1285     lastsort = ambclock;
1286 greg 2.20 }
1287    
1288    
1289 greg 2.18 #ifdef F_SETLKW
1290 greg 2.10
1291 greg 2.47 static void
1292 schorsch 2.56 aflock( /* lock/unlock ambient file */
1293     int typ
1294     )
1295 greg 2.19 {
1296     static struct flock fls; /* static so initialized to zeroes */
1297    
1298 greg 2.66 if (typ == fls.l_type) /* already called? */
1299     return;
1300 greg 2.19 fls.l_type = typ;
1301     if (fcntl(fileno(ambfp), F_SETLKW, &fls) < 0)
1302     error(SYSTEM, "cannot (un)lock ambient file");
1303     }
1304    
1305    
1306 greg 2.71 int
1307 schorsch 2.56 ambsync(void) /* synchronize ambient file */
1308 greg 2.7 {
1309 greg 2.15 long flen;
1310 greg 2.12 AMBVAL avs;
1311 greg 2.70 int n;
1312 greg 2.16
1313 greg 2.65 if (ambfp == NULL) /* no ambient file? */
1314     return(0);
1315 greg 2.63 /* gain appropriate access */
1316     aflock(nunflshed ? F_WRLCK : F_RDLCK);
1317 greg 2.7 /* see if file has grown */
1318 greg 2.55 if ((flen = lseek(fileno(ambfp), (off_t)0, SEEK_END)) < 0)
1319 greg 2.21 goto seekerr;
1320 greg 2.68 if ((n = flen - lastpos) > 0) { /* file has grown */
1321 greg 2.17 if (ambinp == NULL) { /* use duplicate filedes */
1322     ambinp = fdopen(dup(fileno(ambfp)), "r");
1323 greg 2.14 if (ambinp == NULL)
1324 greg 2.17 error(SYSTEM, "fdopen failed in ambsync");
1325 greg 2.14 }
1326 greg 2.66 if (fseek(ambinp, lastpos, SEEK_SET) < 0)
1327 greg 2.21 goto seekerr;
1328 greg 2.15 while (n >= AMBVALSIZ) { /* load contributed values */
1329 greg 2.37 if (!readambval(&avs, ambinp)) {
1330     sprintf(errmsg,
1331 greg 2.47 "ambient file \"%s\" corrupted near character %ld",
1332     ambfile, flen - n);
1333 greg 2.37 error(WARNING, errmsg);
1334     break;
1335     }
1336 greg 2.88 avstore(&avs);
1337 greg 2.15 n -= AMBVALSIZ;
1338     }
1339 greg 2.64 lastpos = flen - n;
1340 greg 2.22 /*** seek always as safety measure
1341     if (n) ***/ /* alignment */
1342 greg 2.64 if (lseek(fileno(ambfp), (off_t)lastpos, SEEK_SET) < 0)
1343 greg 2.21 goto seekerr;
1344 greg 2.7 }
1345     n = fflush(ambfp); /* calls write() at last */
1346 greg 2.66 if (n != EOF)
1347 greg 2.64 lastpos += (long)nunflshed*AMBVALSIZ;
1348 greg 2.66 else if ((lastpos = lseek(fileno(ambfp), (off_t)0, SEEK_CUR)) < 0)
1349     goto seekerr;
1350    
1351 greg 2.19 aflock(F_UNLCK); /* release file */
1352 greg 2.16 nunflshed = 0;
1353 greg 2.7 return(n);
1354 greg 2.21 seekerr:
1355     error(SYSTEM, "seek failed in ambsync");
1356 schorsch 2.56 return -1; /* pro forma return */
1357 greg 2.18 }
1358    
1359 greg 2.71 #else /* ! F_SETLKW */
1360 greg 2.18
1361 greg 2.71 int
1362 schorsch 2.56 ambsync(void) /* flush ambient file */
1363 greg 2.18 {
1364 greg 2.65 if (ambfp == NULL)
1365     return(0);
1366 greg 2.18 nunflshed = 0;
1367     return(fflush(ambfp));
1368 greg 1.1 }
1369 greg 2.10
1370 greg 2.71 #endif /* ! F_SETLKW */