ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambient.c
Revision: 2.47
Committed: Sat Feb 22 02:07:28 2003 UTC (21 years, 2 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.46: +183 -61 lines
Log Message:
Changes and check-in for 3.5 release
Includes new source files and modifications not recorded for many years
See ray/doc/notes/ReleaseNotes for notes between 3.1 and 3.5 release

File Contents

# User Rev Content
1 greg 1.1 #ifndef lint
2 greg 2.47 static const char RCSid[] = "$Id$";
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     /* ====================================================================
11     * The Radiance Software License, Version 1.0
12     *
13     * Copyright (c) 1990 - 2002 The Regents of the University of California,
14     * through Lawrence Berkeley National Laboratory. All rights reserved.
15     *
16     * Redistribution and use in source and binary forms, with or without
17     * modification, are permitted provided that the following conditions
18     * are met:
19     *
20     * 1. Redistributions of source code must retain the above copyright
21     * notice, this list of conditions and the following disclaimer.
22     *
23     * 2. Redistributions in binary form must reproduce the above copyright
24     * notice, this list of conditions and the following disclaimer in
25     * the documentation and/or other materials provided with the
26     * distribution.
27     *
28     * 3. The end-user documentation included with the redistribution,
29     * if any, must include the following acknowledgment:
30     * "This product includes Radiance software
31     * (http://radsite.lbl.gov/)
32     * developed by the Lawrence Berkeley National Laboratory
33     * (http://www.lbl.gov/)."
34     * Alternately, this acknowledgment may appear in the software itself,
35     * if and wherever such third-party acknowledgments normally appear.
36     *
37     * 4. The names "Radiance," "Lawrence Berkeley National Laboratory"
38     * and "The Regents of the University of California" must
39     * not be used to endorse or promote products derived from this
40     * software without prior written permission. For written
41     * permission, please contact [email protected].
42     *
43     * 5. Products derived from this software may not be called "Radiance",
44     * nor may "Radiance" appear in their name, without prior written
45     * permission of Lawrence Berkeley National Laboratory.
46     *
47     * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
48     * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
49     * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
50     * DISCLAIMED. IN NO EVENT SHALL Lawrence Berkeley National Laboratory OR
51     * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
52     * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
53     * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
54     * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
55     * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
56     * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
57     * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58     * SUCH DAMAGE.
59     * ====================================================================
60     *
61     * This software consists of voluntary contributions made by many
62     * individuals on behalf of Lawrence Berkeley National Laboratory. For more
63     * information on Lawrence Berkeley National Laboratory, please see
64     * <http://www.lbl.gov/>.
65 greg 1.1 */
66    
67     #include "ray.h"
68    
69 greg 1.8 #include "otypes.h"
70    
71 greg 1.14 #include "ambient.h"
72    
73 greg 1.1 #include "random.h"
74    
75 greg 2.32 #ifndef OCTSCALE
76 greg 2.29 #define OCTSCALE 1.0 /* ceil((valid rad.)/(cube size)) */
77 greg 2.32 #endif
78 greg 1.1
79 greg 2.27 extern char *shm_boundary; /* memory sharing boundary */
80 greg 2.26
81 greg 2.12 #define MAXASET 511 /* maximum number of elements in ambient set */
82     OBJECT ambset[MAXASET+1]={0}; /* ambient include/exclude set */
83 greg 1.1
84 greg 2.12 double maxarad; /* maximum ambient radius */
85     double minarad; /* minimum ambient radius */
86 greg 1.1
87 greg 2.12 static AMBTREE atrunk; /* our ambient trunk node */
88 greg 1.1
89     static FILE *ambfp = NULL; /* ambient file pointer */
90 greg 2.16 static int nunflshed = 0; /* number of unflushed ambient values */
91 greg 1.1
92 greg 2.26 #ifndef SORT_THRESH
93     #ifdef BIGMEM
94 greg 2.27 #define SORT_THRESH ((9L<<20)/sizeof(AMBVAL))
95 greg 2.26 #else
96 greg 2.27 #define SORT_THRESH ((3L<<20)/sizeof(AMBVAL))
97 greg 2.26 #endif
98     #endif
99     #ifndef SORT_INTVL
100 greg 2.41 #define SORT_INTVL (SORT_THRESH<<1)
101 greg 2.26 #endif
102 greg 2.28 #ifndef MAX_SORT_INTVL
103 greg 2.41 #define MAX_SORT_INTVL (SORT_INTVL<<6)
104 greg 2.28 #endif
105 greg 2.26
106 gregl 2.43 static double avsum = 0.; /* computed ambient value sum (log) */
107     static unsigned int navsum = 0; /* number of values in avsum */
108 greg 2.35 static unsigned int nambvals = 0; /* total number of indirect values */
109     static unsigned int nambshare = 0; /* number of values from file */
110 greg 2.27 static unsigned long ambclock = 0; /* ambient access clock */
111     static unsigned long lastsort = 0; /* time of last value sort */
112 greg 2.26 static long sortintvl = SORT_INTVL; /* time until next sort */
113 greg 2.47 static FILE *ambinp = NULL; /* auxiliary file for input */
114     static long lastpos = -1; /* last flush position */
115 greg 2.26
116     #define MAXACLOCK (1L<<30) /* clock turnover value */
117 greg 2.27 /*
118     * Track access times unless we are sharing ambient values
119     * through memory on a multiprocessor, when we want to avoid
120 greg 2.35 * claiming our own memory (copy on write). Go ahead anyway
121     * if more than two thirds of our values are unshared.
122 gregl 2.43 * Compile with -Dtracktime=0 to turn this code off.
123 greg 2.27 */
124 gregl 2.43 #ifndef tracktime
125 greg 2.35 #define tracktime (shm_boundary == NULL || nambvals > 3*nambshare)
126 gregl 2.43 #endif
127 greg 2.26
128 greg 2.12 #define AMBFLUSH (BUFSIZ/AMBVALSIZ)
129 greg 2.6
130 greg 2.47 #define newambval() (AMBVAL *)malloc(sizeof(AMBVAL))
131     #define freeav(av) free((void *)av);
132 greg 1.1
133 greg 2.47 static void initambfile(), avsave(), avinsert(), sortambvals(), unloadatree();
134     static int avlmemi();
135 greg 2.20 static AMBVAL *avstore();
136 greg 2.19 #ifdef F_SETLKW
137 greg 2.47 static void aflock();
138 greg 2.19 #endif
139 greg 1.1
140 greg 2.7
141 greg 2.47 void
142 greg 2.3 setambres(ar) /* set ambient resolution */
143     int ar;
144     {
145 greg 2.21 ambres = ar < 0 ? 0 : ar; /* may be done already */
146 greg 2.3 /* set min & max radii */
147     if (ar <= 0) {
148 greg 2.25 minarad = 0;
149 greg 2.3 maxarad = thescene.cusize / 2.0;
150     } else {
151     minarad = thescene.cusize / ar;
152 greg 2.30 maxarad = 64 * minarad; /* heuristic */
153 greg 2.3 if (maxarad > thescene.cusize / 2.0)
154     maxarad = thescene.cusize / 2.0;
155     }
156 greg 2.25 if (minarad <= FTINY)
157     minarad = 10*FTINY;
158     if (maxarad <= minarad)
159     maxarad = 64 * minarad;
160 greg 2.3 }
161    
162    
163 greg 2.47 void
164 greg 2.21 setambacc(newa) /* set ambient accuracy */
165 greg 2.20 double newa;
166     {
167 greg 2.33 double ambdiff;
168 greg 2.20
169 greg 2.33 if (newa < 0.0)
170     newa = 0.0;
171     ambdiff = fabs(newa - ambacc);
172     if (ambdiff >= .01 && (ambacc = newa) > FTINY && nambvals > 0)
173     sortambvals(1); /* rebuild tree */
174 greg 2.20 }
175    
176    
177 greg 2.47 void
178     setambient() /* initialize calculation */
179 greg 1.1 {
180 gwlarson 2.46 int readonly = 0;
181 greg 2.37 long pos, flen;
182 greg 2.12 AMBVAL amb;
183 greg 2.47 /* make sure we're fresh */
184     ambdone();
185 greg 2.3 /* init ambient limits */
186     setambres(ambres);
187 greg 2.21 setambacc(ambacc);
188 greg 2.47 if (ambfile == NULL || !ambfile[0])
189 greg 2.19 return;
190 greg 2.20 if (ambacc <= FTINY) {
191 greg 2.21 sprintf(errmsg, "zero ambient accuracy so \"%s\" not opened",
192 greg 2.47 ambfile);
193 greg 2.20 error(WARNING, errmsg);
194     return;
195     }
196 greg 2.3 /* open ambient file */
197 greg 2.47 if ((ambfp = fopen(ambfile, "r+")) == NULL)
198     readonly = (ambfp = fopen(ambfile, "r")) != NULL;
199 gwlarson 2.46 if (ambfp != NULL) {
200     initambfile(0); /* file exists */
201 greg 2.37 pos = ftell(ambfp);
202 greg 2.19 while (readambval(&amb, ambfp))
203 greg 2.21 avinsert(avstore(&amb));
204 gwlarson 2.46 nambshare = nambvals; /* share loaded values */
205     if (readonly) {
206     sprintf(errmsg,
207     "loaded %u values from read-only ambient file",
208     nambvals);
209     error(WARNING, errmsg);
210     fclose(ambfp); /* close file so no writes */
211     ambfp = NULL;
212     return; /* avoid ambsync() */
213     }
214     /* align file pointer */
215 greg 2.37 pos += (long)nambvals*AMBVALSIZ;
216 greg 2.47 flen = lseek(fileno(ambfp), (off_t)0L, 2);
217 greg 2.37 if (flen != pos) {
218 greg 2.42 sprintf(errmsg,
219 greg 2.37 "ignoring last %ld values in ambient file (corrupted)",
220     (flen - pos)/AMBVALSIZ);
221 greg 2.42 error(WARNING, errmsg);
222 greg 2.37 fseek(ambfp, pos, 0);
223 greg 2.47 ftruncate(fileno(ambfp), (off_t)pos);
224 greg 2.37 }
225 greg 2.47 } else if ((ambfp = fopen(ambfile, "w+")) != NULL) {
226 gwlarson 2.46 initambfile(1); /* else create new file */
227     } else {
228 greg 2.47 sprintf(errmsg, "cannot open ambient file \"%s\"", ambfile);
229 greg 2.19 error(SYSTEM, errmsg);
230 greg 2.16 }
231 greg 2.19 nunflshed++; /* lie */
232     ambsync();
233 greg 1.8 }
234    
235    
236 greg 2.47 void
237     ambdone() /* close ambient file and free memory */
238     {
239     if (ambfp != NULL) { /* close ambient file */
240     ambsync();
241     fclose(ambfp);
242     ambfp = NULL;
243     if (ambinp != NULL) {
244     fclose(ambinp);
245     ambinp = NULL;
246     }
247     lastpos = -1;
248     }
249     /* free ambient tree */
250     unloadatree(&atrunk, free);
251     /* reset state variables */
252     avsum = 0.;
253     navsum = 0;
254     nambvals = 0;
255     nambshare = 0;
256     ambclock = 0;
257     lastsort = 0;
258     sortintvl = SORT_INTVL;
259     }
260    
261    
262     void
263 greg 1.8 ambnotify(obj) /* record new modifier */
264 greg 2.12 OBJECT obj;
265 greg 1.8 {
266 greg 1.11 static int hitlimit = 0;
267 greg 2.47 register OBJREC *o;
268 greg 1.8 register char **amblp;
269    
270 greg 2.47 if (obj == OVOID) { /* starting over */
271     ambset[0] = 0;
272     hitlimit = 0;
273     return;
274     }
275     o = objptr(obj);
276 greg 1.11 if (hitlimit || !ismodifier(o->otype))
277 greg 1.8 return;
278     for (amblp = amblist; *amblp != NULL; amblp++)
279     if (!strcmp(o->oname, *amblp)) {
280 greg 1.11 if (ambset[0] >= MAXASET) {
281     error(WARNING, "too many modifiers in ambient list");
282     hitlimit++;
283     return; /* should this be fatal? */
284     }
285 greg 1.8 insertelem(ambset, obj);
286     return;
287 greg 1.1 }
288     }
289    
290    
291 greg 2.47 void
292 greg 2.34 ambient(acol, r, nrm) /* compute ambient component for ray */
293 greg 1.1 COLOR acol;
294     register RAY *r;
295 greg 2.34 FVECT nrm;
296 greg 1.1 {
297     static int rdepth = 0; /* ambient recursion */
298 gregl 2.43 double d, l;
299 greg 1.1
300     if (ambdiv <= 0) /* no ambient calculation */
301     goto dumbamb;
302     /* check number of bounces */
303 greg 1.16 if (rdepth >= ambounce)
304 greg 1.1 goto dumbamb;
305     /* check ambient list */
306     if (ambincl != -1 && r->ro != NULL &&
307     ambincl != inset(ambset, r->ro->omod))
308     goto dumbamb;
309    
310     if (ambacc <= FTINY) { /* no ambient storage */
311 greg 1.16 rdepth++;
312     d = doambient(acol, r, r->rweight, NULL, NULL);
313     rdepth--;
314 greg 2.32 if (d <= FTINY)
315 greg 1.1 goto dumbamb;
316 greg 1.16 return;
317 greg 1.1 }
318 greg 2.40
319     if (tracktime) /* sort to minimize thrashing */
320     sortambvals(0);
321 greg 1.1 /* get ambient value */
322     setcolor(acol, 0.0, 0.0, 0.0);
323 greg 2.34 d = sumambient(acol, r, nrm, rdepth,
324 greg 1.16 &atrunk, thescene.cuorg, thescene.cusize);
325 greg 2.32 if (d > FTINY) {
326 greg 1.16 scalecolor(acol, 1.0/d);
327 greg 2.32 return;
328 greg 1.16 }
329 greg 2.33 rdepth++; /* need to cache new value */
330 greg 2.34 d = makeambient(acol, r, nrm, rdepth-1);
331 greg 2.32 rdepth--;
332 greg 1.16 if (d > FTINY)
333     return;
334 greg 1.1 dumbamb: /* return global value */
335     copycolor(acol, ambval);
336 gregl 2.43 if (ambvwt <= 0 | navsum == 0)
337 greg 2.32 return;
338 gregl 2.43 l = bright(ambval); /* average in computations */
339     if (l > FTINY) {
340     d = (log(l)*(double)ambvwt + avsum) /
341     (double)(ambvwt + navsum);
342     d = exp(d) / l;
343     scalecolor(acol, d); /* apply color of ambval */
344     } else {
345     d = exp( avsum / (double)navsum );
346     setcolor(acol, d, d, d); /* neutral color */
347     }
348 greg 1.1 }
349    
350    
351     double
352 greg 2.34 sumambient(acol, r, rn, al, at, c0, s) /* get interpolated ambient value */
353 greg 1.1 COLOR acol;
354     register RAY *r;
355 greg 2.34 FVECT rn;
356 greg 1.16 int al;
357 greg 2.12 AMBTREE *at;
358 greg 1.1 FVECT c0;
359 greg 2.12 double s;
360 greg 1.1 {
361 greg 2.12 double d, e1, e2, wt, wsum;
362 greg 1.1 COLOR ct;
363     FVECT ck0;
364     int i;
365     register int j;
366 greg 2.12 register AMBVAL *av;
367 greg 2.29
368     wsum = 0.0;
369 greg 1.7 /* do this node */
370 greg 1.1 for (av = at->alist; av != NULL; av = av->next) {
371 greg 2.47 double rn_dot = -2.0;
372 greg 2.26 if (tracktime)
373 greg 2.40 av->latick = ambclock;
374 greg 1.1 /*
375 greg 1.16 * Ambient level test.
376 greg 1.1 */
377 greg 2.23 if (av->lvl > al) /* list sorted, so this works */
378     break;
379     if (av->weight < r->rweight-FTINY)
380 greg 1.1 continue;
381     /*
382     * Ambient radius test.
383     */
384 greg 2.29 d = av->pos[0] - r->rop[0];
385     e1 = d * d;
386     d = av->pos[1] - r->rop[1];
387     e1 += d * d;
388     d = av->pos[2] - r->rop[2];
389     e1 += d * d;
390 greg 1.1 e1 /= av->rad * av->rad;
391     if (e1 > ambacc*ambacc*1.21)
392     continue;
393     /*
394 greg 2.47 * Direction test using closest normal.
395 greg 1.1 */
396 greg 2.47 d = DOT(av->dir, r->ron);
397     if (rn != r->ron) {
398     rn_dot = DOT(av->dir, rn);
399     if (rn_dot > 1.0-FTINY)
400     rn_dot = 1.0-FTINY;
401     if (rn_dot >= d-FTINY) {
402     d = rn_dot;
403     rn_dot = -2.0;
404     }
405     }
406     e2 = (1.0 - d) * r->rweight;
407 greg 1.1 if (e2 < 0.0) e2 = 0.0;
408     if (e1 + e2 > ambacc*ambacc*1.21)
409     continue;
410     /*
411     * Ray behind test.
412     */
413     d = 0.0;
414     for (j = 0; j < 3; j++)
415     d += (r->rop[j] - av->pos[j]) *
416     (av->dir[j] + r->ron[j]);
417 greg 1.18 if (d*0.5 < -minarad*ambacc-.001)
418 greg 1.1 continue;
419     /*
420     * Jittering final test reduces image artifacts.
421     */
422 greg 2.47 e1 = sqrt(e1);
423     e2 = sqrt(e2);
424     wt = e1 + e2;
425 greg 2.31 if (wt > ambacc*(.9+.2*urand(9015+samplendx)))
426 greg 1.1 continue;
427 greg 2.47 /*
428     * Recompute directional error using perturbed normal
429     */
430     if (rn_dot > 0.0) {
431     e2 = sqrt((1.0 - rn_dot)*r->rweight);
432     wt = e1 + e2;
433     }
434 greg 1.1 if (wt <= 1e-3)
435     wt = 1e3;
436     else
437     wt = 1.0 / wt;
438     wsum += wt;
439 greg 2.34 extambient(ct, av, r->rop, rn);
440 greg 1.1 scalecolor(ct, wt);
441     addcolor(acol, ct);
442 greg 1.7 }
443     if (at->kid == NULL)
444     return(wsum);
445     /* do children */
446     s *= 0.5;
447     for (i = 0; i < 8; i++) {
448     for (j = 0; j < 3; j++) {
449     ck0[j] = c0[j];
450     if (1<<j & i)
451     ck0[j] += s;
452     if (r->rop[j] < ck0[j] - OCTSCALE*s)
453     break;
454     if (r->rop[j] > ck0[j] + (1.0+OCTSCALE)*s)
455     break;
456     }
457     if (j == 3)
458 greg 2.34 wsum += sumambient(acol, r, rn, al, at->kid+i, ck0, s);
459 greg 1.1 }
460     return(wsum);
461     }
462    
463    
464     double
465 greg 2.34 makeambient(acol, r, rn, al) /* make a new ambient value */
466 greg 1.1 COLOR acol;
467     register RAY *r;
468 greg 2.34 FVECT rn;
469 greg 1.16 int al;
470 greg 1.1 {
471 greg 2.12 AMBVAL amb;
472 greg 1.14 FVECT gp, gd;
473 greg 1.16 /* compute weight */
474     amb.weight = pow(AVGREFL, (double)al);
475 greg 2.33 if (r->rweight < 0.1*amb.weight) /* heuristic */
476 greg 1.16 amb.weight = r->rweight;
477     /* compute ambient */
478     amb.rad = doambient(acol, r, amb.weight, gp, gd);
479 greg 2.33 if (amb.rad <= FTINY)
480 greg 1.1 return(0.0);
481     /* store it */
482     VCOPY(amb.pos, r->rop);
483     VCOPY(amb.dir, r->ron);
484 greg 1.16 amb.lvl = al;
485 greg 1.1 copycolor(amb.val, acol);
486 greg 1.14 VCOPY(amb.gpos, gp);
487     VCOPY(amb.gdir, gd);
488 greg 1.1 /* insert into tree */
489 greg 2.7 avsave(&amb); /* and save to file */
490 greg 2.34 if (rn != r->ron)
491     extambient(acol, &amb, r->rop, rn); /* texture */
492 greg 1.1 return(amb.rad);
493 greg 1.15 }
494    
495    
496 greg 2.47 void
497 greg 1.15 extambient(cr, ap, pv, nv) /* extrapolate value at pv, nv */
498     COLOR cr;
499 greg 2.12 register AMBVAL *ap;
500 greg 1.15 FVECT pv, nv;
501     {
502 gwlarson 2.45 FVECT v1;
503 greg 1.15 register int i;
504 greg 2.12 double d;
505 greg 1.15
506     d = 1.0; /* zeroeth order */
507     /* gradient due to translation */
508     for (i = 0; i < 3; i++)
509     d += ap->gpos[i]*(pv[i]-ap->pos[i]);
510     /* gradient due to rotation */
511 gwlarson 2.45 VCROSS(v1, ap->dir, nv);
512     d += DOT(ap->gdir, v1);
513 greg 1.15 if (d <= 0.0) {
514     setcolor(cr, 0.0, 0.0, 0.0);
515     return;
516     }
517     copycolor(cr, ap->val);
518     scalecolor(cr, d);
519 greg 1.1 }
520    
521    
522 greg 2.47 static void
523 greg 2.9 initambfile(creat) /* initialize ambient file */
524     int creat;
525     {
526 greg 2.47 extern char *progname, *octname;
527     static char *mybuf = NULL;
528 greg 2.9
529 greg 2.19 #ifdef F_SETLKW
530     aflock(creat ? F_WRLCK : F_RDLCK);
531     #endif
532 greg 2.12 #ifdef MSDOS
533     setmode(fileno(ambfp), O_BINARY);
534     #endif
535 greg 2.47 if (mybuf == NULL)
536     mybuf = (char *)bmalloc(BUFSIZ+8);
537     setbuf(ambfp, mybuf);
538 greg 2.9 if (creat) { /* new file */
539 greg 2.24 newheader("RADIANCE", ambfp);
540 greg 2.41 fprintf(ambfp, "%s -av %g %g %g -aw %d -ab %d -aa %g ",
541 greg 2.9 progname, colval(ambval,RED),
542     colval(ambval,GRN), colval(ambval,BLU),
543 greg 2.41 ambvwt, ambounce, ambacc);
544 greg 2.47 fprintf(ambfp, "-ad %d -as %d -ar %d ",
545     ambdiv, ambssamp, ambres);
546     if (octname != NULL)
547     printargs(1, &octname, ambfp);
548     else
549     fputc('\n', ambfp);
550 greg 2.9 fprintf(ambfp, "SOFTWARE= %s\n", VersionID);
551 greg 2.47 fputnow(ambfp);
552 greg 2.9 fputformat(AMBFMT, ambfp);
553     putc('\n', ambfp);
554     putambmagic(ambfp);
555 greg 2.17 } else if (checkheader(ambfp, AMBFMT, NULL) < 0 || !hasambmagic(ambfp))
556     error(USER, "bad ambient file");
557 greg 2.9 }
558    
559    
560 greg 2.47 static void
561 greg 2.7 avsave(av) /* insert and save an ambient value */
562 greg 2.12 AMBVAL *av;
563 greg 1.1 {
564 greg 2.21 avinsert(avstore(av));
565 greg 1.1 if (ambfp == NULL)
566     return;
567 greg 2.5 if (writambval(av, ambfp) < 0)
568 greg 1.1 goto writerr;
569 greg 2.16 if (++nunflshed >= AMBFLUSH)
570 greg 2.7 if (ambsync() == EOF)
571 greg 1.1 goto writerr;
572     return;
573     writerr:
574 greg 2.47 error(SYSTEM, "error writing to ambient file");
575 greg 1.1 }
576    
577    
578 greg 2.20 static AMBVAL *
579     avstore(aval) /* allocate memory and store aval */
580     register AMBVAL *aval;
581     {
582     register AMBVAL *av;
583 gregl 2.43 double d;
584 greg 2.20
585     if ((av = newambval()) == NULL)
586     error(SYSTEM, "out of memory in avstore");
587     copystruct(av, aval);
588 greg 2.26 av->latick = ambclock;
589     av->next = NULL;
590     nambvals++;
591 gregl 2.43 d = bright(av->val);
592     if (d > FTINY) { /* add to log sum for averaging */
593     avsum += log(d);
594     navsum++;
595     }
596 greg 2.20 return(av);
597     }
598    
599    
600 greg 2.26 #define ATALLOCSZ 512 /* #/8 trees to allocate at once */
601    
602     static AMBTREE *atfreelist = NULL; /* free ambient tree structures */
603    
604    
605 greg 2.47 static AMBTREE *
606 greg 2.26 newambtree() /* allocate 8 ambient tree structs */
607     {
608     register AMBTREE *atp, *upperlim;
609    
610     if (atfreelist == NULL) { /* get more nodes */
611 greg 2.47 atfreelist = (AMBTREE *)malloc(ATALLOCSZ*8*sizeof(AMBTREE));
612 greg 2.26 if (atfreelist == NULL)
613     return(NULL);
614     /* link new free list */
615     upperlim = atfreelist + 8*(ATALLOCSZ-1);
616     for (atp = atfreelist; atp < upperlim; atp += 8)
617     atp->kid = atp + 8;
618     atp->kid = NULL;
619     }
620     atp = atfreelist;
621     atfreelist = atp->kid;
622     bzero((char *)atp, 8*sizeof(AMBTREE));
623     return(atp);
624     }
625    
626    
627 greg 2.47 static void
628 greg 2.26 freeambtree(atp) /* free 8 ambient tree structs */
629     AMBTREE *atp;
630     {
631     atp->kid = atfreelist;
632     atfreelist = atp;
633     }
634    
635    
636 greg 2.47 static void
637 greg 2.21 avinsert(av) /* insert ambient value in our tree */
638 greg 2.20 register AMBVAL *av;
639 greg 1.1 {
640 greg 2.21 register AMBTREE *at;
641 greg 2.23 register AMBVAL *ap;
642     AMBVAL avh;
643 greg 1.1 FVECT ck0;
644 greg 2.21 double s;
645 greg 1.1 int branch;
646     register int i;
647    
648 greg 2.20 if (av->rad <= FTINY)
649     error(CONSISTENCY, "zero ambient radius in avinsert");
650 greg 2.21 at = &atrunk;
651     VCOPY(ck0, thescene.cuorg);
652     s = thescene.cusize;
653 greg 1.1 while (s*(OCTSCALE/2) > av->rad*ambacc) {
654     if (at->kid == NULL)
655     if ((at->kid = newambtree()) == NULL)
656 greg 2.20 error(SYSTEM, "out of memory in avinsert");
657 greg 1.1 s *= 0.5;
658     branch = 0;
659     for (i = 0; i < 3; i++)
660     if (av->pos[i] > ck0[i] + s) {
661     ck0[i] += s;
662     branch |= 1 << i;
663     }
664     at = at->kid + branch;
665     }
666 greg 2.23 avh.next = at->alist; /* order by increasing level */
667     for (ap = &avh; ap->next != NULL; ap = ap->next)
668     if (ap->next->lvl >= av->lvl)
669     break;
670     av->next = ap->next;
671     ap->next = av;
672     at->alist = avh.next;
673 greg 2.7 }
674    
675    
676 greg 2.47 static void
677 greg 2.26 unloadatree(at, f) /* unload an ambient value tree */
678 greg 2.20 register AMBTREE *at;
679 greg 2.47 void (*f)();
680 greg 2.20 {
681     register AMBVAL *av;
682     register int i;
683     /* transfer values at this node */
684     for (av = at->alist; av != NULL; av = at->alist) {
685     at->alist = av->next;
686 greg 2.26 (*f)(av);
687 greg 2.20 }
688 greg 2.21 if (at->kid == NULL)
689     return;
690 greg 2.20 for (i = 0; i < 8; i++) /* transfer and free children */
691 greg 2.26 unloadatree(at->kid+i, f);
692 greg 2.20 freeambtree(at->kid);
693 greg 2.26 at->kid = NULL;
694     }
695    
696    
697 greg 2.39 static struct avl {
698     AMBVAL *p;
699     unsigned long t;
700     } *avlist1; /* ambient value list with ticks */
701     static AMBVAL **avlist2; /* memory positions for sorting */
702 greg 2.26 static int i_avlist; /* index for lists */
703    
704    
705 greg 2.47 static int
706 greg 2.26 av2list(av)
707 greg 2.39 register AMBVAL *av;
708 greg 2.26 {
709 greg 2.27 #ifdef DEBUG
710 greg 2.26 if (i_avlist >= nambvals)
711     error(CONSISTENCY, "too many ambient values in av2list1");
712 greg 2.27 #endif
713 greg 2.39 avlist1[i_avlist].p = avlist2[i_avlist] = av;
714     avlist1[i_avlist++].t = av->latick;
715 greg 2.26 }
716    
717    
718     static int
719 greg 2.39 alatcmp(av1, av2) /* compare ambient values for MRA */
720     struct avl *av1, *av2;
721 greg 2.26 {
722 greg 2.39 register long lc = av2->t - av1->t;
723 greg 2.38 return(lc<0 ? -1 : lc>0 ? 1 : 0);
724 greg 2.26 }
725    
726    
727 greg 2.47 /* GW NOTE 2002/10/3:
728     * I used to compare AMBVAL pointers, but found that this was the
729     * cause of a serious consistency error with gcc, since the optimizer
730     * uses some dangerous trick in pointer subtraction that
731     * assumes pointers differ by exact struct size increments.
732     */
733 greg 2.26 static int
734     aposcmp(avp1, avp2) /* compare ambient value positions */
735 greg 2.47 const void *avp1, *avp2;
736 greg 2.26 {
737 greg 2.47 register long diff = *(char * const *)avp1 - *(char * const *)avp2;
738     if (diff < 0)
739     return(-1);
740     return(diff > 0);
741 greg 2.26 }
742    
743 greg 2.39 #if 1
744 greg 2.27 static int
745     avlmemi(avaddr) /* find list position from address */
746     AMBVAL *avaddr;
747     {
748     register AMBVAL **avlpp;
749    
750     avlpp = (AMBVAL **)bsearch((char *)&avaddr, (char *)avlist2,
751     nambvals, sizeof(AMBVAL *), aposcmp);
752     if (avlpp == NULL)
753     error(CONSISTENCY, "address not found in avlmemi");
754     return(avlpp - avlist2);
755     }
756     #else
757     #define avlmemi(avaddr) ((AMBVAL **)bsearch((char *)&avaddr,(char *)avlist2, \
758     nambvals,sizeof(AMBVAL *),aposcmp) - avlist2)
759     #endif
760    
761    
762 greg 2.47 static void
763 greg 2.26 sortambvals(always) /* resort ambient values */
764     int always;
765     {
766     AMBTREE oldatrunk;
767     AMBVAL tav, *tap, *pnext;
768     register int i, j;
769 greg 2.28 /* see if it's time yet */
770 greg 2.40 if (!always && (ambclock++ < lastsort+sortintvl ||
771 greg 2.28 nambvals < SORT_THRESH))
772     return;
773 greg 2.26 /*
774     * The idea here is to minimize memory thrashing
775     * in VM systems by improving reference locality.
776     * We do this by periodically sorting our stored ambient
777     * values in memory in order of most recently to least
778     * recently accessed. This ordering was chosen so that new
779     * ambient values (which tend to be less important) go into
780     * higher memory with the infrequently accessed values.
781     * Since we expect our values to need sorting less
782     * frequently as the process continues, we double our
783     * waiting interval after each call.
784     * This routine is also called by setambacc() with
785     * the "always" parameter set to 1 so that the ambient
786     * tree will be rebuilt with the new accuracy parameter.
787     */
788 greg 2.27 if (tracktime) { /* allocate pointer arrays to sort */
789 greg 2.26 avlist2 = (AMBVAL **)malloc(nambvals*sizeof(AMBVAL *));
790 greg 2.39 avlist1 = (struct avl *)malloc(nambvals*sizeof(struct avl));
791     } else {
792     avlist2 = NULL;
793     avlist1 = NULL;
794     }
795     if (avlist1 == NULL) { /* no time tracking -- rebuild tree? */
796     if (avlist2 != NULL)
797 greg 2.47 free((void *)avlist2);
798 greg 2.27 if (always) { /* rebuild without sorting */
799     copystruct(&oldatrunk, &atrunk);
800     atrunk.alist = NULL;
801     atrunk.kid = NULL;
802     unloadatree(&oldatrunk, avinsert);
803     }
804 greg 2.26 } else { /* sort memory by last access time */
805     /*
806     * Sorting memory is tricky because it isn't contiguous.
807     * We have to sort an array of pointers by MRA and also
808     * by memory position. We then copy values in "loops"
809     * to minimize memory hits. Nevertheless, we will visit
810 greg 2.27 * everyone at least twice, and this is an expensive process
811 greg 2.26 * when we're thrashing, which is when we need to do it.
812     */
813 greg 2.27 #ifdef DEBUG
814 greg 2.29 sprintf(errmsg, "sorting %u ambient values at ambclock=%lu...",
815     nambvals, ambclock);
816 greg 2.27 eputs(errmsg);
817     #endif
818     i_avlist = 0;
819     unloadatree(&atrunk, av2list); /* empty current tree */
820     #ifdef DEBUG
821     if (i_avlist < nambvals)
822     error(CONSISTENCY, "missing ambient values in sortambvals");
823     #endif
824 greg 2.39 qsort((char *)avlist1, nambvals, sizeof(struct avl), alatcmp);
825 greg 2.26 qsort((char *)avlist2, nambvals, sizeof(AMBVAL *), aposcmp);
826     for (i = 0; i < nambvals; i++) {
827 greg 2.39 if (avlist1[i].p == NULL)
828 greg 2.26 continue;
829     tap = avlist2[i];
830     copystruct(&tav, tap);
831 greg 2.39 for (j = i; (pnext = avlist1[j].p) != tap;
832 greg 2.27 j = avlmemi(pnext)) {
833 greg 2.26 copystruct(avlist2[j], pnext);
834     avinsert(avlist2[j]);
835 greg 2.39 avlist1[j].p = NULL;
836 greg 2.26 }
837     copystruct(avlist2[j], &tav);
838     avinsert(avlist2[j]);
839 greg 2.39 avlist1[j].p = NULL;
840 greg 2.26 }
841 greg 2.47 free((void *)avlist1);
842     free((void *)avlist2);
843 greg 2.28 /* compute new sort interval */
844     sortintvl = ambclock - lastsort;
845 greg 2.32 if (sortintvl >= MAX_SORT_INTVL/2)
846 greg 2.28 sortintvl = MAX_SORT_INTVL;
847     else
848 greg 2.26 sortintvl <<= 1; /* wait twice as long next */
849 greg 2.27 #ifdef DEBUG
850     eputs("done\n");
851     #endif
852 greg 2.26 }
853     if (ambclock >= MAXACLOCK)
854     ambclock = MAXACLOCK/2;
855     lastsort = ambclock;
856 greg 2.20 }
857    
858    
859 greg 2.18 #ifdef F_SETLKW
860 greg 2.10
861 greg 2.47 static void
862 greg 2.19 aflock(typ) /* lock/unlock ambient file */
863     int typ;
864     {
865     static struct flock fls; /* static so initialized to zeroes */
866    
867     fls.l_type = typ;
868     if (fcntl(fileno(ambfp), F_SETLKW, &fls) < 0)
869     error(SYSTEM, "cannot (un)lock ambient file");
870     }
871    
872    
873 greg 2.16 int
874 greg 2.7 ambsync() /* synchronize ambient file */
875     {
876 greg 2.15 long flen;
877 greg 2.12 AMBVAL avs;
878 greg 2.7 register int n;
879 greg 2.16
880     if (nunflshed == 0)
881     return(0);
882 greg 2.19 if (lastpos < 0) /* initializing (locked in initambfile) */
883     goto syncend;
884 greg 2.7 /* gain exclusive access */
885 greg 2.19 aflock(F_WRLCK);
886 greg 2.7 /* see if file has grown */
887 greg 2.47 if ((flen = lseek(fileno(ambfp), (off_t)0L, 2)) < 0)
888 greg 2.21 goto seekerr;
889 greg 2.15 if (n = flen - lastpos) { /* file has grown */
890 greg 2.17 if (ambinp == NULL) { /* use duplicate filedes */
891     ambinp = fdopen(dup(fileno(ambfp)), "r");
892 greg 2.14 if (ambinp == NULL)
893 greg 2.17 error(SYSTEM, "fdopen failed in ambsync");
894 greg 2.14 }
895 greg 2.15 if (fseek(ambinp, lastpos, 0) < 0)
896 greg 2.21 goto seekerr;
897 greg 2.15 while (n >= AMBVALSIZ) { /* load contributed values */
898 greg 2.37 if (!readambval(&avs, ambinp)) {
899     sprintf(errmsg,
900 greg 2.47 "ambient file \"%s\" corrupted near character %ld",
901     ambfile, flen - n);
902 greg 2.37 error(WARNING, errmsg);
903     break;
904     }
905 greg 2.21 avinsert(avstore(&avs));
906 greg 2.15 n -= AMBVALSIZ;
907     }
908 greg 2.22 /*** seek always as safety measure
909     if (n) ***/ /* alignment */
910 greg 2.47 if (lseek(fileno(ambfp), (off_t)(flen-n), 0) < 0)
911 greg 2.21 goto seekerr;
912 greg 2.7 }
913 greg 2.21 #ifdef DEBUG
914     if (ambfp->_ptr - ambfp->_base != nunflshed*AMBVALSIZ) {
915     sprintf(errmsg, "ambient file buffer at %d rather than %d",
916     ambfp->_ptr - ambfp->_base,
917     nunflshed*AMBVALSIZ);
918     error(CONSISTENCY, errmsg);
919     }
920     #endif
921 greg 2.15 syncend:
922 greg 2.7 n = fflush(ambfp); /* calls write() at last */
923 greg 2.47 if ((lastpos = lseek(fileno(ambfp), (off_t)0L, 1)) < 0)
924 greg 2.21 goto seekerr;
925 greg 2.19 aflock(F_UNLCK); /* release file */
926 greg 2.16 nunflshed = 0;
927 greg 2.7 return(n);
928 greg 2.21 seekerr:
929     error(SYSTEM, "seek failed in ambsync");
930 greg 2.18 }
931    
932     #else
933    
934     int
935     ambsync() /* flush ambient file */
936     {
937     if (nunflshed == 0)
938     return(0);
939     nunflshed = 0;
940     return(fflush(ambfp));
941 greg 1.1 }
942 greg 2.10
943     #endif