ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambient.c
Revision: 2.73
Committed: Wed Apr 16 20:32:00 2014 UTC (10 years ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.72: +5 -6 lines
Log Message:
Continued work on Hessian calculation

File Contents

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