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

Comparing ray/src/gen/gendaymtx.c (file contents):
Revision 2.1 by greg, Fri Jan 18 01:12:59 2013 UTC vs.
Revision 2.36 by greg, Mon Apr 13 17:12:19 2020 UTC

# Line 81 | Line 81 | static const char RCSid[] = "$Id$";
81  
82   /* Include files */
83   #define _USE_MATH_DEFINES
84 #include <stdio.h>
84   #include <stdlib.h>
86 #include <string.h>
85   #include <ctype.h>
86 + #include "platform.h"
87   #include "rtmath.h"
88 + #include "rtio.h"
89   #include "color.h"
90 + #include "sun.h"
91  
92   char *progname;                                                         /* Program name */
93   char errmsg[128];                                                       /* Error message buffer */
# Line 108 | Line 109 | double sky_clearness;                  /* Sky clearness */
109   double solar_rad;                       /* Solar radiance */
110   double sun_zenith;                      /* Sun zenith angle (radians) */
111   int     input = 0;                              /* Input type */
112 + int     output = 0;                             /* Output type */
113  
114   extern double dmax( double, double );
115   extern double CalcAirMass();
# Line 208 | Line 210 | static const CategoryBounds SkyClearCat[8] =
210          { 1.950, 2.800 },
211          { 2.800, 4.500 },
212          { 4.500, 6.200 },
213 <        { 6.200, 12.00 }        /* Clear */
213 >        { 6.200, 12.01 }        /* Clear */
214   };
215  
216   /* Luminous efficacy model coefficients */
# Line 246 | Line 248 | static const ModelCoeff DirectLumEff[8] =
248          { 101.18,  1.58, -1.10,  -8.29 }
249   };
250  
251 < extern int jdate(int month, int day);
252 < extern double stadj(int  jd);
253 < extern double sdec(int  jd);
252 < extern double salt(double sd, double st);
253 < extern double sazi(double sd, double st);
254 <                                        /* sun calculation constants */
255 < extern double  s_latitude;
256 < extern double  s_longitude;
257 < extern double  s_meridian;
251 > #ifndef NSUNPATCH
252 > #define NSUNPATCH       4               /* max. # patches to spread sun into */
253 > #endif
254  
255 < double          grefl = 0.2;            /* diffuse ground reflectance */
255 > #define SUN_ANG_DEG     0.533           /* sun full-angle in degrees */
256  
257 + int             nsuns = NSUNPATCH;      /* number of sun patches to use */
258 + double          fixed_sun_sa = -1;      /* fixed solid angle per sun? */
259 +
260   int             verbose = 0;            /* progress reports to stderr? */
261  
262   int             outfmt = 'a';           /* output format */
263  
264   int             rhsubdiv = 1;           /* Reinhart sky subdivisions */
265  
266 < float           skycolor[3] = {.96, 1.004, 1.118};      /* sky coloration */
266 > COLOR           skycolor = {.96, 1.004, 1.118}; /* sky coloration */
267 > COLOR           suncolor = {1., 1., 1.};        /* sun color */
268 > COLOR           grefl = {.2, .2, .2};           /* ground reflectance */
269  
269 int             do_sun = 1;             /* output direct solar contribution? */
270
270   int             nskypatch;              /* number of Reinhart patches */
271   float           *rh_palt;               /* sky patch altitudes (radians) */
272   float           *rh_pazi;               /* sky patch azimuths (radians) */
273   float           *rh_dom;                /* sky patch solid angle (sr) */
274  
275 < #define         vector(v,alt,azi)       (       (v)[1] = tcos(alt), \
276 <                                                (v)[0] = (v)[1]*tsin(azi), \
277 <                                                (v)[1] *= tcos(azi), \
278 <                                                (v)[2] = tsin(alt) )
275 > #define         vector(v,alt,azi)       (       (v)[1] = cos(alt), \
276 >                                                (v)[0] = (v)[1]*sin(azi), \
277 >                                                (v)[1] *= cos(azi), \
278 >                                                (v)[2] = sin(alt) )
279  
280   #define         rh_vector(v,i)          vector(v,rh_palt[i],rh_pazi[i])
281  
282   #define         rh_cos(i)               tsin(rh_palt[i])
283  
284 + #define         solar_minute(jd,hr)     ((24*60)*((jd)-1)+(int)((hr)*60.+.5))
285 +
286   extern int      rh_init(void);
287   extern float *  resize_dmatrix(float *mtx_data, int nsteps, int npatch);
288 + extern void     OutputSun(int id, int goodsun, FILE *fp, FILE *mfp);
289   extern void     AddDirect(float *parr);
290  
291 +
292 + static const char *
293 + getfmtname(int fmt)
294 + {
295 +        switch (fmt) {
296 +        case 'a':
297 +                return("ascii");
298 +        case 'f':
299 +                return("float");
300 +        case 'd':
301 +                return("double");
302 +        }
303 +        return("unknown");
304 + }
305 +
306 +
307   int
308   main(int argc, char *argv[])
309   {
310          char    buf[256];
311 +        int     doheader = 1;           /* output header? */
312 +        double  rotation = 0;           /* site rotation (degrees) */
313          double  elevation;              /* site elevation (meters) */
314 +        int     leap_day = 0;           /* add leap day? */
315          int     dir_is_horiz;           /* direct is meas. on horizontal? */
316 +        FILE    *sunsfp = NULL;         /* output file for individual suns */
317 +        FILE    *modsfp = NULL;         /* modifier output file */
318          float   *mtx_data = NULL;       /* our matrix data */
319 <        int     ntsteps = 0;            /* number of rows in matrix */
319 >        int     avgSky = 0;             /* compute average sky r.t. matrix? */
320 >        int     ntsteps = 0;            /* number of time steps */
321 >        int     tstorage = 0;           /* number of allocated time steps */
322 >        int     nstored = 0;            /* number of time steps in matrix */
323          int     last_monthly = 0;       /* month of last report */
324          int     mo, da;                 /* month (1-12) and day (1-31) */
325          double  hr;                     /* hour (local standard time) */
# Line 305 | Line 331 | main(int argc, char *argv[])
331                                          /* get options */
332          for (i = 1; i < argc && argv[i][0] == '-'; i++)
333                  switch (argv[i][1]) {
334 <                case 'g':
335 <                        grefl = atof(argv[++i]);
334 >                case 'g':                       /* ground reflectance */
335 >                        grefl[0] = atof(argv[++i]);
336 >                        grefl[1] = atof(argv[++i]);
337 >                        grefl[2] = atof(argv[++i]);
338                          break;
339 <                case 'v':
339 >                case 'v':                       /* verbose progress reports */
340                          verbose++;
341                          break;
342 <                case 'o':
342 >                case 'h':                       /* turn off header */
343 >                        doheader = 0;
344 >                        break;
345 >                case 'o':                       /* output format */
346                          switch (argv[i][2]) {
347                          case 'f':
348                          case 'd':
# Line 322 | Line 353 | main(int argc, char *argv[])
353                                  goto userr;
354                          }
355                          break;
356 <                case 'm':
356 >                case 'O':                       /* output type */
357 >                        switch (argv[i][2]) {
358 >                        case '0':
359 >                                output = 0;
360 >                                break;
361 >                        case '1':
362 >                                output = 1;
363 >                                break;
364 >                        default:
365 >                                goto userr;
366 >                        }
367 >                        if (argv[i][3])
368 >                                goto userr;
369 >                        break;
370 >                case 'm':                       /* Reinhart subdivisions */
371                          rhsubdiv = atoi(argv[++i]);
372                          break;
373 <                case 'c':
373 >                case 'c':                       /* sky color */
374                          skycolor[0] = atof(argv[++i]);
375                          skycolor[1] = atof(argv[++i]);
376                          skycolor[2] = atof(argv[++i]);
377                          break;
378 <                case 'd':
379 <                        do_sun = 1;
378 >                case 'D':                       /* output suns to file */
379 >                        if (strcmp(argv[++i], "-")) {
380 >                                sunsfp = fopen(argv[i], "w");
381 >                                if (sunsfp == NULL) {
382 >                                        fprintf(stderr,
383 >                                        "%s: cannot open '%s' for output\n",
384 >                                                        progname, argv[i]);
385 >                                        exit(1);
386 >                                }
387 >                                break;          /* still may output matrix */
388 >                        }
389 >                        sunsfp = stdout;        /* sending to stdout, so... */
390 >                        /* fall through */
391 >                case 'n':                       /* no matrix output */
392 >                        avgSky = -1;
393 >                        rhsubdiv = 1;
394 >                        /* fall through */
395 >                case 'd':                       /* solar (direct) only */
396                          skycolor[0] = skycolor[1] = skycolor[2] = 0;
397 +                        grefl[0] = grefl[1] = grefl[2] = 0;
398                          break;
399 <                case 's':
400 <                        do_sun = 0;
401 <                        if (skycolor[1] <= 1e-4)
402 <                                skycolor[0] = skycolor[1] = skycolor[2] = 1;
399 >                case 'M':                       /* send sun modifiers to file */
400 >                        if ((modsfp = fopen(argv[++i], "w")) == NULL) {
401 >                                fprintf(stderr, "%s: cannot open '%s' for output\n",
402 >                                                progname, argv[i]);
403 >                                exit(1);
404 >                        }
405                          break;
406 +                case 's':                       /* sky only (no direct) */
407 +                        suncolor[0] = suncolor[1] = suncolor[2] = 0;
408 +                        break;
409 +                case 'r':                       /* rotate distribution */
410 +                        if (argv[i][2] && argv[i][2] != 'z')
411 +                                goto userr;
412 +                        rotation = atof(argv[++i]);
413 +                        break;
414 +                case '5':                       /* 5-phase calculation */
415 +                        nsuns = 1;
416 +                        fixed_sun_sa = PI/360.*atof(argv[++i]);
417 +                        if (fixed_sun_sa <= 0) {
418 +                                fprintf(stderr, "%s: missing solar disk size argument for '-5' option\n",
419 +                                                progname);
420 +                                exit(1);
421 +                        }
422 +                        fixed_sun_sa *= fixed_sun_sa*PI;
423 +                        break;
424 +                case 'A':                       /* compute average sky */
425 +                        avgSky = 1;
426 +                        break;
427                  default:
428                          goto userr;
429                  }
# Line 349 | Line 434 | main(int argc, char *argv[])
434                                  progname, argv[i]);
435                  exit(1);
436          }
437 +        if ((modsfp != NULL) & (sunsfp == NULL))
438 +                fprintf(stderr, "%s: warning -M output will be empty without -D\n",
439 +                                progname);
440          if (verbose) {
441                  if (i == argc-1)
442                          fprintf(stderr, "%s: reading weather tape '%s'\n",
# Line 358 | Line 446 | main(int argc, char *argv[])
446                                          progname);
447          }
448                                          /* read weather tape header */
449 <        if (scanf("place %[^\n]\n", buf) != 1)
449 >        if (scanf("place %[^\r\n] ", buf) != 1)
450                  goto fmterr;
451          if (scanf("latitude %lf\n", &s_latitude) != 1)
452                  goto fmterr;
# Line 391 | Line 479 | main(int argc, char *argv[])
479                  fprintf(stderr, "%s: location '%s'\n", progname, buf);
480                  fprintf(stderr, "%s: (lat,long)=(%.1f,%.1f) degrees north, west\n",
481                                  progname, s_latitude, s_longitude);
482 <                fprintf(stderr, "%s: %d sky patches per time step\n",
483 <                                progname, nskypatch);
482 >                if (avgSky >= 0)
483 >                        fprintf(stderr, "%s: %d sky patches\n",
484 >                                        progname, nskypatch);
485 >                if (sunsfp)
486 >                        fprintf(stderr, "%s: outputting suns to file\n",
487 >                                        progname);
488 >                if (rotation != 0)
489 >                        fprintf(stderr, "%s: rotating output %.0f degrees\n",
490 >                                        progname, rotation);
491          }
492 +                                        /* convert quantities to radians */
493 +        s_latitude = DegToRad(s_latitude);
494 +        s_longitude = DegToRad(s_longitude);
495 +        s_meridian = DegToRad(s_meridian);
496 +                                        /* initial allocation */
497 +        mtx_data = resize_dmatrix(mtx_data, tstorage=2, nskypatch);
498                                          /* process each time step in tape */
499          while (scanf("%d %d %lf %lf %lf\n", &mo, &da, &hr, &dir, &dif) == 5) {
500                  double          sda, sta;
501 <                                        /* make space for next time step */
502 <                mtx_offset = 3*nskypatch*ntsteps++;
503 <                mtx_data = resize_dmatrix(mtx_data, ntsteps, nskypatch);
504 <                if (dif <= 1e-4) {
505 <                        memset(mtx_data+mtx_offset, 0, sizeof(float)*3*nskypatch);
506 <                        continue;
501 >
502 >                mtx_offset = 3*nskypatch*nstored;
503 >                nstored += !avgSky | !nstored;
504 >                                        /* make space for next row */
505 >                if (nstored > tstorage) {
506 >                        tstorage += (tstorage>>1) + nstored + 7;
507 >                        mtx_data = resize_dmatrix(mtx_data, tstorage, nskypatch);
508                  }
509 <                if (verbose && mo != last_monthly)
408 <                        fprintf(stderr, "%s: stepping through month %d...\n",
409 <                                                progname, last_monthly=mo);
509 >                ntsteps++;              /* keep count of time steps */
510                                          /* compute solar position */
511 <                julian_date = jdate(mo, da);
511 >                if ((mo == 2) & (da == 29)) {
512 >                        julian_date = 60;
513 >                        leap_day = 1;
514 >                } else
515 >                        julian_date = jdate(mo, da) + leap_day;
516                  sda = sdec(julian_date);
517                  sta = stadj(julian_date);
518                  altitude = salt(sda, hr+sta);
519 <                azimuth = sazi(sda, hr+sta);
519 >                azimuth = sazi(sda, hr+sta) + PI - DegToRad(rotation);
520 >
521 >                if (dir+dif <= 1e-4) {  /* effectively nighttime? */
522 >                        if (!avgSky | !mtx_offset)
523 >                                memset(mtx_data+mtx_offset, 0,
524 >                                                sizeof(float)*3*nskypatch);
525 >                        if (sunsfp)     /* output black sun */
526 >                                OutputSun(solar_minute(julian_date,hr), 0,
527 >                                                        sunsfp, modsfp);
528 >                        continue;
529 >                }
530                                          /* convert measured values */
531                  if (dir_is_horiz && altitude > 0.)
532                          dir /= sin(altitude);
# Line 425 | Line 539 | main(int argc, char *argv[])
539                  }
540                                          /* compute sky patch values */
541                  ComputeSky(mtx_data+mtx_offset);
542 <                if (do_sun)
543 <                        AddDirect(mtx_data+mtx_offset);
542 >
543 >                if (sunsfp)             /* output sun if requested */
544 >                        OutputSun(solar_minute(julian_date,hr), 1,
545 >                                                sunsfp, modsfp);
546 >
547 >                if (avgSky < 0)         /* no matrix? */
548 >                        continue;
549 >
550 >                AddDirect(mtx_data+mtx_offset);
551 >                                        /* update cumulative sky? */
552 >                for (i = 3*nskypatch*(avgSky&(ntsteps>1)); i--; )
553 >                        mtx_data[i] += mtx_data[mtx_offset+i];
554 >                                        /* monthly reporting */
555 >                if (verbose && mo != last_monthly)
556 >                        fprintf(stderr, "%s: stepping through month %d...\n",
557 >                                                progname, last_monthly=mo);
558 >                                        /* note whether leap-day was given */
559          }
560 +        if (!ntsteps) {
561 +                fprintf(stderr, "%s: no valid time steps on input\n", progname);
562 +                exit(1);
563 +        }
564                                          /* check for junk at end */
565          while ((i = fgetc(stdin)) != EOF)
566                  if (!isspace(i)) {
# Line 438 | Line 571 | main(int argc, char *argv[])
571                          fputs(buf, stderr); fputc('\n', stderr);
572                          break;
573                  }
574 +
575 +        if (avgSky < 0)                 /* no matrix output? */
576 +                goto alldone;
577 +
578 +        dif = 1./(double)ntsteps;       /* average sky? */
579 +        for (i = 3*nskypatch*(avgSky&(ntsteps>1)); i--; )
580 +                mtx_data[i] *= dif;
581                                          /* write out matrix */
582 +        if (outfmt != 'a')
583 +                SET_FILE_BINARY(stdout);
584   #ifdef getc_unlocked
585          flockfile(stdout);
586   #endif
587          if (verbose)
588                  fprintf(stderr, "%s: writing %smatrix with %d time steps...\n",
589 <                                progname, outfmt=='a' ? "" : "binary ", ntsteps);
589 >                                progname, outfmt=='a' ? "" : "binary ", nstored);
590 >        if (doheader) {
591 >                newheader("RADIANCE", stdout);
592 >                printargs(argc, argv, stdout);
593 >                printf("LATLONG= %.8f %.8f\n", RadToDeg(s_latitude),
594 >                                        -RadToDeg(s_longitude));
595 >                printf("NROWS=%d\n", nskypatch);
596 >                printf("NCOLS=%d\n", nstored);
597 >                printf("NCOMP=3\n");
598 >                if ((outfmt == 'f') | (outfmt == 'd'))
599 >                        fputendian(stdout);
600 >                fputformat((char *)getfmtname(outfmt), stdout);
601 >                putchar('\n');
602 >        }
603                                          /* patches are rows (outer sort) */
604          for (i = 0; i < nskypatch; i++) {
605                  mtx_offset = 3*i;
606                  switch (outfmt) {
607                  case 'a':
608 <                        for (j = 0; j < ntsteps; j++) {
609 <                                printf("%.3e %.3e %.3e\n", mtx_data[mtx_offset],
608 >                        for (j = 0; j < nstored; j++) {
609 >                                printf("%.3g %.3g %.3g\n", mtx_data[mtx_offset],
610                                                  mtx_data[mtx_offset+1],
611                                                  mtx_data[mtx_offset+2]);
612                                  mtx_offset += 3*nskypatch;
613                          }
614 <                        fputc('\n', stdout);
614 >                        if (nstored > 1)
615 >                                fputc('\n', stdout);
616                          break;
617                  case 'f':
618 <                        for (j = 0; j < ntsteps; j++) {
619 <                                fwrite(mtx_data+mtx_offset, sizeof(float), 3,
618 >                        for (j = 0; j < nstored; j++) {
619 >                                putbinary(mtx_data+mtx_offset, sizeof(float), 3,
620                                                  stdout);
621                                  mtx_offset += 3*nskypatch;
622                          }
623                          break;
624                  case 'd':
625 <                        for (j = 0; j < ntsteps; j++) {
625 >                        for (j = 0; j < nstored; j++) {
626                                  double  ment[3];
627                                  ment[0] = mtx_data[mtx_offset];
628                                  ment[1] = mtx_data[mtx_offset+1];
629                                  ment[2] = mtx_data[mtx_offset+2];
630 <                                fwrite(ment, sizeof(double), 3, stdout);
630 >                                putbinary(ment, sizeof(double), 3, stdout);
631                                  mtx_offset += 3*nskypatch;
632                          }
633                          break;
# Line 479 | Line 635 | main(int argc, char *argv[])
635                  if (ferror(stdout))
636                          goto writerr;
637          }
638 <        if (fflush(stdout) == EOF)
638 > alldone:
639 >        if (fflush(NULL) == EOF)
640                  goto writerr;
641          if (verbose)
642                  fprintf(stderr, "%s: done.\n", progname);
643          exit(0);
644   userr:
645 <        fprintf(stderr, "Usage: %s [-v][-d|-s][-m N][-g refl][-c r g b][-o{f|d}] [tape.wea]\n",
645 >        fprintf(stderr, "Usage: %s [-v][-h][-A][-d|-s|-n][-D file][-r deg][-m N][-g r g b][-c r g b][-o{f|d}][-O{0|1}] [tape.wea]\n",
646                          progname);
647          exit(1);
648   fmterr:
649 <        fprintf(stderr, "%s: input weather tape format error\n", progname);
649 >        fprintf(stderr, "%s: weather tape format error in header\n", progname);
650          exit(1);
651   writerr:
652          fprintf(stderr, "%s: write error on output\n", progname);
# Line 506 | Line 663 | ComputeSky(float *parr)
663   {
664          int index;                      /* Category index */
665          double norm_diff_illum;         /* Normalized diffuse illuimnance */
509        double zlumin;                  /* Zenith luminance */
666          int i;
511
512        if (bright(skycolor) <= 1e-4) {                 /* 0 sky component? */
513                memset(parr, 0, sizeof(float)*3*nskypatch);
514                return;
515        }
667          
668          /* Calculate atmospheric precipitable water content */
669          apwc = CalcPrecipWater(dew_point);
670  
671 <        /* Limit solar altitude to keep circumsolar off zenith */
672 <        if (altitude > DegToRad(87.0))
673 <                altitude = DegToRad(87.0);
671 >        /* Calculate sun zenith angle (don't let it dip below horizon) */
672 >        /* Also limit minimum angle to keep circumsolar off zenith */
673 >        if (altitude <= 0.0)
674 >                sun_zenith = DegToRad(90.0);
675 >        else if (altitude >= DegToRad(87.0))
676 >                sun_zenith = DegToRad(3.0);
677 >        else
678 >                sun_zenith = DegToRad(90.0) - altitude;
679  
524        /* Calculate sun zenith angle */
525        sun_zenith = DegToRad(90.0) - altitude;
526
680          /* Compute the inputs for the calculation of the sky distribution */
681          
682          if (input == 0)                                 /* XXX never used */
# Line 542 | Line 695 | ComputeSky(float *parr)
695                  sky_brightness = CalcSkyBrightness();
696                  sky_clearness =  CalcSkyClearness();
697  
698 +                /* Limit sky clearness */
699 +                if (sky_clearness > 11.9)
700 +                        sky_clearness = 11.9;
701 +
702 +                /* Limit sky brightness */
703 +                if (sky_brightness < 0.01)
704 +                        sky_brightness = 0.01;
705 +
706                  /* Calculate illuminance */
707                  index = GetCategoryIndex();
708                  diff_illum = diff_irrad * CalcDiffuseIllumRatio(index);
# Line 553 | Line 714 | ComputeSky(float *parr)
714                  index = CalcSkyParamFromIllum();
715          }
716  
717 +        if (output == 1) {                      /* hack for solar radiance */
718 +                diff_illum = diff_irrad * WHTEFFICACY;
719 +                dir_illum = dir_irrad * WHTEFFICACY;
720 +        }
721          /* Compute ground radiance (include solar contribution if any) */
722 <        parr[0] = diff_illum * (1./PI/WHTEFFICACY);
722 >        parr[0] = diff_illum;
723          if (altitude > 0)
724 <                parr[0] += dir_illum * sin(altitude) * (1./PI/WHTEFFICACY);
725 <        parr[2] = parr[1] = parr[0];
724 >                parr[0] += dir_illum * sin(altitude);
725 >        parr[2] = parr[1] = parr[0] *= (1./PI/WHTEFFICACY);
726 >        multcolor(parr, grefl);
727  
728 +        if (bright(skycolor) <= 1e-4) {                 /* 0 sky component? */
729 +                memset(parr+3, 0, sizeof(float)*3*(nskypatch-1));
730 +                return;
731 +        }
732          /* Calculate Perez sky model parameters */
733          CalcPerezParam(sun_zenith, sky_clearness, sky_brightness, index);
734  
# Line 568 | Line 738 | ComputeSky(float *parr)
738          /* Calculate relative horizontal illuminance */
739          norm_diff_illum = CalcRelHorzIllum(parr);
740  
741 +        /* Check for zero sky -- make uniform in that case */
742 +        if (norm_diff_illum <= FTINY) {
743 +                for (i = 1; i < nskypatch; i++)
744 +                        setcolor(parr+3*i, 1., 1., 1.);
745 +                norm_diff_illum = PI;
746 +        }
747          /* Normalization coefficient */
748          norm_diff_illum = diff_illum / norm_diff_illum;
749  
574        /* Calculate relative zenith luminance */
575        zlumin = CalcRelLuminance(sun_zenith, 0.0);
576
577        /* Calculate absolute zenith illuminance */
578        zlumin *= norm_diff_illum;
579
750          /* Apply to sky patches to get absolute radiance values */
751          for (i = 1; i < nskypatch; i++) {
752 <                scalecolor(parr+3*i, zlumin*(1./WHTEFFICACY));
752 >                scalecolor(parr+3*i, norm_diff_illum*(1./WHTEFFICACY));
753                  multcolor(parr+3*i, skycolor);
754          }
755   }
# Line 589 | Line 759 | void
759   AddDirect(float *parr)
760   {
761          FVECT   svec;
762 <        double  near_dprod[4];
763 <        int     near_patch[4];
764 <        double  wta[4], wtot;
762 >        double  near_dprod[NSUNPATCH];
763 >        int     near_patch[NSUNPATCH];
764 >        double  wta[NSUNPATCH], wtot;
765          int     i, j, p;
766  
767 <        if (!do_sun || dir_illum < 1e-4)
767 >        if (dir_illum <= 1e-4 || bright(suncolor) <= 1e-4)
768                  return;
769 <                                        /* identify 4 closest patches */
770 <        for (i = 4; i--; )
769 >                                        /* identify nsuns closest patches */
770 >        if (nsuns > NSUNPATCH)
771 >                nsuns = NSUNPATCH;
772 >        else if (nsuns <= 0)
773 >                nsuns = 1;
774 >        for (i = nsuns; i--; )
775                  near_dprod[i] = -1.;
776          vector(svec, altitude, azimuth);
777          for (p = 1; p < nskypatch; p++) {
# Line 605 | Line 779 | AddDirect(float *parr)
779                  double  dprod;
780                  rh_vector(pvec, p);
781                  dprod = DOT(pvec, svec);
782 <                for (i = 0; i < 4; i++)
782 >                for (i = 0; i < nsuns; i++)
783                          if (dprod > near_dprod[i]) {
784 <                                for (j = 4; --j > i; ) {
784 >                                for (j = nsuns; --j > i; ) {
785                                          near_dprod[j] = near_dprod[j-1];
786                                          near_patch[j] = near_patch[j-1];
787                                  }
# Line 617 | Line 791 | AddDirect(float *parr)
791                          }
792          }
793          wtot = 0;                       /* weight by proximity */
794 <        for (i = 4; i--; )
794 >        for (i = nsuns; i--; )
795                  wtot += wta[i] = 1./(1.002 - near_dprod[i]);
796                                          /* add to nearest patch radiances */
797 <        for (i = 4; i--; )
798 <                parr[near_patch[i]] += wta[i] * dir_illum /
799 <                                        (wtot * rh_dom[near_patch[i]]);
797 >        for (i = nsuns; i--; ) {
798 >                float   *pdest = parr + 3*near_patch[i];
799 >                float   val_add = wta[i] * dir_illum / (WHTEFFICACY * wtot);
800 >
801 >                val_add /= (fixed_sun_sa > 0)   ? fixed_sun_sa
802 >                                                : rh_dom[near_patch[i]] ;
803 >                *pdest++ += val_add*suncolor[0];
804 >                *pdest++ += val_add*suncolor[1];
805 >                *pdest++ += val_add*suncolor[2];
806 >        }
807   }
808  
809 + /* Output a sun to indicated file if appropriate for this time step */
810 + void
811 + OutputSun(int id, int goodsun, FILE *fp, FILE *mfp)
812 + {
813 +        double  srad;
814 +        FVECT   sv;
815 +
816 +        srad = DegToRad(SUN_ANG_DEG/2.);
817 +
818 +        if (altitude < -srad)           /* well below horizon? */
819 +                return;
820 +
821 +        srad = goodsun ? dir_illum/(WHTEFFICACY * PI*srad*srad) : 0;
822 +        vector(sv, altitude, azimuth);
823 +        fprintf(fp, "\nvoid light solar%d\n0\n0\n", id);
824 +        fprintf(fp, "3 %.3e %.3e %.3e\n", srad*suncolor[0],
825 +                        srad*suncolor[1], srad*suncolor[2]);
826 +        fprintf(fp, "\nsolar%d source sun%d\n0\n0\n", id, id);
827 +        fprintf(fp, "4 %.6f %.6f %.6f %.4f\n", sv[0], sv[1], sv[2], SUN_ANG_DEG);
828 +        
829 +        if (mfp != NULL)                /* saving modifier IDs? */
830 +                fprintf(mfp, "solar%d\n", id);
831 + }
832 +
833   /* Initialize Reinhart sky patch positions (GW) */
834   int
835   rh_init(void)
# Line 656 | Line 861 | rh_init(void)
861          for (i = 0; i < NROW*rhsubdiv; i++) {
862                  const float     ralt = alpha*(i + .5);
863                  const int       ninrow = tnaz[i/rhsubdiv]*rhsubdiv;
864 <                const float     dom = (sin(alpha*(i+1)) - sin(alpha*i))/ninrow;
864 >                const float     dom = 2.*PI*(sin(alpha*(i+1)) - sin(alpha*i)) /
865 >                                                (double)ninrow;
866                  for (j = 0; j < ninrow; j++) {
867                          rh_palt[p] = ralt;
868                          rh_pazi[p] = 2.*PI * j / (double)ninrow;
# Line 761 | Line 967 | double CalcSkyClearness()
967          double sz_cubed;        /* Sun zenith angle cubed */
968  
969          /* Calculate sun zenith angle cubed */
970 <        sz_cubed = pow(sun_zenith, 3.0);
970 >        sz_cubed = sun_zenith*sun_zenith*sun_zenith;
971  
972          return ((diff_irrad + dir_irrad) / diff_irrad + 1.041 *
973                          sz_cubed) / (1.0 + 1.041 * sz_cubed);
# Line 792 | Line 998 | double CalcDiffuseIrradiance()
998   double CalcDirectIrradiance()
999   {
1000          return CalcDiffuseIrradiance() * ((sky_clearness - 1.0) * (1 + 1.041
1001 <                        * pow(sun_zenith, 3.0)));
1001 >                        * sun_zenith*sun_zenith*sun_zenith));
1002   }
1003  
1004   /* Calculate sky brightness and clearness from illuminance values */
# Line 818 | Line 1024 | int CalcSkyParamFromIllum()
1024                  sky_clearness = 12.0;
1025  
1026          /* Limit sky brightness */
1027 <        if (sky_brightness < 0.05)
1027 >        if (sky_brightness < 0.01)
1028                          sky_brightness = 0.01;
1029  
1030          while (((fabs(diff_irrad - test1) > 10.0) ||
# Line 831 | Line 1037 | int CalcSkyParamFromIllum()
1037                  /* Convert illuminance to irradiance */
1038                  index = GetCategoryIndex();
1039                  diff_irrad = diff_illum / CalcDiffuseIllumRatio(index);
1040 <                dir_irrad = dir_illum / CalcDirectIllumRatio(index);
1040 >                dir_irrad = CalcDirectIllumRatio(index);
1041 >                if (dir_irrad > 0.1)
1042 >                        dir_irrad = dir_illum / dir_irrad;
1043          
1044                  /* Calculate sky brightness and clearness */
1045                  sky_brightness = CalcSkyBrightness();
# Line 842 | Line 1050 | int CalcSkyParamFromIllum()
1050                          sky_clearness = 12.0;
1051          
1052                  /* Limit sky brightness */
1053 <                if (sky_brightness < 0.05)
1053 >                if (sky_brightness < 0.01)
1054                          sky_brightness = 0.01;
1055          }
1056  
# Line 928 | Line 1136 | double CalcRelHorzIllum( float *parr )
1136          double rh_illum = 0.0;  /* Relative horizontal illuminance */
1137  
1138          for (i = 1; i < nskypatch; i++)
1139 <                rh_illum += parr[3*i+1] * rh_cos(i);
1139 >                rh_illum += parr[3*i+1] * rh_cos(i) * rh_dom[i];
1140  
1141 <        return rh_illum * (2.0 * PI / (nskypatch-1));
1141 >        return rh_illum;
1142   }
1143  
1144   /* Calculate earth orbit eccentricity correction factor */

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines