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.14 by greg, Tue Nov 3 21:29:52 1992 UTC vs.
Revision 2.39 by greg, Tue Jul 9 19:37:09 1996 UTC

# Line 1 | Line 1
1 < /* Copyright (c) 1992 Regents of the University of California */
1 > /* Copyright (c) 1996 Regents of the University of California */
2  
3   #ifndef lint
4   static char SCCSid[] = "$SunId$ LBL";
# Line 6 | Line 6 | static char SCCSid[] = "$SunId$ LBL";
6  
7   /*
8   *  ambient.c - routines dealing with ambient (inter-reflected) component.
9 *
10 *     5/9/86
9   */
10  
11   #include  "ray.h"
# Line 20 | Line 18 | static char SCCSid[] = "$SunId$ LBL";
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 {
26          AMBVAL  *alist;         /* ambient value list */
# Line 29 | Line 29 | typedef struct ambtree {
29  
30   extern CUBE  thescene;          /* contains space boundaries */
31  
32 + extern char  *shm_boundary;     /* memory sharing boundary */
33 +
34   #define  MAXASET        511     /* maximum number of elements in ambient set */
35   OBJECT  ambset[MAXASET+1]={0};  /* ambient include/exclude set */
36  
# Line 38 | Line 40 | double minarad;                /* minimum ambient radius */
40   static AMBTREE  atrunk;         /* our ambient trunk node */
41  
42   static FILE  *ambfp = NULL;     /* ambient file pointer */
43 + static int  nunflshed = 0;      /* number of unflushed ambient values */
44  
45 + #ifndef SORT_THRESH
46 + #ifdef BIGMEM
47 + #define SORT_THRESH     ((9L<<20)/sizeof(AMBVAL))
48 + #else
49 + #define SORT_THRESH     ((3L<<20)/sizeof(AMBVAL))
50 + #endif
51 + #endif
52 + #ifndef SORT_INTVL
53 + #define SORT_INTVL      (SORT_THRESH*256)
54 + #endif
55 + #ifndef MAX_SORT_INTVL
56 + #define MAX_SORT_INTVL  (SORT_INTVL<<4)
57 + #endif
58 +
59 + static COLOR  avsum = BLKCOLOR;         /* computed ambient value sum */
60 + static unsigned int  nambvals = 0;      /* total number of indirect values */
61 + static unsigned int  nambshare = 0;     /* number of values from file */
62 + static unsigned long  ambclock = 0;     /* ambient access clock */
63 + static unsigned long  lastsort = 0;     /* time of last value sort */
64 + static long  sortintvl = SORT_INTVL;    /* time until next sort */
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).  Go ahead anyway
71 +         * if more than two thirds of our values are unshared.
72 +         */
73 + #define tracktime       (shm_boundary == NULL || nambvals > 3*nambshare)
74 +
75   #define  AMBFLUSH       (BUFSIZ/AMBVALSIZ)
76  
77   #define  newambval()    (AMBVAL *)bmalloc(sizeof(AMBVAL))
78  
46 #define  newambtree()   (AMBTREE *)calloc(8, sizeof(AMBTREE))
47
79   extern long  ftell(), lseek();
80 < static int  initambfile(), avsave(), avinsert(), ambsync();
80 > static int  initambfile(), avsave(), avinsert(), sortambvals();
81 > static AMBVAL  *avstore();
82 > #ifdef  F_SETLKW
83 > static  aflock();
84 > #endif
85  
86  
87   setambres(ar)                           /* set ambient resolution */
88   int  ar;
89   {
90 +        ambres = ar < 0 ? 0 : ar;               /* may be done already */
91                                                  /* set min & max radii */
92          if (ar <= 0) {
93 <                minarad = 0.0;
93 >                minarad = 0;
94                  maxarad = thescene.cusize / 2.0;
95          } else {
96                  minarad = thescene.cusize / ar;
97 <                maxarad = 16.0 * minarad;               /* heuristic */
97 >                maxarad = 64 * minarad;                 /* heuristic */
98                  if (maxarad > thescene.cusize / 2.0)
99                          maxarad = thescene.cusize / 2.0;
100          }
101 <        if (maxarad <= FTINY)
102 <                maxarad = .001;
101 >        if (minarad <= FTINY)
102 >                minarad = 10*FTINY;
103 >        if (maxarad <= minarad)
104 >                maxarad = 64 * minarad;
105   }
106  
107  
108 + setambacc(newa)                         /* set ambient accuracy */
109 + double  newa;
110 + {
111 +        double  ambdiff;
112 +
113 +        if (newa < 0.0)
114 +                newa = 0.0;
115 +        ambdiff = fabs(newa - ambacc);
116 +        if (ambdiff >= .01 && (ambacc = newa) > FTINY && nambvals > 0)
117 +                sortambvals(1);                 /* rebuild tree */
118 + }
119 +
120 +
121   setambient(afile)                       /* initialize calculation */
122   char  *afile;
123   {
124 <        long  headlen;
124 >        long  pos, flen;
125          AMBVAL  amb;
126                                                  /* init ambient limits */
127          setambres(ambres);
128 +        setambacc(ambacc);
129 +        if (afile == NULL)
130 +                return;
131 +        if (ambacc <= FTINY) {
132 +                sprintf(errmsg, "zero ambient accuracy so \"%s\" not opened",
133 +                                afile);
134 +                error(WARNING, errmsg);
135 +                return;
136 +        }
137                                                  /* open ambient file */
138 <        if (afile != NULL)
139 <                if ((ambfp = fopen(afile, "r+")) != NULL) {
140 <                        initambfile(0);
141 <                        headlen = ftell(ambfp);
142 <                        while (readambval(&amb, ambfp))
143 <                                avinsert(&amb, &atrunk, thescene.cuorg,
144 <                                                thescene.cusize);
145 <                                                        /* align */
146 <                        fseek(ambfp, -((ftell(ambfp)-headlen)%AMBVALSIZ), 1);
147 <                } else if ((ambfp = fopen(afile, "w+")) != NULL)
148 <                        initambfile(1);
149 <                else {
150 <                        sprintf(errmsg, "cannot open ambient file \"%s\"",
151 <                                        afile);
92 <                        error(SYSTEM, errmsg);
138 >        if ((ambfp = fopen(afile, "r+")) != NULL) {
139 >                initambfile(0);
140 >                pos = ftell(ambfp);
141 >                while (readambval(&amb, ambfp))
142 >                        avinsert(avstore(&amb));
143 >                                                /* align */
144 >                pos += (long)nambvals*AMBVALSIZ;
145 >                flen = lseek(fileno(ambfp), 0L, 2);
146 >                if (flen != pos) {
147 >                        error(WARNING,
148 >                        "ignoring last %ld values in ambient file (corrupted)",
149 >                                        (flen - pos)/AMBVALSIZ);
150 >                        fseek(ambfp, pos, 0);
151 >                        ftruncate(fileno(ambfp), pos);
152                  }
153 +                nambshare = nambvals;
154 +        } else if ((ambfp = fopen(afile, "w+")) != NULL)
155 +                initambfile(1);
156 +        else {
157 +                sprintf(errmsg, "cannot open ambient file \"%s\"", afile);
158 +                error(SYSTEM, errmsg);
159 +        }
160 +        nunflshed++;    /* lie */
161 +        ambsync();
162   }
163  
164  
# Line 116 | Line 184 | OBJECT obj;
184   }
185  
186  
187 < ambient(acol, r)                /* compute ambient component for ray */
187 > ambient(acol, r, nrm)           /* compute ambient component for ray */
188   COLOR  acol;
189   register RAY  *r;
190 + FVECT  nrm;
191   {
192          static int  rdepth = 0;                 /* ambient recursion */
193          double  d;
# Line 137 | Line 206 | register RAY  *r;
206                  rdepth++;
207                  d = doambient(acol, r, r->rweight, NULL, NULL);
208                  rdepth--;
209 <                if (d == 0.0)
209 >                if (d <= FTINY)
210                          goto dumbamb;
211                  return;
212          }
213 +                                                /* resort memory? */
214 +        sortambvals(0);
215                                                  /* get ambient value */
216          setcolor(acol, 0.0, 0.0, 0.0);
217 <        d = sumambient(acol, r, rdepth,
217 >        d = sumambient(acol, r, nrm, rdepth,
218                          &atrunk, thescene.cuorg, thescene.cusize);
219 <        if (d > FTINY)
219 >        if (d > FTINY) {
220                  scalecolor(acol, 1.0/d);
221 <        else {
151 <                d = makeambient(acol, r, rdepth++);
152 <                rdepth--;
221 >                return;
222          }
223 +        rdepth++;                               /* need to cache new value */
224 +        d = makeambient(acol, r, nrm, rdepth-1);
225 +        rdepth--;
226          if (d > FTINY)
227                  return;
228   dumbamb:                                        /* return global value */
229          copycolor(acol, ambval);
230 +        if (ambvwt <= 0 | nambvals == 0)
231 +                return;
232 +        scalecolor(acol, (double)ambvwt);
233 +        addcolor(acol, avsum);                  /* average in computations */
234 +        d = 1.0/(ambvwt+nambvals);
235 +        scalecolor(acol, d);
236   }
237  
238  
239   double
240 < sumambient(acol, r, al, at, c0, s)      /* get interpolated ambient value */
240 > sumambient(acol, r, rn, al, at, c0, s)  /* get interpolated ambient value */
241   COLOR  acol;
242   register RAY  *r;
243 + FVECT  rn;
244   int  al;
245   AMBTREE  *at;
246   FVECT  c0;
# Line 173 | Line 252 | double s;
252          int  i;
253          register int  j;
254          register AMBVAL  *av;
255 <                                        /* do this node */
255 >
256          wsum = 0.0;
257 +                                        /* do this node */
258          for (av = at->alist; av != NULL; av = av->next) {
259 +                if (tracktime)
260 +                        av->latick = ambclock++;
261                  /*
262                   *  Ambient level test.
263                   */
264 <                if (av->lvl > al || av->weight < r->rweight-FTINY)
264 >                if (av->lvl > al)       /* list sorted, so this works */
265 >                        break;
266 >                if (av->weight < r->rweight-FTINY)
267                          continue;
268                  /*
269                   *  Ambient radius test.
270                   */
271 <                e1 = 0.0;
272 <                for (j = 0; j < 3; j++) {
273 <                        d = av->pos[j] - r->rop[j];
274 <                        e1 += d * d;
275 <                }
271 >                d = av->pos[0] - r->rop[0];
272 >                e1 = d * d;
273 >                d = av->pos[1] - r->rop[1];
274 >                e1 += d * d;
275 >                d = av->pos[2] - r->rop[2];
276 >                e1 += d * d;
277                  e1 /= av->rad * av->rad;
278                  if (e1 > ambacc*ambacc*1.21)
279                          continue;
# Line 212 | Line 297 | double s;
297                   *  Jittering final test reduces image artifacts.
298                   */
299                  wt = sqrt(e1) + sqrt(e2);
300 <                wt *= .9 + .2*urand(9015+samplendx);
216 <                if (wt > ambacc)
300 >                if (wt > ambacc*(.9+.2*urand(9015+samplendx)))
301                          continue;
302                  if (wt <= 1e-3)
303                          wt = 1e3;
304                  else
305                          wt = 1.0 / wt;
306                  wsum += wt;
307 <                extambient(ct, av, r->rop, r->ron);
307 >                extambient(ct, av, r->rop, rn);
308                  scalecolor(ct, wt);
309                  addcolor(acol, ct);
310          }
# Line 239 | Line 323 | double s;
323                                  break;
324                  }
325                  if (j == 3)
326 <                        wsum += sumambient(acol, r, al, at->kid+i, ck0, s);
326 >                        wsum += sumambient(acol, r, rn, al, at->kid+i, ck0, s);
327          }
328          return(wsum);
329   }
330  
331  
332   double
333 < makeambient(acol, r, al)        /* make a new ambient value */
333 > makeambient(acol, r, rn, al)    /* make a new ambient value */
334   COLOR  acol;
335   register RAY  *r;
336 + FVECT  rn;
337   int  al;
338   {
339          AMBVAL  amb;
340          FVECT   gp, gd;
341                                                  /* compute weight */
342          amb.weight = pow(AVGREFL, (double)al);
343 <        if (r->rweight < 0.2*amb.weight)        /* heuristic */
343 >        if (r->rweight < 0.1*amb.weight)        /* heuristic */
344                  amb.weight = r->rweight;
345                                                  /* compute ambient */
346          amb.rad = doambient(acol, r, amb.weight, gp, gd);
347 <        if (amb.rad == 0.0)
347 >        if (amb.rad <= FTINY)
348                  return(0.0);
349                                                  /* store it */
350          VCOPY(amb.pos, r->rop);
# Line 270 | Line 355 | int  al;
355          VCOPY(amb.gdir, gd);
356                                                  /* insert into tree */
357          avsave(&amb);                           /* and save to file */
358 +        if (rn != r->ron)
359 +                extambient(acol, &amb, r->rop, rn);     /* texture */
360          return(amb.rad);
361   }
362  
# Line 306 | Line 393 | int  creat;
393   {
394          extern char  *progname, *octname, VersionID[];
395  
396 + #ifdef  F_SETLKW
397 +        aflock(creat ? F_WRLCK : F_RDLCK);
398 + #endif
399   #ifdef MSDOS
400          setmode(fileno(ambfp), O_BINARY);
401   #endif
402 <        setbuf(ambfp, bmalloc(BUFSIZ));
402 >        setbuf(ambfp, bmalloc(BUFSIZ+8));
403          if (creat) {                    /* new file */
404 +                newheader("RADIANCE", ambfp);
405                  fprintf(ambfp, "%s -av %g %g %g -ab %d -aa %g ",
406                                  progname, colval(ambval,RED),
407                                  colval(ambval,GRN), colval(ambval,BLU),
# Line 322 | Line 413 | int  creat;
413                  fputformat(AMBFMT, ambfp);
414                  putc('\n', ambfp);
415                  putambmagic(ambfp);
325                fflush(ambfp);
326 #ifndef  NIX
327                sync();                 /* protect against NFS buffering */
328 #endif
416          } else if (checkheader(ambfp, AMBFMT, NULL) < 0 || !hasambmagic(ambfp))
417                  error(USER, "bad ambient file");
418   }
# Line 335 | Line 422 | static
422   avsave(av)                              /* insert and save an ambient value */
423   AMBVAL  *av;
424   {
425 <        static int  nunflshed = 0;
339 <
340 <        avinsert(av, &atrunk, thescene.cuorg, thescene.cusize);
425 >        avinsert(avstore(av));
426          if (ambfp == NULL)
427                  return;
428          if (writambval(av, ambfp) < 0)
429                  goto writerr;
430 <        if (++nunflshed >= AMBFLUSH) {
430 >        if (++nunflshed >= AMBFLUSH)
431                  if (ambsync() == EOF)
432                          goto writerr;
348                nunflshed = 0;
349        }
433          return;
434   writerr:
435          error(SYSTEM, "error writing ambient file");
436   }
437  
438  
439 + static AMBVAL *
440 + avstore(aval)                           /* allocate memory and store aval */
441 + register AMBVAL  *aval;
442 + {
443 +        register AMBVAL  *av;
444 +
445 +        if ((av = newambval()) == NULL)
446 +                error(SYSTEM, "out of memory in avstore");
447 +        copystruct(av, aval);
448 +        av->latick = ambclock;
449 +        av->next = NULL;
450 +        addcolor(avsum, av->val);       /* add to sum for averaging */
451 +        nambvals++;
452 +        return(av);
453 + }
454 +
455 +
456 + #define ATALLOCSZ       512             /* #/8 trees to allocate at once */
457 +
458 + static AMBTREE  *atfreelist = NULL;     /* free ambient tree structures */
459 +
460 +
461   static
462 < avinsert(aval, at, c0, s)               /* insert ambient value in a tree */
463 < AMBVAL  *aval;
359 < register AMBTREE  *at;
360 < FVECT  c0;
361 < double  s;
462 > AMBTREE *
463 > newambtree()                            /* allocate 8 ambient tree structs */
464   {
465 +        register AMBTREE  *atp, *upperlim;
466 +
467 +        if (atfreelist == NULL) {       /* get more nodes */
468 +                atfreelist = (AMBTREE *)bmalloc(ATALLOCSZ*8*sizeof(AMBTREE));
469 +                if (atfreelist == NULL)
470 +                        return(NULL);
471 +                                        /* link new free list */
472 +                upperlim = atfreelist + 8*(ATALLOCSZ-1);
473 +                for (atp = atfreelist; atp < upperlim; atp += 8)
474 +                        atp->kid = atp + 8;
475 +                atp->kid = NULL;
476 +        }
477 +        atp = atfreelist;
478 +        atfreelist = atp->kid;
479 +        bzero((char *)atp, 8*sizeof(AMBTREE));
480 +        return(atp);
481 + }
482 +
483 +
484 + static
485 + freeambtree(atp)                        /* free 8 ambient tree structs */
486 + AMBTREE  *atp;
487 + {
488 +        atp->kid = atfreelist;
489 +        atfreelist = atp;
490 + }
491 +
492 +
493 + static
494 + avinsert(av)                            /* insert ambient value in our tree */
495 + register AMBVAL  *av;
496 + {
497 +        register AMBTREE  *at;
498 +        register AMBVAL  *ap;
499 +        AMBVAL  avh;
500          FVECT  ck0;
501 +        double  s;
502          int  branch;
365        register AMBVAL  *av;
503          register int  i;
504  
505 <        if ((av = newambval()) == NULL)
506 <                goto memerr;
507 <        copystruct(av, aval);
508 <        VCOPY(ck0, c0);
505 >        if (av->rad <= FTINY)
506 >                error(CONSISTENCY, "zero ambient radius in avinsert");
507 >        at = &atrunk;
508 >        VCOPY(ck0, thescene.cuorg);
509 >        s = thescene.cusize;
510          while (s*(OCTSCALE/2) > av->rad*ambacc) {
511                  if (at->kid == NULL)
512                          if ((at->kid = newambtree()) == NULL)
513 <                                goto memerr;
513 >                                error(SYSTEM, "out of memory in avinsert");
514                  s *= 0.5;
515                  branch = 0;
516                  for (i = 0; i < 3; i++)
# Line 382 | Line 520 | double s;
520                          }
521                  at = at->kid + branch;
522          }
523 <        av->next = at->alist;
524 <        at->alist = av;
525 <        return;
526 < memerr:
527 <        error(SYSTEM, "out of memory in avinsert");
523 >        avh.next = at->alist;           /* order by increasing level */
524 >        for (ap = &avh; ap->next != NULL; ap = ap->next)
525 >                if (ap->next->lvl >= av->lvl)
526 >                        break;
527 >        av->next = ap->next;
528 >        ap->next = av;
529 >        at->alist = avh.next;
530   }
531  
532  
533 < #ifdef  NIX
533 > static
534 > unloadatree(at, f)                      /* unload an ambient value tree */
535 > register AMBTREE  *at;
536 > int     (*f)();
537 > {
538 >        register AMBVAL  *av;
539 >        register int  i;
540 >                                        /* transfer values at this node */
541 >        for (av = at->alist; av != NULL; av = at->alist) {
542 >                at->alist = av->next;
543 >                (*f)(av);
544 >        }
545 >        if (at->kid == NULL)
546 >                return;
547 >        for (i = 0; i < 8; i++)         /* transfer and free children */
548 >                unloadatree(at->kid+i, f);
549 >        freeambtree(at->kid);
550 >        at->kid = NULL;
551 > }
552  
553 +
554 + static struct avl {
555 +        AMBVAL  *p;
556 +        unsigned long   t;
557 + }       *avlist1;                       /* ambient value list with ticks */
558 + static AMBVAL   **avlist2;              /* memory positions for sorting */
559 + static int      i_avlist;               /* index for lists */
560 +
561 +
562   static
563 < ambsync()                       /* flush ambient file */
563 > av2list(av)
564 > register AMBVAL *av;
565   {
566 <        return(fflush(ambfp));
566 > #ifdef DEBUG
567 >        if (i_avlist >= nambvals)
568 >                error(CONSISTENCY, "too many ambient values in av2list1");
569 > #endif
570 >        avlist1[i_avlist].p = avlist2[i_avlist] = av;
571 >        avlist1[i_avlist++].t = av->latick;
572   }
573  
574 +
575 + static int
576 + alatcmp(av1, av2)                       /* compare ambient values for MRA */
577 + struct avl      *av1, *av2;
578 + {
579 +        register long  lc = av2->t - av1->t;
580 +        return(lc<0 ? -1 : lc>0 ? 1 : 0);
581 + }
582 +
583 +
584 + static int
585 + aposcmp(avp1, avp2)                     /* compare ambient value positions */
586 + AMBVAL  **avp1, **avp2;
587 + {
588 +        return(*avp1 - *avp2);
589 + }
590 +
591 +
592 + #if 1
593 + static int
594 + avlmemi(avaddr)                         /* find list position from address */
595 + AMBVAL  *avaddr;
596 + {
597 +        register AMBVAL  **avlpp;
598 +
599 +        avlpp = (AMBVAL **)bsearch((char *)&avaddr, (char *)avlist2,
600 +                        nambvals, sizeof(AMBVAL *), aposcmp);
601 +        if (avlpp == NULL)
602 +                error(CONSISTENCY, "address not found in avlmemi");
603 +        return(avlpp - avlist2);
604 + }
605   #else
606 + #define avlmemi(avaddr) ((AMBVAL **)bsearch((char *)&avaddr,(char *)avlist2, \
607 +                                nambvals,sizeof(AMBVAL *),aposcmp) - avlist2)
608 + #endif
609  
403 #include  <sys/types.h>
404 #include  <sys/stat.h>
610  
611   static
612 + sortambvals(always)                     /* resort ambient values */
613 + int     always;
614 + {
615 +        AMBTREE  oldatrunk;
616 +        AMBVAL  tav, *tap, *pnext;
617 +        register int    i, j;
618 +                                        /* see if it's time yet */
619 +        if (!always && (ambclock < lastsort+sortintvl ||
620 +                        nambvals < SORT_THRESH))
621 +                return;
622 +        /*
623 +         * The idea here is to minimize memory thrashing
624 +         * in VM systems by improving reference locality.
625 +         * We do this by periodically sorting our stored ambient
626 +         * values in memory in order of most recently to least
627 +         * recently accessed.  This ordering was chosen so that new
628 +         * ambient values (which tend to be less important) go into
629 +         * higher memory with the infrequently accessed values.
630 +         *      Since we expect our values to need sorting less
631 +         * frequently as the process continues, we double our
632 +         * waiting interval after each call.
633 +         *      This routine is also called by setambacc() with
634 +         * the "always" parameter set to 1 so that the ambient
635 +         * tree will be rebuilt with the new accuracy parameter.
636 +         */
637 +        if (tracktime) {                /* allocate pointer arrays to sort */
638 +                avlist2 = (AMBVAL **)malloc(nambvals*sizeof(AMBVAL *));
639 +                avlist1 = (struct avl *)malloc(nambvals*sizeof(struct avl));
640 +        } else {
641 +                avlist2 = NULL;
642 +                avlist1 = NULL;
643 +        }
644 +        if (avlist1 == NULL) {          /* no time tracking -- rebuild tree? */
645 +                if (avlist2 != NULL)
646 +                        free((char *)avlist2);
647 +                if (always) {           /* rebuild without sorting */
648 +                        copystruct(&oldatrunk, &atrunk);
649 +                        atrunk.alist = NULL;
650 +                        atrunk.kid = NULL;
651 +                        unloadatree(&oldatrunk, avinsert);
652 +                }
653 +        } else {                        /* sort memory by last access time */
654 +                /*
655 +                 * Sorting memory is tricky because it isn't contiguous.
656 +                 * We have to sort an array of pointers by MRA and also
657 +                 * by memory position.  We then copy values in "loops"
658 +                 * to minimize memory hits.  Nevertheless, we will visit
659 +                 * everyone at least twice, and this is an expensive process
660 +                 * when we're thrashing, which is when we need to do it.
661 +                 */
662 + #ifdef DEBUG
663 +                sprintf(errmsg, "sorting %u ambient values at ambclock=%lu...",
664 +                                nambvals, ambclock);
665 +                eputs(errmsg);
666 + #endif
667 +                i_avlist = 0;
668 +                unloadatree(&atrunk, av2list);  /* empty current tree */
669 + #ifdef DEBUG
670 +                if (i_avlist < nambvals)
671 +                        error(CONSISTENCY, "missing ambient values in sortambvals");
672 + #endif
673 +                qsort((char *)avlist1, nambvals, sizeof(struct avl), alatcmp);
674 +                qsort((char *)avlist2, nambvals, sizeof(AMBVAL *), aposcmp);
675 +                for (i = 0; i < nambvals; i++) {
676 +                        if (avlist1[i].p == NULL)
677 +                                continue;
678 +                        tap = avlist2[i];
679 +                        copystruct(&tav, tap);
680 +                        for (j = i; (pnext = avlist1[j].p) != tap;
681 +                                        j = avlmemi(pnext)) {
682 +                                copystruct(avlist2[j], pnext);
683 +                                avinsert(avlist2[j]);
684 +                                avlist1[j].p = NULL;
685 +                        }
686 +                        copystruct(avlist2[j], &tav);
687 +                        avinsert(avlist2[j]);
688 +                        avlist1[j].p = NULL;
689 +                }
690 +                free((char *)avlist1);
691 +                free((char *)avlist2);
692 +                                                /* compute new sort interval */
693 +                sortintvl = ambclock - lastsort;
694 +                if (sortintvl >= MAX_SORT_INTVL/2)
695 +                        sortintvl = MAX_SORT_INTVL;
696 +                else
697 +                        sortintvl <<= 1;        /* wait twice as long next */
698 + #ifdef DEBUG
699 +                eputs("done\n");
700 + #endif
701 +        }
702 +        if (ambclock >= MAXACLOCK)
703 +                ambclock = MAXACLOCK/2;
704 +        lastsort = ambclock;
705 + }
706 +
707 +
708 + #ifdef  F_SETLKW
709 +
710 + static
711 + aflock(typ)                     /* lock/unlock ambient file */
712 + int  typ;
713 + {
714 +        static struct flock  fls;       /* static so initialized to zeroes */
715 +
716 +        fls.l_type = typ;
717 +        if (fcntl(fileno(ambfp), F_SETLKW, &fls) < 0)
718 +                error(SYSTEM, "cannot (un)lock ambient file");
719 + }
720 +
721 +
722 + int
723   ambsync()                       /* synchronize ambient file */
724   {
725          static FILE  *ambinp = NULL;
726 <        struct flock  fls;
727 <        struct stat  sts;
412 < #define flen    sts.st_size
726 >        static long  lastpos = -1;
727 >        long  flen;
728          AMBVAL  avs;
414        long  lastpos;
729          register int  n;
730 +
731 +        if (nunflshed == 0)
732 +                return(0);
733 +        if (lastpos < 0)        /* initializing (locked in initambfile) */
734 +                goto syncend;
735                                  /* gain exclusive access */
736 <        fls.l_type = F_WRLCK;
418 <        fls.l_whence = 0;
419 <        fls.l_start = 0L;
420 <        fls.l_len = 0L;
421 <        if (fcntl(fileno(ambfp), F_SETLKW, &fls) < 0)
422 <                error(SYSTEM, "cannot lock ambient file");
736 >        aflock(F_WRLCK);
737                                  /* see if file has grown */
738 <        lastpos = lseek(fileno(ambfp), 0L, 1);  /* get previous position */
739 <        if (fstat(fileno(ambfp), &sts) < 0)     /* get current length */
740 <                error(SYSTEM, "cannot stat ambient file");
741 <        if (n = (flen - lastpos)/AMBVALSIZ) {   /* file has grown */
428 <                if (ambinp == NULL) {           /* use duplicate file */
738 >        if ((flen = lseek(fileno(ambfp), 0L, 2)) < 0)
739 >                goto seekerr;
740 >        if (n = flen - lastpos) {               /* file has grown */
741 >                if (ambinp == NULL) {           /* use duplicate filedes */
742                          ambinp = fdopen(dup(fileno(ambfp)), "r");
743                          if (ambinp == NULL)
744                                  error(SYSTEM, "fdopen failed in ambsync");
745                  }
746 <                while (n--) {                   /* load contributed values */
747 <                        readambval(&avs, ambinp);
748 <                        avinsert(&avs,&atrunk,thescene.cuorg,thescene.cusize);
749 <                }                               /* moves shared file pointer */
750 <                if (n = (flen - lastpos)%AMBVALSIZ)     /* alignment */
751 <                        lseek(fileno(ambfp), flen-n, 0);
746 >                if (fseek(ambinp, lastpos, 0) < 0)
747 >                        goto seekerr;
748 >                while (n >= AMBVALSIZ) {        /* load contributed values */
749 >                        if (!readambval(&avs, ambinp)) {
750 >                                sprintf(errmsg,
751 >                                "ambient file corrupted near character %ld",
752 >                                                flen - n);
753 >                                error(WARNING, errmsg);
754 >                                break;
755 >                        }
756 >                        avinsert(avstore(&avs));
757 >                        n -= AMBVALSIZ;
758 >                }
759 >                /*** seek always as safety measure
760 >                if (n) ***/                     /* alignment */
761 >                        if (lseek(fileno(ambfp), flen-n, 0) < 0)
762 >                                goto seekerr;
763          }
764 + #ifdef  DEBUG
765 +        if (ambfp->_ptr - ambfp->_base != nunflshed*AMBVALSIZ) {
766 +                sprintf(errmsg, "ambient file buffer at %d rather than %d",
767 +                                ambfp->_ptr - ambfp->_base,
768 +                                nunflshed*AMBVALSIZ);
769 +                error(CONSISTENCY, errmsg);
770 +        }
771 + #endif
772 + syncend:
773          n = fflush(ambfp);                      /* calls write() at last */
774 <        fls.l_type = F_UNLCK;                   /* release file */
775 <        fcntl(fileno(ambfp), F_SETLKW, &fls);
774 >        if ((lastpos = lseek(fileno(ambfp), 0L, 1)) < 0)
775 >                goto seekerr;
776 >        aflock(F_UNLCK);                        /* release file */
777 >        nunflshed = 0;
778          return(n);
779 + seekerr:
780 +        error(SYSTEM, "seek failed in ambsync");
781 + }
782 +
783 + #else
784 +
785 + int
786 + ambsync()                       /* flush ambient file */
787 + {
788 +        if (nunflshed == 0)
789 +                return(0);
790 +        nunflshed = 0;
791 +        return(fflush(ambfp));
792   }
793  
794   #endif

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines