ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambient.c
Revision: 2.83
Committed: Sat Apr 26 05:15:17 2014 UTC (10 years ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.82: +28 -25 lines
Log Message:
Experimenting with depth-first ambient tree traversal, avoiding long-reach

File Contents

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