ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambient.c
Revision: 2.101
Committed: Sun Mar 6 01:13:17 2016 UTC (8 years, 2 months ago) by schorsch
Content type: text/plain
Branch: MAIN
Changes since 2.100: +1 -3 lines
Log Message:
Prepare for SCons build on Win32 and Win64

File Contents

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