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.2 by greg, Tue Feb 21 14:34:08 1989 UTC vs.
Revision 2.57 by greg, Fri Nov 5 17:36:55 2004 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines