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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines