ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambient.c
Revision: 2.43
Committed: Sat Aug 30 10:17:01 1997 UTC (26 years, 8 months ago) by gregl
Content type: text/plain
Branch: MAIN
Changes since 2.42: +23 -8 lines
Log Message:
switched to geometric mean for average -av substitute

File Contents

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