ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambient.c
(Generate patch)

Comparing ray/src/rt/ambient.c (file contents):
Revision 2.18 by greg, Fri Jan 29 12:02:23 1993 UTC vs.
Revision 2.91 by greg, Thu Jun 19 16:26:55 2014 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines