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 2.80 by greg, Fri Apr 25 18:38:47 2014 UTC vs.
Revision 2.111 by greg, Thu Nov 18 19:38:21 2021 UTC

# Line 1 | Line 1
1 #ifndef lint
1   static const char       RCSid[] = "$Id$";
3 #endif
2   /*
3   *  ambient.c - routines dealing with ambient (inter-reflected) component.
4   *
# Line 14 | Line 12 | static const char      RCSid[] = "$Id$";
12   #include  "platform.h"
13   #include  "ray.h"
14   #include  "otypes.h"
15 + #include  "otspecial.h"
16   #include  "resolu.h"
17   #include  "ambient.h"
18   #include  "random.h"
19 + #include  "pmapamb.h"
20  
21   #ifndef  OCTSCALE
22   #define  OCTSCALE       1.0     /* ceil((valid rad.)/(cube size)) */
# Line 52 | Line 52 | static int  nunflshed = 0;     /* number of unflushed ambi
52   #endif
53  
54  
55 static double  qambacc = 0.;            /* ambient accuracy to the 1/4 power */
55   static double  avsum = 0.;              /* computed ambient value sum (log) */
56   static unsigned int  navsum = 0;        /* number of values in avsum */
57   static unsigned int  nambvals = 0;      /* total number of indirect values */
# Line 78 | Line 77 | static long  lastpos = -1;             /* last flush position */
77   #define  AMBFLUSH       (BUFSIZ/AMBVALSIZ)
78  
79   #define  newambval()    (AMBVAL *)malloc(sizeof(AMBVAL))
81 #define  freeav(av)     free((void *)av);
80  
81 + #define  tfunc(lwr, x, upr)     (((x)-(lwr))/((upr)-(lwr)))
82 +
83   static void initambfile(int creat);
84   static void avsave(AMBVAL *av);
85   static AMBVAL *avstore(AMBVAL  *aval);
# Line 96 | Line 96 | static int aposcmp(const void *avp1, const void *avp2)
96   static int avlmemi(AMBVAL *avaddr);
97   static void sortambvals(int always);
98  
99 + static int      plugaleak(RAY *r, AMBVAL *ap, FVECT anorm, double ang);
100 + static double   sumambient(COLOR acol, RAY *r, FVECT rn, int al,
101 +                                AMBTREE *at, FVECT c0, double s);
102 + static int      makeambient(COLOR acol, RAY *r, FVECT rn, int al);
103 + static int      extambient(COLOR cr, AMBVAL *ap, FVECT pv, FVECT nv,
104 +                                FVECT uvw[3]);
105 +
106   #ifdef  F_SETLKW
107   static void aflock(int  typ);
108   #endif
# Line 110 | Line 117 | setambres(                             /* set ambient resolution */
117                                                  /* set min & max radii */
118          if (ar <= 0) {
119                  minarad = 0;
120 <                maxarad = thescene.cusize / 2.0;
120 >                maxarad = thescene.cusize*0.2;
121          } else {
122                  minarad = thescene.cusize / ar;
123 <                maxarad = 64 * minarad;                 /* heuristic */
124 <                if (maxarad > thescene.cusize / 2.0)
125 <                        maxarad = thescene.cusize / 2.0;
123 >                maxarad = 64.0 * minarad;               /* heuristic */
124 >                if (maxarad > thescene.cusize*0.2)
125 >                        maxarad = thescene.cusize*0.2;
126          }
127          if (minarad <= FTINY)
128 <                minarad = 10*FTINY;
128 >                minarad = 10.0*FTINY;
129          if (maxarad <= minarad)
130 <                maxarad = 64 * minarad;
130 >                maxarad = 64.0 * minarad;
131   }
132  
133  
# Line 129 | Line 136 | setambacc(                             /* set ambient accuracy */
136          double  newa
137   )
138   {
139 <        double  ambdiff;
140 <
141 <        if (newa < 0.0)
142 <                newa = 0.0;
143 <        ambdiff = fabs(newa - ambacc);
144 <        if (ambdiff >= .01 && (ambacc = newa) > FTINY) {
138 <                qambacc = sqrt(sqrt(ambacc));
139 <                if (nambvals > 0)
139 >        static double   olda;           /* remember previous setting here */
140 >        
141 >        newa *= (newa > 0);
142 >        if (fabs(newa - olda) >= .05*(newa + olda)) {
143 >                ambacc = newa;
144 >                if (ambacc > FTINY && nambvals > 0)
145                          sortambvals(1);         /* rebuild tree */
146          }
147   }
# Line 152 | Line 157 | setambient(void)                               /* initialize calculation */
157          ambdone();
158                                                  /* init ambient limits */
159          setambres(ambres);
160 <        qambacc = sqrt(sqrt(ambacc *= (ambacc > FTINY)));
160 >        setambacc(ambacc);
161          if (ambfile == NULL || !ambfile[0])
162                  return;
163          if (ambacc <= FTINY) {
# Line 168 | Line 173 | setambient(void)                               /* initialize calculation */
173                  initambfile(0);                 /* file exists */
174                  lastpos = ftell(ambfp);
175                  while (readambval(&amb, ambfp))
176 <                        avinsert(avstore(&amb));
176 >                        avstore(&amb);
177                  nambshare = nambvals;           /* share loaded values */
178                  if (readonly) {
179                          sprintf(errmsg,
# Line 188 | Line 193 | setambient(void)                               /* initialize calculation */
193                                          (flen - lastpos)/AMBVALSIZ);
194                          error(WARNING, errmsg);
195                          fseek(ambfp, lastpos, SEEK_SET);
191 #ifndef _WIN32 /* XXX we need a replacement for that one */
196                          ftruncate(fileno(ambfp), (off_t)lastpos);
193 #endif
197                  }
198          } else if ((ambfp = fopen(ambfile, "w+")) != NULL) {
199                  initambfile(1);                 /* else create new file */
# Line 200 | Line 203 | setambient(void)                               /* initialize calculation */
203                  sprintf(errmsg, "cannot open ambient file \"%s\"", ambfile);
204                  error(SYSTEM, errmsg);
205          }
203 #ifdef getc_unlocked
204        flockfile(ambfp);                       /* application-level lock */
205 #endif
206   #ifdef  F_SETLKW
207          aflock(F_UNLCK);                        /* release file */
208   #endif
# Line 223 | Line 223 | ambdone(void)                  /* close ambient file and free memory
223                  lastpos = -1;
224          }
225                                          /* free ambient tree */
226 <        unloadatree(&atrunk, &avfree);
226 >        unloadatree(&atrunk, avfree);
227                                          /* reset state variables */
228          avsum = 0.;
229          navsum = 0;
# Line 264 | Line 264 | ambnotify(                     /* record new modifier */
264                  }
265   }
266  
267 /************ THE FOLLOWING ROUTINES DIFFER BETWEEN NEW & OLD ***************/
267  
269 #ifdef NEWAMB
270
271 #define tfunc(lwr, x, upr)      (((x)-(lwr))/((upr)-(lwr)))
272
273 static double   sumambient(COLOR acol, RAY *r, FVECT rn, int al,
274                                AMBTREE *at, FVECT c0, double s);
275 static int      makeambient(COLOR acol, RAY *r, FVECT rn, int al);
276 static void     extambient(COLOR cr, AMBVAL *ap, FVECT pv, FVECT nv,
277                                FVECT uvw[3]);
278
268   void
269   multambient(            /* compute ambient component & multiply by coef. */
270          COLOR  aval,
# Line 283 | Line 272 | multambient(           /* compute ambient component & multiply
272          FVECT  nrm
273   )
274   {
275 +        static double  logAvgAbsorp = 1;
276          static int  rdepth = 0;                 /* ambient recursion */
277 <        COLOR   acol;
278 <        int     ok;
277 >        COLOR   acol, caustic;
278 >        int     i, ok;
279          double  d, l;
280  
281 +        /* PMAP: Factor in ambient from photon map, if enabled and ray is
282 +         * ambient. Return as all ambient components accounted for, else
283 +         * continue. */
284 +        if (ambPmap(aval, r, rdepth))
285 +                return;
286 +
287 +        if (logAvgAbsorp > 0)                   /* exclude in -aw to avoid growth */
288 +                logAvgAbsorp = log(1.-AVGREFL);
289 +
290 +        /* PMAP: Factor in specular-diffuse ambient (caustics) from photon
291 +         * map, if enabled and ray is primary, else caustic is zero.  Continue
292 +         * with RADIANCE ambient calculation */
293 +        copycolor(caustic, aval);
294 +        ambPmapCaustic(caustic, r, rdepth);
295 +        
296          if (ambdiv <= 0)                        /* no ambient calculation */
297                  goto dumbamb;
298                                                  /* check number of bounces */
# Line 299 | Line 304 | multambient(           /* compute ambient component & multiply
304                  goto dumbamb;
305  
306          if (ambacc <= FTINY) {                  /* no ambient storage */
307 +                FVECT   uvd[2];
308 +                float   dgrad[2], *dgp = NULL;
309 +
310 +                if (nrm != r->ron && DOT(nrm,r->ron) < 0.9999)
311 +                        dgp = dgrad;            /* compute rotational grad. */
312                  copycolor(acol, aval);
313                  rdepth++;
314 <                ok = doambient(acol, r, r->rweight, NULL, NULL, NULL, NULL);
314 >                ok = doambient(acol, r, r->rweight,
315 >                                uvd, NULL, NULL, dgp, NULL);
316                  rdepth--;
317                  if (!ok)
318                          goto dumbamb;
319 +                if ((ok > 0) & (dgp != NULL)) { /* apply texture */
320 +                        FVECT   v1;
321 +                        VCROSS(v1, r->ron, nrm);
322 +                        d = 1.0;
323 +                        for (i = 3; i--; )
324 +                                d += v1[i] * (dgp[0]*uvd[0][i] + dgp[1]*uvd[1][i]);
325 +                        if (d >= 0.05)
326 +                                scalecolor(acol, d);
327 +                }
328                  copycolor(aval, acol);
329 +
330 +                /* PMAP: add in caustic */
331 +                addcolor(aval, caustic);
332                  return;
333          }
334  
# Line 315 | Line 338 | multambient(           /* compute ambient component & multiply
338          setcolor(acol, 0.0, 0.0, 0.0);
339          d = sumambient(acol, r, nrm, rdepth,
340                          &atrunk, thescene.cuorg, thescene.cusize);
341 +                        
342          if (d > FTINY) {
343                  d = 1.0/d;
344                  scalecolor(acol, d);
345                  multcolor(aval, acol);
346 +
347 +                /* PMAP: add in caustic */
348 +                addcolor(aval, caustic);
349                  return;
350          }
351 +        
352          rdepth++;                               /* need to cache new value */
353          ok = makeambient(acol, r, nrm, rdepth-1);
354          rdepth--;
355 +        
356          if (ok) {
357                  multcolor(aval, acol);          /* computed new value */
358 +
359 +                /* PMAP: add in caustic */
360 +                addcolor(aval, caustic);
361                  return;
362          }
363 +        
364   dumbamb:                                        /* return global value */
365          if ((ambvwt <= 0) | (navsum == 0)) {
366                  multcolor(aval, ambval);
367 +                
368 +                /* PMAP: add in caustic */
369 +                addcolor(aval, caustic);
370                  return;
371          }
372 <        l = bright(ambval);                     /* average in computations */
372 >        
373 >        l = bright(ambval);                     /* average in computations */  
374          if (l > FTINY) {
375 <                d = (log(l)*(double)ambvwt + avsum) /
375 >                d = (log(l)*(double)ambvwt + avsum + logAvgAbsorp*navsum) /
376                                  (double)(ambvwt + navsum);
377                  d = exp(d) / l;
378                  scalecolor(aval, d);
379                  multcolor(aval, ambval);        /* apply color of ambval */
380          } else {
381 <                d = exp( avsum / (double)navsum );
381 >                d = exp( avsum/(double)navsum + logAvgAbsorp );
382                  scalecolor(aval, d);            /* neutral color */
383          }
384   }
385  
386  
387 < double
387 > /* Plug a potential leak where ambient cache value is occluded */
388 > static int
389 > plugaleak(RAY *r, AMBVAL *ap, FVECT anorm, double ang)
390 > {
391 >        const double    cost70sq = 0.1169778;   /* cos(70deg)^2 */
392 >        RAY             rtst;
393 >        FVECT           vdif;
394 >        double          normdot, ndotd, nadotd;
395 >        double          a, b, c, t[2];
396 >
397 >        ang += 2.*PI*(ang < 0);                 /* check direction flags */
398 >        if ( !(ap->corral>>(int)(ang*(16./PI)) & 1) )
399 >                return(0);
400 >        /*
401 >         * Generate test ray, targeting 20 degrees above sample point plane
402 >         * along surface normal from cache position.  This should be high
403 >         * enough to miss local geometry we don't really care about.
404 >         */
405 >        VSUB(vdif, ap->pos, r->rop);
406 >        normdot = DOT(anorm, r->ron);
407 >        ndotd = DOT(vdif, r->ron);
408 >        nadotd = DOT(vdif, anorm);
409 >        a = normdot*normdot - cost70sq;
410 >        b = 2.0*(normdot*ndotd - nadotd*cost70sq);
411 >        c = ndotd*ndotd - DOT(vdif,vdif)*cost70sq;
412 >        if (quadratic(t, a, b, c) != 2)
413 >                return(1);                      /* should rarely happen */
414 >        if (t[1] <= FTINY)
415 >                return(0);                      /* should fail behind test */
416 >        rayorigin(&rtst, SHADOW, r, NULL);
417 >        VSUM(rtst.rdir, vdif, anorm, t[1]);     /* further dist. > plane */
418 >        rtst.rmax = normalize(rtst.rdir);       /* short ray test */
419 >        while (localhit(&rtst, &thescene)) {    /* check for occluder */
420 >                OBJREC  *m = findmaterial(rtst.ro);
421 >                if (m != NULL && !istransp(m->otype) && !isBSDFproxy(m) &&
422 >                                (rtst.clipset == NULL ||
423 >                                        !inset(rtst.clipset, rtst.ro->omod)))
424 >                        return(1);              /* plug light leak */
425 >                VCOPY(rtst.rorg, rtst.rop);     /* skip invisible surface */
426 >                rtst.rmax -= rtst.rot;
427 >                rayclear(&rtst);
428 >        }
429 >        return(0);                              /* seems we're OK */
430 > }
431 >
432 >
433 > static double
434   sumambient(             /* get interpolated ambient value */
435          COLOR  acol,
436          RAY  *r,
# Line 359 | Line 442 | sumambient(            /* get interpolated ambient value */
442   )
443   {                       /* initial limit is 10 degrees plus ambacc radians */
444          const double    minangle = 10.0 * PI/180.;
445 <        const double    maxangle = (minangle+ambacc-PI/2.)*pow(r->rweight,0.13)
363 <                                        + PI/2.;
445 >        double          maxangle = minangle + ambacc;
446          double          wsum = 0.0;
447          FVECT           ck0;
448          int             i, j;
449          AMBVAL          *av;
450 +
451 +        if (at->kid != NULL) {          /* sum children first */                                
452 +                s *= 0.5;
453 +                for (i = 0; i < 8; i++) {
454 +                        for (j = 0; j < 3; j++) {
455 +                                ck0[j] = c0[j];
456 +                                if (1<<j & i)
457 +                                        ck0[j] += s;
458 +                                if (r->rop[j] < ck0[j] - OCTSCALE*s)
459 +                                        break;
460 +                                if (r->rop[j] > ck0[j] + (1.0+OCTSCALE)*s)
461 +                                        break;
462 +                        }
463 +                        if (j == 3)
464 +                                wsum += sumambient(acol, r, rn, al,
465 +                                                        at->kid+i, ck0, s);
466 +                }
467 +                                        /* good enough? */
468 +                if (wsum >= 0.05 && s > minarad*10.0)
469 +                        return(wsum);
470 +        }
471 +                                        /* adjust maximum angle */
472 +        if (at->alist != NULL && (at->alist->lvl <= al) & (r->rweight < 0.6))
473 +                maxangle = (maxangle - PI/2.)*pow(r->rweight,0.13) + PI/2.;
474                                          /* sum this node */
475          for (av = at->alist; av != NULL; av = av->next) {
476 <                double  d, delta_r2, delta_t2;
476 >                double  u, v, d, delta_r2, delta_t2;
477                  COLOR   ct;
478                  FVECT   uvw[3];
479                                          /* record access */
# Line 376 | Line 482 | sumambient(            /* get interpolated ambient value */
482                  /*
483                   *  Ambient level test
484                   */
485 <                if (av->lvl > al)       /* list sorted, so this works */
485 >                if (av->lvl > al ||     /* list sorted, so this works */
486 >                                (av->lvl == al) & (av->weight < 0.9*r->rweight))
487                          break;
381                if (av->weight < 0.9*r->rweight)
382                        continue;
488                  /*
489                   *  Direction test using unperturbed normal
490                   */
# Line 391 | Line 496 | sumambient(            /* get interpolated ambient value */
496                  if (delta_r2 >= maxangle*maxangle)
497                          continue;
498                  /*
499 +                 *  Modified ray behind test
500 +                 */
501 +                VSUB(ck0, r->rop, av->pos);
502 +                d = DOT(ck0, uvw[2]);
503 +                if (d < -minarad*ambacc-.001)
504 +                        continue;
505 +                d /= av->rad[0];
506 +                delta_t2 = d*d;
507 +                if (delta_t2 >= ambacc*ambacc)
508 +                        continue;
509 +                /*
510                   *  Elliptical radii test based on Hessian
511                   */
512                  decodedir(uvw[0], av->udir);
513                  VCROSS(uvw[1], uvw[2], uvw[0]);
514 <                VSUB(ck0, av->pos, r->rop);
399 <                d = DOT(ck0, uvw[0]) / av->rad[0];
400 <                delta_t2 = d*d;
401 <                d = DOT(ck0, uvw[1]) / av->rad[1];
514 >                d = (u = DOT(ck0, uvw[0])) / av->rad[0];
515                  delta_t2 += d*d;
516 <                d = DOT(ck0, uvw[2]) / av->rad[0];
516 >                d = (v = DOT(ck0, uvw[1])) / av->rad[1];
517                  delta_t2 += d*d;
518 <                if (delta_t2 >= qambacc*qambacc)
518 >                if (delta_t2 >= ambacc*ambacc)
519                          continue;
520                  /*
521 +                 *  Test for potential light leak
522 +                 */
523 +                if (av->corral && plugaleak(r, av, uvw[2], atan2a(v,u)))
524 +                        continue;
525 +                /*
526                   *  Extrapolate value and compute final weight (hat function)
527                   */
528 <                extambient(ct, av, r->rop, rn, uvw);
528 >                if (!extambient(ct, av, r->rop, rn, uvw))
529 >                        continue;
530                  d = tfunc(maxangle, sqrt(delta_r2), 0.0) *
531 <                        tfunc(qambacc, sqrt(delta_t2), 0.0);
531 >                        tfunc(ambacc, sqrt(delta_t2), 0.0);
532                  scalecolor(ct, d);
533                  addcolor(acol, ct);
534                  wsum += d;
535          }
417        if (at->kid == NULL)
418                return(wsum);
419                                        /* sum children */
420        s *= 0.5;
421        for (i = 0; i < 8; i++) {
422                for (j = 0; j < 3; j++) {
423                        ck0[j] = c0[j];
424                        if (1<<j & i)
425                                ck0[j] += s;
426                        if (r->rop[j] < ck0[j] - OCTSCALE*s)
427                                break;
428                        if (r->rop[j] > ck0[j] + (1.0+OCTSCALE)*s)
429                                break;
430                }
431                if (j == 3)
432                        wsum += sumambient(acol, r, rn, al,
433                                                at->kid+i, ck0, s);
434        }
536          return(wsum);
537   }
538  
539  
540 < int
540 > static int
541   makeambient(            /* make a new ambient value for storage */
542          COLOR  acol,
543          RAY  *r,
# Line 455 | Line 556 | makeambient(           /* make a new ambient value for storage
556                  amb.weight = 1.25*r->rweight;
557          setcolor(acol, AVGREFL, AVGREFL, AVGREFL);
558                                                  /* compute ambient */
559 <        i = doambient(acol, r, amb.weight, uvw, amb.rad, amb.gpos, amb.gdir);
559 >        i = doambient(acol, r, amb.weight,
560 >                        uvw, amb.rad, amb.gpos, amb.gdir, &amb.corral);
561          scalecolor(acol, 1./AVGREFL);           /* undo assumed reflectance */
562          if (i <= 0 || amb.rad[0] <= FTINY)      /* no Hessian or zero radius */
563                  return(i);
# Line 475 | Line 577 | makeambient(           /* make a new ambient value for storage
577   }
578  
579  
580 < void
580 > static int
581   extambient(             /* extrapolate value at pv, nv */
582          COLOR  cr,
583          AMBVAL   *ap,
# Line 484 | Line 586 | extambient(            /* extrapolate value at pv, nv */
586          FVECT  uvw[3]
587   )
588   {
589 +        const double    min_d = 0.05;
590 +        const double    max_d = 20.;
591          static FVECT    my_uvw[3];
592          FVECT           v1;
593          int             i;
# Line 503 | Line 607 | extambient(            /* extrapolate value at pv, nv */
607          for (i = 3; i--; )
608                  d += v1[i] * (ap->gdir[0]*uvw[0][i] + ap->gdir[1]*uvw[1][i]);
609          
610 <        if (d <= 0.0) {
611 <                setcolor(cr, 0.0, 0.0, 0.0);
612 <                return;
613 <        }
610 >        if (d < min_d)                  /* clamp min/max scaling */
611 >                d = min_d;
612 >        else if (d > max_d)
613 >                d = max_d;
614          copycolor(cr, ap->val);
615          scalecolor(cr, d);
616 +        return(d > min_d);
617   }
618  
619  
# Line 530 | Line 635 | avinsert(                              /* insert ambient value in our tree */
635          at = &atrunk;
636          VCOPY(ck0, thescene.cuorg);
637          s = thescene.cusize;
638 <        while (s*(OCTSCALE/2) > av->rad[1]*qambacc) {
638 >        while (s*(OCTSCALE/2) > av->rad[1]*ambacc) {
639                  if (at->kid == NULL)
640                          if ((at->kid = newambtree()) == NULL)
641                                  error(SYSTEM, "out of memory in avinsert");
# Line 545 | Line 650 | avinsert(                              /* insert ambient value in our tree */
650          }
651          avh.next = at->alist;           /* order by increasing level */
652          for (ap = &avh; ap->next != NULL; ap = ap->next)
653 <                if (ap->next->lvl >= av->lvl)
653 >                if ( ap->next->lvl > av->lvl ||
654 >                                (ap->next->lvl == av->lvl) &
655 >                                (ap->next->weight <= av->weight) )
656                          break;
657          av->next = ap->next;
658          ap->next = (AMBVAL*)av;
# Line 553 | Line 660 | avinsert(                              /* insert ambient value in our tree */
660   }
661  
662  
556 #else /* ! NEWAMB */
557
558 static double   sumambient(COLOR acol, RAY *r, FVECT rn, int al,
559                                AMBTREE *at, FVECT c0, double s);
560 static double   makeambient(COLOR acol, RAY *r, FVECT rn, int al);
561 static void     extambient(COLOR cr, AMBVAL *ap, FVECT pv, FVECT nv);
562
563
564 void
565 multambient(            /* compute ambient component & multiply by coef. */
566        COLOR  aval,
567        RAY  *r,
568        FVECT  nrm
569 )
570 {
571        static int  rdepth = 0;                 /* ambient recursion */
572        COLOR   acol;
573        double  d, l;
574
575        if (ambdiv <= 0)                        /* no ambient calculation */
576                goto dumbamb;
577                                                /* check number of bounces */
578        if (rdepth >= ambounce)
579                goto dumbamb;
580                                                /* check ambient list */
581        if (ambincl != -1 && r->ro != NULL &&
582                        ambincl != inset(ambset, r->ro->omod))
583                goto dumbamb;
584
585        if (ambacc <= FTINY) {                  /* no ambient storage */
586                copycolor(acol, aval);
587                rdepth++;
588                d = doambient(acol, r, r->rweight, NULL, NULL);
589                rdepth--;
590                if (d <= FTINY)
591                        goto dumbamb;
592                copycolor(aval, acol);
593                return;
594        }
595
596        if (tracktime)                          /* sort to minimize thrashing */
597                sortambvals(0);
598                                                /* interpolate ambient value */
599        setcolor(acol, 0.0, 0.0, 0.0);
600        d = sumambient(acol, r, nrm, rdepth,
601                        &atrunk, thescene.cuorg, thescene.cusize);
602        if (d > FTINY) {
603                d = 1.0/d;
604                scalecolor(acol, d);
605                multcolor(aval, acol);
606                return;
607        }
608        rdepth++;                               /* need to cache new value */
609        d = makeambient(acol, r, nrm, rdepth-1);
610        rdepth--;
611        if (d > FTINY) {
612                multcolor(aval, acol);          /* got new value */
613                return;
614        }
615 dumbamb:                                        /* return global value */
616        if ((ambvwt <= 0) | (navsum == 0)) {
617                multcolor(aval, ambval);
618                return;
619        }
620        l = bright(ambval);                     /* average in computations */
621        if (l > FTINY) {
622                d = (log(l)*(double)ambvwt + avsum) /
623                                (double)(ambvwt + navsum);
624                d = exp(d) / l;
625                scalecolor(aval, d);
626                multcolor(aval, ambval);        /* apply color of ambval */
627        } else {
628                d = exp( avsum / (double)navsum );
629                scalecolor(aval, d);            /* neutral color */
630        }
631 }
632
633
634 static double
635 sumambient(     /* get interpolated ambient value */
636        COLOR  acol,
637        RAY  *r,
638        FVECT  rn,
639        int  al,
640        AMBTREE  *at,
641        FVECT  c0,
642        double  s
643 )
644 {
645        double  d, e1, e2, wt, wsum;
646        COLOR  ct;
647        FVECT  ck0;
648        int  i;
649        int  j;
650        AMBVAL   *av;
651
652        wsum = 0.0;
653                                        /* do this node */
654        for (av = at->alist; av != NULL; av = av->next) {
655                double  rn_dot = -2.0;
656                if (tracktime)
657                        av->latick = ambclock;
658                /*
659                 *  Ambient level test.
660                 */
661                if (av->lvl > al)       /* list sorted, so this works */
662                        break;
663                if (av->weight < 0.9*r->rweight)
664                        continue;
665                /*
666                 *  Ambient radius test.
667                 */
668                VSUB(ck0, av->pos, r->rop);
669                e1 = DOT(ck0, ck0) / (av->rad * av->rad);
670                if (e1 > ambacc*ambacc*1.21)
671                        continue;
672                /*
673                 *  Direction test using closest normal.
674                 */
675                d = DOT(av->dir, r->ron);
676                if (rn != r->ron) {
677                        rn_dot = DOT(av->dir, rn);
678                        if (rn_dot > 1.0-FTINY)
679                                rn_dot = 1.0-FTINY;
680                        if (rn_dot >= d-FTINY) {
681                                d = rn_dot;
682                                rn_dot = -2.0;
683                        }
684                }
685                e2 = (1.0 - d) * r->rweight;
686                if (e2 < 0.0)
687                        e2 = 0.0;
688                else if (e1 + e2 > ambacc*ambacc*1.21)
689                        continue;
690                /*
691                 *  Ray behind test.
692                 */
693                d = 0.0;
694                for (j = 0; j < 3; j++)
695                        d += (r->rop[j] - av->pos[j]) *
696                                        (av->dir[j] + r->ron[j]);
697                if (d*0.5 < -minarad*ambacc-.001)
698                        continue;
699                /*
700                 *  Jittering final test reduces image artifacts.
701                 */
702                e1 = sqrt(e1);
703                e2 = sqrt(e2);
704                wt = e1 + e2;
705                if (wt > ambacc*(.9+.2*urand(9015+samplendx)))
706                        continue;
707                /*
708                 *  Recompute directional error using perturbed normal
709                 */
710                if (rn_dot > 0.0) {
711                        e2 = sqrt((1.0 - rn_dot)*r->rweight);
712                        wt = e1 + e2;
713                }
714                if (wt <= 1e-3)
715                        wt = 1e3;
716                else
717                        wt = 1.0 / wt;
718                wsum += wt;
719                extambient(ct, av, r->rop, rn);
720                scalecolor(ct, wt);
721                addcolor(acol, ct);
722        }
723        if (at->kid == NULL)
724                return(wsum);
725                                        /* do children */
726        s *= 0.5;
727        for (i = 0; i < 8; i++) {
728                for (j = 0; j < 3; j++) {
729                        ck0[j] = c0[j];
730                        if (1<<j & i)
731                                ck0[j] += s;
732                        if (r->rop[j] < ck0[j] - OCTSCALE*s)
733                                break;
734                        if (r->rop[j] > ck0[j] + (1.0+OCTSCALE)*s)
735                                break;
736                }
737                if (j == 3)
738                        wsum += sumambient(acol, r, rn, al,
739                                                at->kid+i, ck0, s);
740        }
741        return(wsum);
742 }
743
744
745 static double
746 makeambient(            /* make a new ambient value for storage */
747        COLOR  acol,
748        RAY  *r,
749        FVECT  rn,
750        int  al
751 )
752 {
753        AMBVAL  amb;
754        FVECT   gp, gd;
755        int     i;
756
757        amb.weight = 1.0;                       /* compute weight */
758        for (i = al; i-- > 0; )
759                amb.weight *= AVGREFL;
760        if (r->rweight < 0.1*amb.weight)        /* heuristic override */
761                amb.weight = 1.25*r->rweight;
762        setcolor(acol, AVGREFL, AVGREFL, AVGREFL);
763                                                /* compute ambient */
764        amb.rad = doambient(acol, r, amb.weight, gp, gd);
765        if (amb.rad <= FTINY) {
766                setcolor(acol, 0.0, 0.0, 0.0);
767                return(0.0);
768        }
769        scalecolor(acol, 1./AVGREFL);           /* undo assumed reflectance */
770                                                /* store value */
771        VCOPY(amb.pos, r->rop);
772        VCOPY(amb.dir, r->ron);
773        amb.lvl = al;
774        copycolor(amb.val, acol);
775        VCOPY(amb.gpos, gp);
776        VCOPY(amb.gdir, gd);
777                                                /* insert into tree */
778        avsave(&amb);                           /* and save to file */
779        if (rn != r->ron)
780                extambient(acol, &amb, r->rop, rn);     /* texture */
781        return(amb.rad);
782 }
783
784
663   static void
786 extambient(             /* extrapolate value at pv, nv */
787        COLOR  cr,
788        AMBVAL   *ap,
789        FVECT  pv,
790        FVECT  nv
791 )
792 {
793        FVECT  v1;
794        int  i;
795        double  d;
796
797        d = 1.0;                        /* zeroeth order */
798                                        /* gradient due to translation */
799        for (i = 0; i < 3; i++)
800                d += ap->gpos[i]*(pv[i]-ap->pos[i]);
801                                        /* gradient due to rotation */
802        VCROSS(v1, ap->dir, nv);
803        d += DOT(ap->gdir, v1);
804        if (d <= 0.0) {
805                setcolor(cr, 0.0, 0.0, 0.0);
806                return;
807        }
808        copycolor(cr, ap->val);
809        scalecolor(cr, d);
810 }
811
812
813 static void
814 avinsert(                               /* insert ambient value in our tree */
815        AMBVAL *av
816 )
817 {
818        AMBTREE  *at;
819        AMBVAL  *ap;
820        AMBVAL  avh;
821        FVECT  ck0;
822        double  s;
823        int  branch;
824        int  i;
825
826        if (av->rad <= FTINY)
827                error(CONSISTENCY, "zero ambient radius in avinsert");
828        at = &atrunk;
829        VCOPY(ck0, thescene.cuorg);
830        s = thescene.cusize;
831        while (s*(OCTSCALE/2) > av->rad*ambacc) {
832                if (at->kid == NULL)
833                        if ((at->kid = newambtree()) == NULL)
834                                error(SYSTEM, "out of memory in avinsert");
835                s *= 0.5;
836                branch = 0;
837                for (i = 0; i < 3; i++)
838                        if (av->pos[i] > ck0[i] + s) {
839                                ck0[i] += s;
840                                branch |= 1 << i;
841                        }
842                at = at->kid + branch;
843        }
844        avh.next = at->alist;           /* order by increasing level */
845        for (ap = &avh; ap->next != NULL; ap = ap->next)
846                if (ap->next->lvl >= av->lvl)
847                        break;
848        av->next = ap->next;
849        ap->next = (AMBVAL*)av;
850        at->alist = avh.next;
851 }
852
853 #endif  /* ! NEWAMB */
854
855 /************* FOLLOWING ROUTINES SAME FOR NEW & OLD METHODS ***************/
856
857 static void
664   initambfile(            /* initialize ambient file */
665          int  cre8
666   )
# Line 895 | Line 701 | avsave(                                /* insert and save an ambient value */
701          AMBVAL  *av
702   )
703   {
704 <        avinsert(avstore(av));
704 >        avstore(av);
705          if (ambfp == NULL)
706                  return;
707          if (writambval(av, ambfp) < 0)
# Line 910 | Line 716 | writerr:
716  
717  
718   static AMBVAL *
719 < avstore(                                /* allocate memory and store aval */
719 > avstore(                                /* allocate memory and save aval */
720          AMBVAL  *aval
721   )
722   {
# Line 928 | Line 734 | avstore(                               /* allocate memory and store aval */
734                  avsum += log(d);
735                  navsum++;
736          }
737 +        avinsert(av);                   /* insert in our cache tree */
738          return(av);
739   }
740  
# Line 954 | Line 761 | newambtree(void)                               /* allocate 8 ambient tree structs
761          }
762          atp = atfreelist;
763          atfreelist = atp->kid;
764 <        memset((char *)atp, '\0', 8*sizeof(AMBTREE));
764 >        memset(atp, 0, 8*sizeof(AMBTREE));
765          return(atp);
766   }
767  
# Line 980 | Line 787 | unloadatree(                   /* unload an ambient value tree */
787                                          /* transfer values at this node */
788          for (av = at->alist; av != NULL; av = at->alist) {
789                  at->alist = av->next;
790 +                av->next = NULL;
791                  (*f)(av);
792          }
793          if (at->kid == NULL)
# Line 1057 | Line 865 | avlmemi(                               /* find list position from address */
865   {
866          AMBVAL  **avlpp;
867  
868 <        avlpp = (AMBVAL **)bsearch((char *)&avaddr, (char *)avlist2,
869 <                        nambvals, sizeof(AMBVAL *), &aposcmp);
868 >        avlpp = (AMBVAL **)bsearch(&avaddr, avlist2,
869 >                        nambvals, sizeof(AMBVAL *), aposcmp);
870          if (avlpp == NULL)
871                  error(CONSISTENCY, "address not found in avlmemi");
872          return(avlpp - avlist2);
# Line 1101 | Line 909 | sortambvals(                   /* resort ambient values */
909          }
910          if (avlist1 == NULL) {          /* no time tracking -- rebuild tree? */
911                  if (avlist2 != NULL)
912 <                        free((void *)avlist2);
912 >                        free(avlist2);
913                  if (always) {           /* rebuild without sorting */
914                          oldatrunk = atrunk;
915                          atrunk.alist = NULL;
916                          atrunk.kid = NULL;
917 <                        unloadatree(&oldatrunk, &avinsert);
917 >                        unloadatree(&oldatrunk, avinsert);
918                  }
919          } else {                        /* sort memory by last access time */
920                  /*
# Line 1123 | Line 931 | sortambvals(                   /* resort ambient values */
931                  eputs(errmsg);
932   #endif
933                  i_avlist = 0;
934 <                unloadatree(&atrunk, &av2list); /* empty current tree */
934 >                unloadatree(&atrunk, av2list);  /* empty current tree */
935   #ifdef DEBUG
936                  if (i_avlist < nambvals)
937                          error(CONSISTENCY, "missing ambient values in sortambvals");
938   #endif
939 <                qsort((char *)avlist1, nambvals, sizeof(struct avl), &alatcmp);
940 <                qsort((char *)avlist2, nambvals, sizeof(AMBVAL *), &aposcmp);
939 >                qsort(avlist1, nambvals, sizeof(struct avl), alatcmp);
940 >                qsort(avlist2, nambvals, sizeof(AMBVAL *), aposcmp);
941                  for (i = 0; i < nambvals; i++) {
942                          if (avlist1[i].p == NULL)
943                                  continue;
# Line 1145 | Line 953 | sortambvals(                   /* resort ambient values */
953                          avinsert(avlist2[j]);
954                          avlist1[j].p = NULL;
955                  }
956 <                free((void *)avlist1);
957 <                free((void *)avlist2);
956 >                free(avlist1);
957 >                free(avlist2);
958                                                  /* compute new sort interval */
959                  sortintvl = ambclock - lastsort;
960                  if (sortintvl >= MAX_SORT_INTVL/2)
# Line 1174 | Line 982 | aflock(                        /* lock/unlock ambient file */
982  
983          if (typ == fls.l_type)          /* already called? */
984                  return;
985 +
986          fls.l_type = typ;
987 <        if (fcntl(fileno(ambfp), F_SETLKW, &fls) < 0)
988 <                error(SYSTEM, "cannot (un)lock ambient file");
987 >        do
988 >                if (fcntl(fileno(ambfp), F_SETLKW, &fls) != -1)
989 >                        return;
990 >        while (errno == EINTR);
991 >        
992 >        error(SYSTEM, "cannot (un)lock ambient file");
993   }
994  
995  
# Line 1195 | Line 1008 | ambsync(void)                  /* synchronize ambient file */
1008          if ((flen = lseek(fileno(ambfp), (off_t)0, SEEK_END)) < 0)
1009                  goto seekerr;
1010          if ((n = flen - lastpos) > 0) {         /* file has grown */
1011 <                if (ambinp == NULL) {           /* use duplicate filedes */
1012 <                        ambinp = fdopen(dup(fileno(ambfp)), "r");
1011 >                if (ambinp == NULL) {           /* get new file pointer */
1012 >                        ambinp = fopen(ambfile, "rb");
1013                          if (ambinp == NULL)
1014 <                                error(SYSTEM, "fdopen failed in ambsync");
1014 >                                error(SYSTEM, "fopen failed in ambsync");
1015                  }
1016                  if (fseek(ambinp, lastpos, SEEK_SET) < 0)
1017                          goto seekerr;
# Line 1210 | Line 1023 | ambsync(void)                  /* synchronize ambient file */
1023                                  error(WARNING, errmsg);
1024                                  break;
1025                          }
1026 <                        avinsert(avstore(&avs));
1026 >                        avstore(&avs);
1027                          n -= AMBVALSIZ;
1028                  }
1029 <                lastpos = flen - n;
1030 <                /*** seek always as safety measure
1031 <                if (n) ***/                     /* alignment */
1219 <                        if (lseek(fileno(ambfp), (off_t)lastpos, SEEK_SET) < 0)
1220 <                                goto seekerr;
1029 >                lastpos = flen - n;             /* check alignment */
1030 >                if (n && lseek(fileno(ambfp), (off_t)lastpos, SEEK_SET) < 0)
1031 >                        goto seekerr;
1032          }
1033          n = fflush(ambfp);                      /* calls write() at last */
1034 <        if (n != EOF)
1224 <                lastpos += (long)nunflshed*AMBVALSIZ;
1225 <        else if ((lastpos = lseek(fileno(ambfp), (off_t)0, SEEK_CUR)) < 0)
1226 <                goto seekerr;
1227 <                
1034 >        lastpos += (long)nunflshed*AMBVALSIZ;
1035          aflock(F_UNLCK);                        /* release file */
1036          nunflshed = 0;
1037          return(n);
1038   seekerr:
1039          error(SYSTEM, "seek failed in ambsync");
1040 <        return -1; /* pro forma return */
1040 >        return(EOF);    /* pro forma return */
1041   }
1042  
1043   #else   /* ! F_SETLKW */

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines