ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambient.c
Revision: 2.85
Committed: Tue May 6 17:15:11 2014 UTC (9 years, 11 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.84: +2 -2 lines
Log Message:
Bug fix (-DNEWAMB) where ray behind test was failing

File Contents

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