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.31 by greg, Tue Oct 3 11:53:30 1995 UTC vs.
Revision 2.83 by greg, Sat Apr 26 05:15:17 2014 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines