ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambient.c
(Generate patch)

Comparing ray/src/rt/ambient.c (file contents):
Revision 1.13 by greg, Thu Jun 6 10:48:50 1991 UTC vs.
Revision 2.28 by greg, Sun Apr 30 13:24:36 1995 UTC

# Line 1 | Line 1
1 < /* Copyright (c) 1986 Regents of the University of California */
1 > /* Copyright (c) 1995 Regents of the University of California */
2  
3   #ifndef lint
4   static char SCCSid[] = "$SunId$ LBL";
# Line 6 | Line 6 | static char SCCSid[] = "$SunId$ LBL";
6  
7   /*
8   *  ambient.c - routines dealing with ambient (inter-reflected) component.
9 *
10 *  The macro AMBFLUSH (if defined) is the number of ambient values
11 *      to wait before flushing to the ambient file.
12 *
13 *     5/9/86
9   */
10  
11   #include  "ray.h"
# Line 19 | Line 14 | static char SCCSid[] = "$SunId$ LBL";
14  
15   #include  "otypes.h"
16  
17 + #include  "ambient.h"
18 +
19   #include  "random.h"
20  
21 < #define  OCTSCALE       0.5     /* ceil((valid rad.)/(cube size)) */
21 > #define  OCTSCALE       0.5     /* ceil((valid rad.)/(cube size)) */
22  
23 + typedef struct ambtree {
24 +        AMBVAL  *alist;         /* ambient value list */
25 +        struct ambtree  *kid;   /* 8 child nodes */
26 + }  AMBTREE;                     /* ambient octree */
27 +
28   extern CUBE  thescene;          /* contains space boundaries */
29  
30 < extern COLOR  ambval;           /* global ambient component */
29 < extern double  ambacc;          /* ambient accuracy */
30 < extern int  ambres;             /* ambient resolution */
31 < extern int  ambdiv;             /* number of divisions for calculation */
32 < extern int  ambssamp;           /* number of super-samples */
33 < extern int  ambounce;           /* number of ambient bounces */
34 < extern char  *amblist[];        /* ambient include/exclude list */
35 < extern int  ambincl;            /* include == 1, exclude == 0 */
30 > extern char  *shm_boundary;     /* memory sharing boundary */
31  
32 < #define  MAXASET        511     /* maximum number of elements in ambient set */
33 < OBJECT  ambset[MAXASET+1]={0};  /* ambient include/exclude set */
32 > #define  MAXASET        511     /* maximum number of elements in ambient set */
33 > OBJECT  ambset[MAXASET+1]={0};  /* ambient include/exclude set */
34  
35 < double  maxarad;                /* maximum ambient radius */
36 < double  minarad;                /* minimum ambient radius */
35 > double  maxarad;                /* maximum ambient radius */
36 > double  minarad;                /* minimum ambient radius */
37  
38 < /*
44 < * Since we've defined our vectors as float below to save space,
45 < * watch out for changes in the definitions of VCOPY() and DOT().
46 < */
47 < typedef struct ambval {
48 <        float  pos[3];          /* position in space */
49 <        float  dir[3];          /* normal direction */
50 <        int  lvl;               /* recursion level of parent ray */
51 <        float  weight;          /* weight of parent ray */
52 <        COLOR  val;             /* computed ambient value */
53 <        float  rad;             /* validity radius */
54 <        struct ambval  *next;   /* next in list */
55 < }  AMBVAL;                      /* ambient value */
38 > static AMBTREE  atrunk;         /* our ambient trunk node */
39  
40 < typedef struct ambtree {
41 <        AMBVAL  *alist;         /* ambient value list */
59 <        struct ambtree  *kid;   /* 8 child nodes */
60 < }  AMBTREE;                     /* ambient octree */
40 > static FILE  *ambfp = NULL;     /* ambient file pointer */
41 > static int  nunflshed = 0;      /* number of unflushed ambient values */
42  
43 < typedef struct {
44 <        float  k;               /* error contribution per sample */
45 <        COLOR  v;               /* ray sum */
46 <        int  n;                 /* number of samples */
47 <        short  t, p;            /* theta, phi indices */
48 < }  AMBSAMP;                     /* ambient sample */
43 > #ifndef SORT_THRESH
44 > #ifdef BIGMEM
45 > #define SORT_THRESH     ((9L<<20)/sizeof(AMBVAL))
46 > #else
47 > #define SORT_THRESH     ((3L<<20)/sizeof(AMBVAL))
48 > #endif
49 > #endif
50 > #ifndef SORT_INTVL
51 > #define SORT_INTVL      (SORT_THRESH*32)
52 > #endif
53 > #ifndef MAX_SORT_INTVL
54 > #define MAX_SORT_INTVL  (SORT_INTVL<<8)
55 > #endif
56  
57 < static AMBTREE  atrunk;         /* our ambient trunk node */
57 > static unsigned long  ambclock = 0;     /* ambient access clock */
58 > static unsigned int  nambvals = 0;      /* number of stored ambient values */
59 > static unsigned long  lastsort = 0;     /* time of last value sort */
60 > static long  sortintvl = SORT_INTVL;    /* time until next sort */
61  
62 < static FILE  *ambfp = NULL;     /* ambient file pointer */
62 > #define MAXACLOCK       (1L<<30)        /* clock turnover value */
63 >        /*
64 >         * Track access times unless we are sharing ambient values
65 >         * through memory on a multiprocessor, when we want to avoid
66 >         * claiming our own memory (copy on write).
67 >         */
68 > #define tracktime       (shm_boundary == NULL || ambfp == NULL)
69  
70 < #define  newambval()    (AMBVAL *)bmalloc(sizeof(AMBVAL))
70 > #define  AMBFLUSH       (BUFSIZ/AMBVALSIZ)
71  
72 < #define  newambtree()   (AMBTREE *)calloc(8, sizeof(AMBTREE))
72 > #define  newambval()    (AMBVAL *)bmalloc(sizeof(AMBVAL))
73  
74 < double  sumambient(), doambient(), makeambient();
74 > extern long  ftell(), lseek();
75 > static int  initambfile(), avsave(), avinsert(), sortambvals();
76 > static AMBVAL  *avstore();
77 > #ifdef  F_SETLKW
78 > static  aflock();
79 > #endif
80  
81  
82 < setambient(afile)                       /* initialize calculation */
83 < char  *afile;
82 > setambres(ar)                           /* set ambient resolution */
83 > int  ar;
84   {
85 <        long  ftell();
86 <        AMBVAL  amb;
85 >        ambres = ar < 0 ? 0 : ar;               /* may be done already */
86 >                                                /* set min & max radii */
87 >        if (ar <= 0) {
88 >                minarad = 0;
89 >                maxarad = thescene.cusize / 2.0;
90 >        } else {
91 >                minarad = thescene.cusize / ar;
92 >                maxarad = 16 * minarad;                 /* heuristic */
93 >                if (maxarad > thescene.cusize / 2.0)
94 >                        maxarad = thescene.cusize / 2.0;
95 >        }
96 >        if (minarad <= FTINY)
97 >                minarad = 10*FTINY;
98 >        if (maxarad <= minarad)
99 >                maxarad = 64 * minarad;
100 > }
101  
86        maxarad = thescene.cusize / 2.0;                /* maximum radius */
87                                                        /* minimum radius */
88        minarad = ambres > 0 ? thescene.cusize/ambres : 0.0;
102  
103 <                                        /* open ambient file */
104 <        if (afile != NULL)
105 <                if ((ambfp = fopen(afile, "r+")) != NULL) {
106 <                        while (fread((char *)&amb,sizeof(AMBVAL),1,ambfp) == 1)
107 <                                avinsert(&amb, &atrunk, thescene.cuorg,
108 <                                                thescene.cusize);
109 <                                                        /* align */
110 <                        fseek(ambfp, -(ftell(ambfp)%sizeof(AMBVAL)), 1);
111 <                } else if ((ambfp = fopen(afile, "w")) == NULL) {
112 <                        sprintf(errmsg, "cannot open ambient file \"%s\"",
113 <                                        afile);
114 <                        error(SYSTEM, errmsg);
115 <                }
103 > setambacc(newa)                         /* set ambient accuracy */
104 > double  newa;
105 > {
106 >        static double  oldambacc = -1.0;
107 >
108 >        ambacc = newa < 0.0 ? 0.0 : newa;       /* may be done already */
109 >        if (oldambacc < -FTINY)
110 >                oldambacc = ambacc;     /* do nothing first call */
111 >        if (fabs(newa - oldambacc) < 0.01)
112 >                return;                 /* insignificant -- don't bother */
113 >        if (ambacc <= FTINY)
114 >                return;                 /* cannot build new tree */
115 >                                        /* else need to rebuild tree */
116 >        sortambvals(1);
117 >        oldambacc = ambacc;             /* remeber setting for next call */
118   }
119  
120  
121 + setambient(afile)                       /* initialize calculation */
122 + char  *afile;
123 + {
124 +        long  headlen;
125 +        AMBVAL  amb;
126 +                                                /* init ambient limits */
127 +        setambres(ambres);
128 +        setambacc(ambacc);
129 +        if (afile == NULL)
130 +                return;
131 +        if (ambacc <= FTINY) {
132 +                sprintf(errmsg, "zero ambient accuracy so \"%s\" not opened",
133 +                                afile);
134 +                error(WARNING, errmsg);
135 +                return;
136 +        }
137 +                                                /* open ambient file */
138 +        if ((ambfp = fopen(afile, "r+")) != NULL) {
139 +                initambfile(0);
140 +                headlen = ftell(ambfp);
141 +                while (readambval(&amb, ambfp))
142 +                        avinsert(avstore(&amb));
143 +                                                /* align */
144 +                fseek(ambfp, -((ftell(ambfp)-headlen)%AMBVALSIZ), 1);
145 +        } else if ((ambfp = fopen(afile, "w+")) != NULL)
146 +                initambfile(1);
147 +        else {
148 +                sprintf(errmsg, "cannot open ambient file \"%s\"", afile);
149 +                error(SYSTEM, errmsg);
150 +        }
151 +        nunflshed++;    /* lie */
152 +        ambsync();
153 + }
154 +
155 +
156   ambnotify(obj)                  /* record new modifier */
157 < OBJECT  obj;
157 > OBJECT  obj;
158   {
159          static int  hitlimit = 0;
160 <        register OBJREC  *o = objptr(obj);
160 >        register OBJREC  *o = objptr(obj);
161          register char  **amblp;
162  
163          if (hitlimit || !ismodifier(o->otype))
# Line 130 | Line 180 | COLOR  acol;
180   register RAY  *r;
181   {
182          static int  rdepth = 0;                 /* ambient recursion */
183 <        double  wsum;
183 >        double  d;
184  
135        rdepth++;                               /* increment level */
136
185          if (ambdiv <= 0)                        /* no ambient calculation */
186                  goto dumbamb;
187                                                  /* check number of bounces */
188 <        if (rdepth > ambounce)
188 >        if (rdepth >= ambounce)
189                  goto dumbamb;
190                                                  /* check ambient list */
191          if (ambincl != -1 && r->ro != NULL &&
# Line 145 | Line 193 | register RAY  *r;
193                  goto dumbamb;
194  
195          if (ambacc <= FTINY) {                  /* no ambient storage */
196 <                if (doambient(acol, r) == 0.0)
196 >                rdepth++;
197 >                d = doambient(acol, r, r->rweight, NULL, NULL);
198 >                rdepth--;
199 >                if (d == 0.0)
200                          goto dumbamb;
201 <                goto done;
201 >                return;
202          }
203 +                                                /* resort memory? */
204 +        sortambvals(0);
205                                                  /* get ambient value */
206          setcolor(acol, 0.0, 0.0, 0.0);
207 <        wsum = sumambient(acol, r, &atrunk, thescene.cuorg, thescene.cusize);
208 <        if (wsum > FTINY)
209 <                scalecolor(acol, 1.0/wsum);
210 <        else if (makeambient(acol, r) == 0.0)
211 <                goto dumbamb;
212 <        goto done;
213 <
207 >        d = sumambient(acol, r, rdepth,
208 >                        &atrunk, thescene.cuorg, thescene.cusize);
209 >        if (d > FTINY)
210 >                scalecolor(acol, 1.0/d);
211 >        else {
212 >                d = makeambient(acol, r, rdepth++);
213 >                rdepth--;
214 >        }
215 >        if (d > FTINY)
216 >                return;
217   dumbamb:                                        /* return global value */
218          copycolor(acol, ambval);
163 done:                                           /* must finish here! */
164        rdepth--;
219   }
220  
221  
222   double
223 < sumambient(acol, r, at, c0, s)          /* get interpolated ambient value */
223 > sumambient(acol, r, al, at, c0, s)      /* get interpolated ambient value */
224   COLOR  acol;
225   register RAY  *r;
226 < AMBTREE  *at;
226 > int  al;
227 > AMBTREE  *at;
228   FVECT  c0;
229 < double  s;
229 > double  s;
230   {
231 <        extern double  sqrt();
177 <        double  d, e1, e2, wt, wsum;
231 >        double  d, e1, e2, wt, wsum;
232          COLOR  ct;
233          FVECT  ck0;
234          int  i;
235          register int  j;
236 <        register AMBVAL  *av;
236 >        register AMBVAL  *av;
237                                          /* do this node */
238          wsum = 0.0;
239          for (av = at->alist; av != NULL; av = av->next) {
240 +                if (tracktime)
241 +                        av->latick = ambclock++;
242                  /*
243 <                 *  Ray strength test.
243 >                 *  Ambient level test.
244                   */
245 <                if (av->lvl > r->rlvl || av->weight < r->rweight-FTINY)
245 >                if (av->lvl > al)       /* list sorted, so this works */
246 >                        break;
247 >                if (av->weight < r->rweight-FTINY)
248                          continue;
249                  /*
250                   *  Ambient radius test.
# Line 213 | Line 271 | double  s;
271                  for (j = 0; j < 3; j++)
272                          d += (r->rop[j] - av->pos[j]) *
273                                          (av->dir[j] + r->ron[j]);
274 <                if (d*0.5 < -minarad*ambacc)
274 >                if (d*0.5 < -minarad*ambacc-.001)
275                          continue;
276                  /*
277                   *  Jittering final test reduces image artifacts.
278                   */
279                  wt = sqrt(e1) + sqrt(e2);
280 <                wt *= .9 + .2*frandom();
280 >                wt *= .9 + .2*urand(9015+samplendx);
281                  if (wt > ambacc)
282                          continue;
283                  if (wt <= 1e-3)
# Line 227 | Line 285 | double  s;
285                  else
286                          wt = 1.0 / wt;
287                  wsum += wt;
288 <                copycolor(ct, av->val);
288 >                extambient(ct, av, r->rop, r->ron);
289                  scalecolor(ct, wt);
290                  addcolor(acol, ct);
291          }
# Line 246 | Line 304 | double  s;
304                                  break;
305                  }
306                  if (j == 3)
307 <                        wsum += sumambient(acol, r, at->kid+i, ck0, s);
307 >                        wsum += sumambient(acol, r, al, at->kid+i, ck0, s);
308          }
309          return(wsum);
310   }
311  
312  
313   double
314 < makeambient(acol, r)            /* make a new ambient value */
314 > makeambient(acol, r, al)        /* make a new ambient value */
315   COLOR  acol;
316   register RAY  *r;
317 + int  al;
318   {
319 <        AMBVAL  amb;
320 <
321 <        amb.rad = doambient(acol, r);           /* compute ambient */
319 >        AMBVAL  amb;
320 >        FVECT   gp, gd;
321 >                                                /* compute weight */
322 >        amb.weight = pow(AVGREFL, (double)al);
323 >        if (r->rweight < 0.2*amb.weight)        /* heuristic */
324 >                amb.weight = r->rweight;
325 >                                                /* compute ambient */
326 >        amb.rad = doambient(acol, r, amb.weight, gp, gd);
327          if (amb.rad == 0.0)
328                  return(0.0);
329                                                  /* store it */
330          VCOPY(amb.pos, r->rop);
331          VCOPY(amb.dir, r->ron);
332 <        amb.lvl = r->rlvl;
269 <        amb.weight = r->rweight;
332 >        amb.lvl = al;
333          copycolor(amb.val, acol);
334 +        VCOPY(amb.gpos, gp);
335 +        VCOPY(amb.gdir, gd);
336                                                  /* insert into tree */
337 <        avinsert(&amb, &atrunk, thescene.cuorg, thescene.cusize);
273 <        avsave(&amb);                           /* write to file */
337 >        avsave(&amb);                           /* and save to file */
338          return(amb.rad);
339   }
340  
341  
342 < double
343 < doambient(acol, r)                      /* compute ambient component */
344 < COLOR  acol;
345 < register RAY  *r;
342 > extambient(cr, ap, pv, nv)              /* extrapolate value at pv, nv */
343 > COLOR  cr;
344 > register AMBVAL  *ap;
345 > FVECT  pv, nv;
346   {
347 <        extern int  ambcmp();
348 <        extern double  sin(), cos(), sqrt();
349 <        int  hlist[4];
286 <        double  phi, xd, yd, zd;
287 <        double  b, b2;
288 <        register AMBSAMP  *div;
289 <        AMBSAMP  dnew;
290 <        RAY  ar;
291 <        FVECT  ux, uy;
292 <        double  arad;
293 <        int  ndivs, nt, np, ns, ne, i, j;
294 <        register int  k;
347 >        FVECT  v1, v2;
348 >        register int  i;
349 >        double  d;
350  
351 <        setcolor(acol, 0.0, 0.0, 0.0);
352 <                                        /* set number of divisions */
353 <        nt = sqrt(ambdiv * r->rweight * 0.5) + 0.5;
354 <        np = 2 * nt;
355 <        ndivs = nt * np;
356 <                                        /* check first */
357 <        if (ndivs == 0 || rayorigin(&ar, r, AMBIENT, 0.5) < 0)
358 <                return(0.0);
359 <                                        /* set number of super-samples */
360 <        ns = ambssamp * r->rweight + 0.5;
361 <        if (ns > 0) {
307 <                div = (AMBSAMP *)malloc(ndivs*sizeof(AMBSAMP));
308 <                if (div == NULL)
309 <                        error(SYSTEM, "out of memory in doambient");
310 <        } else
311 <                div = NULL;
312 <                                        /* make axes */
313 <        uy[0] = uy[1] = uy[2] = 0.0;
314 <        for (k = 0; k < 3; k++)
315 <                if (r->ron[k] < 0.6 && r->ron[k] > -0.6)
316 <                        break;
317 <        uy[k] = 1.0;
318 <        fcross(ux, r->ron, uy);
319 <        normalize(ux);
320 <        fcross(uy, ux, r->ron);
321 <                                        /* set up urand */
322 <        hlist[0] = r->rno;
323 <                                                /* sample divisions */
324 <        arad = 0.0;
325 <        ne = 0;
326 <        for (i = 0; i < nt; i++) {
327 <                hlist[1] = i;
328 <                for (j = 0; j < np; j++) {
329 <                        rayorigin(&ar, r, AMBIENT, 0.5);        /* pretested */
330 <                        hlist[2] = j;
331 <                        hlist[3] = 0;
332 <                        zd = sqrt((i+urand(ilhash(hlist,4)))/nt);
333 <                        hlist[3] = 1;
334 <                        phi = 2.0*PI * (j+urand(ilhash(hlist,4)))/np;
335 <                        xd = cos(phi) * zd;
336 <                        yd = sin(phi) * zd;
337 <                        zd = sqrt(1.0 - zd*zd);
338 <                        for (k = 0; k < 3; k++)
339 <                                ar.rdir[k] = xd*ux[k]+yd*uy[k]+zd*r->ron[k];
340 <                        dimlist[ndims++] = i*np + j + 38813;
341 <                        rayvalue(&ar);
342 <                        ndims--;
343 <                        if (ar.rot < FHUGE)
344 <                                arad += 1.0 / ar.rot;
345 <                        if (div != NULL) {              /* save division */
346 <                                div[ne].k = 0.0;
347 <                                copycolor(div[ne].v, ar.rcol);
348 <                                div[ne].n = 0;
349 <                                div[ne].t = i; div[ne].p = j;
350 <                                                        /* sum errors */
351 <                                b = bright(ar.rcol);
352 <                                if (i > 0) {            /* from above */
353 <                                        b2 = bright(div[ne-np].v) - b;
354 <                                        b2 *= b2 * 0.25;
355 <                                        div[ne].k += b2;
356 <                                        div[ne].n++;
357 <                                        div[ne-np].k += b2;
358 <                                        div[ne-np].n++;
359 <                                }
360 <                                if (j > 0) {            /* from behind */
361 <                                        b2 = bright(div[ne-1].v) - b;
362 <                                        b2 *= b2 * 0.25;
363 <                                        div[ne].k += b2;
364 <                                        div[ne].n++;
365 <                                        div[ne-1].k += b2;
366 <                                        div[ne-1].n++;
367 <                                }
368 <                                if (j == np-1) {        /* around */
369 <                                        b2 = bright(div[ne-(np-1)].v) - b;
370 <                                        b2 *= b2 * 0.25;
371 <                                        div[ne].k += b2;
372 <                                        div[ne].n++;
373 <                                        div[ne-(np-1)].k += b2;
374 <                                        div[ne-(np-1)].n++;
375 <                                }
376 <                                ne++;
377 <                        } else
378 <                                addcolor(acol, ar.rcol);
379 <                }
351 >        d = 1.0;                        /* zeroeth order */
352 >                                        /* gradient due to translation */
353 >        for (i = 0; i < 3; i++)
354 >                d += ap->gpos[i]*(pv[i]-ap->pos[i]);
355 >                                        /* gradient due to rotation */
356 >        VCOPY(v1, ap->dir);
357 >        fcross(v2, v1, nv);
358 >        d += DOT(ap->gdir, v2);
359 >        if (d <= 0.0) {
360 >                setcolor(cr, 0.0, 0.0, 0.0);
361 >                return;
362          }
363 <        for (k = 0; k < ne; k++) {              /* compute errors */
364 <                if (div[k].n > 1)
383 <                        div[k].k /= div[k].n;
384 <                div[k].n = 1;
385 <        }
386 <                                                /* sort the divisions */
387 <        qsort(div, ne, sizeof(AMBSAMP), ambcmp);
388 <                                                /* skim excess */
389 <        while (ne > ns) {
390 <                ne--;
391 <                addcolor(acol, div[ne].v);
392 <        }
393 <                                                /* super-sample */
394 <        for (i = ns; i > 0; i--) {
395 <                rayorigin(&ar, r, AMBIENT, 0.5);        /* pretested */
396 <                hlist[1] = div[0].t;
397 <                hlist[2] = div[0].p;
398 <                hlist[3] = 0;
399 <                zd = sqrt((div[0].t+urand(ilhash(hlist,4)+div[0].n))/nt);
400 <                hlist[3] = 1;
401 <                phi = 2.0*PI * (div[0].p+urand(ilhash(hlist,4)+div[0].n))/np;
402 <                xd = cos(phi) * zd;
403 <                yd = sin(phi) * zd;
404 <                zd = sqrt(1.0 - zd*zd);
405 <                for (k = 0; k < 3; k++)
406 <                        ar.rdir[k] = xd*ux[k]+yd*uy[k]+zd*r->ron[k];
407 <                dimlist[ndims++] = div[0].t*np + div[0].p + 38813;
408 <                rayvalue(&ar);
409 <                ndims--;
410 <                rayvalue(&ar);
411 <                if (ar.rot < FHUGE)
412 <                        arad += 1.0 / ar.rot;
413 <                                                /* recompute error */
414 <                copycolor(dnew.v, div[0].v);
415 <                addcolor(dnew.v, ar.rcol);
416 <                dnew.n = div[0].n + 1;
417 <                dnew.t = div[0].t; dnew.p = div[0].p;
418 <                b2 = bright(dnew.v)/dnew.n - bright(ar.rcol);
419 <                b2 = b2*b2 + div[0].k*(div[0].n*div[0].n);
420 <                dnew.k = b2/(dnew.n*dnew.n);
421 <                                                /* reinsert */
422 <                for (k = 0; k < ne-1 && dnew.k < div[k+1].k; k++)
423 <                        copystruct(&div[k], &div[k+1]);
424 <                copystruct(&div[k], &dnew);
425 <
426 <                if (ne >= i) {          /* extract darkest division */
427 <                        ne--;
428 <                        if (div[ne].n > 1) {
429 <                                b = 1.0/div[ne].n;
430 <                                scalecolor(div[ne].v, b);
431 <                                div[ne].n = 1;
432 <                        }
433 <                        addcolor(acol, div[ne].v);
434 <                }
435 <        }
436 <        scalecolor(acol, 1.0/ndivs);
437 <        if (arad <= FTINY)
438 <                arad = FHUGE;
439 <        else
440 <                arad = (ndivs+ns) / arad / sqrt(r->rweight);
441 <        if (arad > maxarad)
442 <                arad = maxarad;
443 <        else if (arad < minarad)
444 <                arad = minarad;
445 <        if (div != NULL)
446 <                free((char *)div);
447 <        return(arad);
363 >        copycolor(cr, ap->val);
364 >        scalecolor(cr, d);
365   }
366  
367  
368 < static int
369 < ambcmp(d1, d2)                          /* decreasing order */
370 < AMBSAMP  *d1, *d2;
368 > static
369 > initambfile(creat)              /* initialize ambient file */
370 > int  creat;
371   {
372 <        if (d1->k < d2->k)
373 <                return(1);
374 <        if (d1->k > d2->k)
375 <                return(-1);
376 <        return(0);
372 >        extern char  *progname, *octname, VersionID[];
373 >
374 > #ifdef  F_SETLKW
375 >        aflock(creat ? F_WRLCK : F_RDLCK);
376 > #endif
377 > #ifdef MSDOS
378 >        setmode(fileno(ambfp), O_BINARY);
379 > #endif
380 >        setbuf(ambfp, bmalloc(BUFSIZ+8));
381 >        if (creat) {                    /* new file */
382 >                newheader("RADIANCE", ambfp);
383 >                fprintf(ambfp, "%s -av %g %g %g -ab %d -aa %g ",
384 >                                progname, colval(ambval,RED),
385 >                                colval(ambval,GRN), colval(ambval,BLU),
386 >                                ambounce, ambacc);
387 >                fprintf(ambfp, "-ad %d -as %d -ar %d %s\n",
388 >                                ambdiv, ambssamp, ambres,
389 >                                octname==NULL ? "" : octname);
390 >                fprintf(ambfp, "SOFTWARE= %s\n", VersionID);
391 >                fputformat(AMBFMT, ambfp);
392 >                putc('\n', ambfp);
393 >                putambmagic(ambfp);
394 >        } else if (checkheader(ambfp, AMBFMT, NULL) < 0 || !hasambmagic(ambfp))
395 >                error(USER, "bad ambient file");
396   }
397  
398  
399   static
400 < avsave(av)                              /* save an ambient value */
401 < AMBVAL  *av;
400 > avsave(av)                              /* insert and save an ambient value */
401 > AMBVAL  *av;
402   {
403 < #ifdef  AMBFLUSH
468 <        static int  nunflshed = 0;
469 < #endif
403 >        avinsert(avstore(av));
404          if (ambfp == NULL)
405                  return;
406 <        if (fwrite((char *)av, sizeof(AMBVAL), 1, ambfp) != 1)
406 >        if (writambval(av, ambfp) < 0)
407                  goto writerr;
408 < #ifdef  AMBFLUSH
409 <        if (++nunflshed >= AMBFLUSH) {
476 <                if (fflush(ambfp) == EOF)
408 >        if (++nunflshed >= AMBFLUSH)
409 >                if (ambsync() == EOF)
410                          goto writerr;
478                nunflshed = 0;
479        }
480 #endif
411          return;
412   writerr:
413          error(SYSTEM, "error writing ambient file");
414   }
415  
416  
417 + static AMBVAL *
418 + avstore(aval)                           /* allocate memory and store aval */
419 + register AMBVAL  *aval;
420 + {
421 +        register AMBVAL  *av;
422 +
423 +        if ((av = newambval()) == NULL)
424 +                error(SYSTEM, "out of memory in avstore");
425 +        copystruct(av, aval);
426 +        av->latick = ambclock;
427 +        av->next = NULL;
428 +        nambvals++;
429 +        return(av);
430 + }
431 +
432 +
433 + #define ATALLOCSZ       512             /* #/8 trees to allocate at once */
434 +
435 + static AMBTREE  *atfreelist = NULL;     /* free ambient tree structures */
436 +
437 +
438   static
439 < avinsert(aval, at, c0, s)               /* insert ambient value in a tree */
440 < AMBVAL  *aval;
490 < register AMBTREE  *at;
491 < FVECT  c0;
492 < double  s;
439 > AMBTREE *
440 > newambtree()                            /* allocate 8 ambient tree structs */
441   {
442 +        register AMBTREE  *atp, *upperlim;
443 +
444 +        if (atfreelist == NULL) {       /* get more nodes */
445 +                atfreelist = (AMBTREE *)bmalloc(ATALLOCSZ*8*sizeof(AMBTREE));
446 +                if (atfreelist == NULL)
447 +                        return(NULL);
448 +                                        /* link new free list */
449 +                upperlim = atfreelist + 8*(ATALLOCSZ-1);
450 +                for (atp = atfreelist; atp < upperlim; atp += 8)
451 +                        atp->kid = atp + 8;
452 +                atp->kid = NULL;
453 +        }
454 +        atp = atfreelist;
455 +        atfreelist = atp->kid;
456 +        bzero((char *)atp, 8*sizeof(AMBTREE));
457 +        return(atp);
458 + }
459 +
460 +
461 + static
462 + freeambtree(atp)                        /* free 8 ambient tree structs */
463 + AMBTREE  *atp;
464 + {
465 +        atp->kid = atfreelist;
466 +        atfreelist = atp;
467 + }
468 +
469 +
470 + static
471 + avinsert(av)                            /* insert ambient value in our tree */
472 + register AMBVAL  *av;
473 + {
474 +        register AMBTREE  *at;
475 +        register AMBVAL  *ap;
476 +        AMBVAL  avh;
477          FVECT  ck0;
478 +        double  s;
479          int  branch;
496        register AMBVAL  *av;
480          register int  i;
481  
482 <        if ((av = newambval()) == NULL)
483 <                goto memerr;
484 <        copystruct(av, aval);
485 <        VCOPY(ck0, c0);
482 >        if (av->rad <= FTINY)
483 >                error(CONSISTENCY, "zero ambient radius in avinsert");
484 >        at = &atrunk;
485 >        VCOPY(ck0, thescene.cuorg);
486 >        s = thescene.cusize;
487          while (s*(OCTSCALE/2) > av->rad*ambacc) {
488                  if (at->kid == NULL)
489                          if ((at->kid = newambtree()) == NULL)
490 <                                goto memerr;
490 >                                error(SYSTEM, "out of memory in avinsert");
491                  s *= 0.5;
492                  branch = 0;
493                  for (i = 0; i < 3; i++)
# Line 513 | Line 497 | double  s;
497                          }
498                  at = at->kid + branch;
499          }
500 <        av->next = at->alist;
501 <        at->alist = av;
502 <        return;
503 < memerr:
504 <        error(SYSTEM, "out of memory in avinsert");
500 >        avh.next = at->alist;           /* order by increasing level */
501 >        for (ap = &avh; ap->next != NULL; ap = ap->next)
502 >                if (ap->next->lvl >= av->lvl)
503 >                        break;
504 >        av->next = ap->next;
505 >        ap->next = av;
506 >        at->alist = avh.next;
507   }
508 +
509 +
510 + static
511 + unloadatree(at, f)                      /* unload an ambient value tree */
512 + register AMBTREE  *at;
513 + int     (*f)();
514 + {
515 +        register AMBVAL  *av;
516 +        register int  i;
517 +                                        /* transfer values at this node */
518 +        for (av = at->alist; av != NULL; av = at->alist) {
519 +                at->alist = av->next;
520 +                (*f)(av);
521 +        }
522 +        if (at->kid == NULL)
523 +                return;
524 +        for (i = 0; i < 8; i++)         /* transfer and free children */
525 +                unloadatree(at->kid+i, f);
526 +        freeambtree(at->kid);
527 +        at->kid = NULL;
528 + }
529 +
530 +
531 + static AMBVAL   **avlist1, **avlist2;   /* ambient value lists for sorting */
532 + static int      i_avlist;               /* index for lists */
533 +
534 +
535 + static
536 + av2list(av)
537 + AMBVAL  *av;
538 + {
539 + #ifdef DEBUG
540 +        if (i_avlist >= nambvals)
541 +                error(CONSISTENCY, "too many ambient values in av2list1");
542 + #endif
543 +        avlist1[i_avlist] = avlist2[i_avlist] = av;
544 +        i_avlist++;
545 + }
546 +
547 +
548 + static int
549 + alatcmp(avp1, avp2)                     /* compare ambient values for MRA */
550 + AMBVAL  **avp1, **avp2;
551 + {
552 +        return((**avp2).latick - (**avp1).latick);
553 + }
554 +
555 +
556 + static int
557 + aposcmp(avp1, avp2)                     /* compare ambient value positions */
558 + AMBVAL  **avp1, **avp2;
559 + {
560 +        return(*avp1 - *avp2);
561 + }
562 +
563 +
564 + #ifdef DEBUG
565 + static int
566 + avlmemi(avaddr)                         /* find list position from address */
567 + AMBVAL  *avaddr;
568 + {
569 +        register AMBVAL  **avlpp;
570 +
571 +        avlpp = (AMBVAL **)bsearch((char *)&avaddr, (char *)avlist2,
572 +                        nambvals, sizeof(AMBVAL *), aposcmp);
573 +        if (avlpp == NULL)
574 +                error(CONSISTENCY, "address not found in avlmemi");
575 +        return(avlpp - avlist2);
576 + }
577 + #else
578 + #define avlmemi(avaddr) ((AMBVAL **)bsearch((char *)&avaddr,(char *)avlist2, \
579 +                                nambvals,sizeof(AMBVAL *),aposcmp) - avlist2)
580 + #endif
581 +
582 +
583 + static
584 + sortambvals(always)                     /* resort ambient values */
585 + int     always;
586 + {
587 +        AMBTREE  oldatrunk;
588 +        AMBVAL  tav, *tap, *pnext;
589 +        register int    i, j;
590 +                                        /* see if it's time yet */
591 +        if (!always && (ambclock < lastsort+sortintvl ||
592 +                        nambvals < SORT_THRESH))
593 +                return;
594 +        /*
595 +         * The idea here is to minimize memory thrashing
596 +         * in VM systems by improving reference locality.
597 +         * We do this by periodically sorting our stored ambient
598 +         * values in memory in order of most recently to least
599 +         * recently accessed.  This ordering was chosen so that new
600 +         * ambient values (which tend to be less important) go into
601 +         * higher memory with the infrequently accessed values.
602 +         *      Since we expect our values to need sorting less
603 +         * frequently as the process continues, we double our
604 +         * waiting interval after each call.
605 +         *      This routine is also called by setambacc() with
606 +         * the "always" parameter set to 1 so that the ambient
607 +         * tree will be rebuilt with the new accuracy parameter.
608 +         */
609 +        if (tracktime) {                /* allocate pointer arrays to sort */
610 +                avlist1 = (AMBVAL **)malloc(nambvals*sizeof(AMBVAL *));
611 +                avlist2 = (AMBVAL **)malloc(nambvals*sizeof(AMBVAL *));
612 +        } else
613 +                avlist1 = avlist2 = NULL;
614 +        if (avlist2 == NULL) {          /* no time tracking -- rebuild tree? */
615 +                if (avlist1 != NULL)
616 +                        free((char *)avlist1);
617 +                if (always) {           /* rebuild without sorting */
618 +                        copystruct(&oldatrunk, &atrunk);
619 +                        atrunk.alist = NULL;
620 +                        atrunk.kid = NULL;
621 +                        unloadatree(&oldatrunk, avinsert);
622 +                }
623 +        } else {                        /* sort memory by last access time */
624 +                /*
625 +                 * Sorting memory is tricky because it isn't contiguous.
626 +                 * We have to sort an array of pointers by MRA and also
627 +                 * by memory position.  We then copy values in "loops"
628 +                 * to minimize memory hits.  Nevertheless, we will visit
629 +                 * everyone at least twice, and this is an expensive process
630 +                 * when we're thrashing, which is when we need to do it.
631 +                 */
632 + #ifdef DEBUG
633 +                sprintf(errmsg, "sorting %u ambient values...", nambvals);
634 +                eputs(errmsg);
635 + #endif
636 +                i_avlist = 0;
637 +                unloadatree(&atrunk, av2list);  /* empty current tree */
638 + #ifdef DEBUG
639 +                if (i_avlist < nambvals)
640 +                        error(CONSISTENCY, "missing ambient values in sortambvals");
641 + #endif
642 +                qsort((char *)avlist1, nambvals, sizeof(AMBVAL *), alatcmp);
643 +                qsort((char *)avlist2, nambvals, sizeof(AMBVAL *), aposcmp);
644 +                for (i = 0; i < nambvals; i++) {
645 +                        if (avlist1[i] == NULL)
646 +                                continue;
647 +                        tap = avlist2[i];
648 +                        copystruct(&tav, tap);
649 +                        for (j = i; (pnext = avlist1[j]) != tap;
650 +                                        j = avlmemi(pnext)) {
651 +                                copystruct(avlist2[j], pnext);
652 +                                avinsert(avlist2[j]);
653 +                                avlist1[j] = NULL;
654 +                        }
655 +                        copystruct(avlist2[j], &tav);
656 +                        avinsert(avlist2[j]);
657 +                        avlist1[j] = NULL;
658 +                }
659 +                free((char *)avlist1);
660 +                free((char *)avlist2);
661 +                                                /* compute new sort interval */
662 +                sortintvl = ambclock - lastsort;
663 +                if (sortintvl > MAX_SORT_INTVL)
664 +                        sortintvl = MAX_SORT_INTVL;
665 +                else
666 +                        sortintvl <<= 1;        /* wait twice as long next */
667 + #ifdef DEBUG
668 +                eputs("done\n");
669 + #endif
670 +        }
671 +        if (ambclock >= MAXACLOCK)
672 +                ambclock = MAXACLOCK/2;
673 +        lastsort = ambclock;
674 + }
675 +
676 +
677 + #ifdef  F_SETLKW
678 +
679 + static
680 + aflock(typ)                     /* lock/unlock ambient file */
681 + int  typ;
682 + {
683 +        static struct flock  fls;       /* static so initialized to zeroes */
684 +
685 +        fls.l_type = typ;
686 +        if (fcntl(fileno(ambfp), F_SETLKW, &fls) < 0)
687 +                error(SYSTEM, "cannot (un)lock ambient file");
688 + }
689 +
690 +
691 + int
692 + ambsync()                       /* synchronize ambient file */
693 + {
694 +        static FILE  *ambinp = NULL;
695 +        static long  lastpos = -1;
696 +        long  flen;
697 +        AMBVAL  avs;
698 +        register int  n;
699 +
700 +        if (nunflshed == 0)
701 +                return(0);
702 +        if (lastpos < 0)        /* initializing (locked in initambfile) */
703 +                goto syncend;
704 +                                /* gain exclusive access */
705 +        aflock(F_WRLCK);
706 +                                /* see if file has grown */
707 +        if ((flen = lseek(fileno(ambfp), 0L, 2)) < 0)
708 +                goto seekerr;
709 +        if (n = flen - lastpos) {               /* file has grown */
710 +                if (ambinp == NULL) {           /* use duplicate filedes */
711 +                        ambinp = fdopen(dup(fileno(ambfp)), "r");
712 +                        if (ambinp == NULL)
713 +                                error(SYSTEM, "fdopen failed in ambsync");
714 +                }
715 +                if (fseek(ambinp, lastpos, 0) < 0)
716 +                        goto seekerr;
717 +                while (n >= AMBVALSIZ) {        /* load contributed values */
718 +                        readambval(&avs, ambinp);
719 +                        avinsert(avstore(&avs));
720 +                        n -= AMBVALSIZ;
721 +                }
722 +                /*** seek always as safety measure
723 +                if (n) ***/                     /* alignment */
724 +                        if (lseek(fileno(ambfp), flen-n, 0) < 0)
725 +                                goto seekerr;
726 +        }
727 + #ifdef  DEBUG
728 +        if (ambfp->_ptr - ambfp->_base != nunflshed*AMBVALSIZ) {
729 +                sprintf(errmsg, "ambient file buffer at %d rather than %d",
730 +                                ambfp->_ptr - ambfp->_base,
731 +                                nunflshed*AMBVALSIZ);
732 +                error(CONSISTENCY, errmsg);
733 +        }
734 + #endif
735 + syncend:
736 +        n = fflush(ambfp);                      /* calls write() at last */
737 +        if ((lastpos = lseek(fileno(ambfp), 0L, 1)) < 0)
738 +                goto seekerr;
739 +        aflock(F_UNLCK);                        /* release file */
740 +        nunflshed = 0;
741 +        return(n);
742 + seekerr:
743 +        error(SYSTEM, "seek failed in ambsync");
744 + }
745 +
746 + #else
747 +
748 + int
749 + ambsync()                       /* flush ambient file */
750 + {
751 +        if (nunflshed == 0)
752 +                return(0);
753 +        nunflshed = 0;
754 +        return(fflush(ambfp));
755 + }
756 +
757 + #endif

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines