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.2 by greg, Fri Jan 18 19:56:03 2013 UTC vs.
Revision 2.44 by greg, Sat Jun 7 05:09:45 2025 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 + #include "loadEPW.h"
92  
91 char *progname;                                                         /* Program name */
92 char errmsg[128];                                                       /* Error message buffer */
93   const double DC_SolarConstantE = 1367.0;        /* Solar constant W/m^2 */
94   const double DC_SolarConstantL = 127.5;         /* Solar constant klux */
95  
# Line 108 | Line 108 | double sky_clearness;                  /* Sky clearness */
108   double solar_rad;                       /* Solar radiance */
109   double sun_zenith;                      /* Sun zenith angle (radians) */
110   int     input = 0;                              /* Input type */
111 + int     output = 0;                             /* Output type */
112  
113   extern double dmax( double, double );
114   extern double CalcAirMass();
# Line 127 | Line 128 | extern void CalcPerezParam( double, double, double, in
128   extern void CalcSkyPatchLumin( float *parr );
129   extern void ComputeSky( float *parr );
130  
131 +
132 + extern double  solar_sunset(int month, int day);
133 + extern double  solar_sunrise(int month, int day);
134 +
135   /* Degrees into radians */
136   #define DegToRad(deg)   ((deg)*(PI/180.))
137  
138   /* Radiuans into degrees */
139   #define RadToDeg(rad)   ((rad)*(180./PI))
140  
136
141   /* Perez sky model coefficients */
142  
143   /* Reference:   Perez, R., R. Seals, and J. Michalsky, 1993. "All- */
# Line 208 | Line 212 | static const CategoryBounds SkyClearCat[8] =
212          { 1.950, 2.800 },
213          { 2.800, 4.500 },
214          { 4.500, 6.200 },
215 <        { 6.200, 12.00 }        /* Clear */
215 >        { 6.200, 12.01 }        /* Clear */
216   };
217  
218   /* Luminous efficacy model coefficients */
# Line 246 | Line 250 | static const ModelCoeff DirectLumEff[8] =
250          { 101.18,  1.58, -1.10,  -8.29 }
251   };
252  
253 < extern int jdate(int month, int day);
254 < extern double stadj(int  jd);
255 < 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;
253 > #ifndef NSUNPATCH
254 > #define NSUNPATCH       4               /* max. # patches to spread sun into */
255 > #endif
256  
257 < double          grefl = 0.2;            /* diffuse ground reflectance */
257 > #define SUN_ANG_DEG     0.533           /* sun full-angle in degrees */
258  
259 + int             nsuns = NSUNPATCH;      /* number of sun patches to use */
260 + double          fixed_sun_sa = -1;      /* fixed solid angle per sun? */
261 +
262   int             verbose = 0;            /* progress reports to stderr? */
263  
264   int             outfmt = 'a';           /* output format */
265  
266   int             rhsubdiv = 1;           /* Reinhart sky subdivisions */
267  
268 < float           skycolor[3] = {.96, 1.004, 1.118};      /* sky coloration */
268 > COLOR           skycolor = {.96, 1.004, 1.118}; /* sky coloration */
269 > COLOR           suncolor = {1., 1., 1.};        /* sun color */
270 > COLOR           grefl = {.2, .2, .2};           /* ground reflectance */
271  
269 int             do_sun = 1;             /* output direct solar contribution? */
270
272   int             nskypatch;              /* number of Reinhart patches */
273   float           *rh_palt;               /* sky patch altitudes (radians) */
274   float           *rh_pazi;               /* sky patch azimuths (radians) */
275   float           *rh_dom;                /* sky patch solid angle (sr) */
276  
277 < #define         vector(v,alt,azi)       (       (v)[1] = tcos(alt), \
278 <                                                (v)[0] = (v)[1]*tsin(azi), \
279 <                                                (v)[1] *= tcos(azi), \
280 <                                                (v)[2] = tsin(alt) )
277 > #define         vector(v,alt,azi)       (       (v)[1] = cos(alt), \
278 >                                                (v)[0] = (v)[1]*sin(azi), \
279 >                                                (v)[1] *= cos(azi), \
280 >                                                (v)[2] = sin(alt) )
281  
282   #define         rh_vector(v,i)          vector(v,rh_palt[i],rh_pazi[i])
283  
284   #define         rh_cos(i)               tsin(rh_palt[i])
285  
286 + #define         solar_minute(jd,hr)     ((24*60)*((jd)-1)+(int)((hr)*60.+.5))
287 +
288   extern int      rh_init(void);
289   extern float *  resize_dmatrix(float *mtx_data, int nsteps, int npatch);
290 + extern void     OutputSun(int id, int goodsun, FILE *fp, FILE *mfp);
291   extern void     AddDirect(float *parr);
292  
293 +
294 + static const char *
295 + getfmtname(int fmt)
296 + {
297 +        switch (fmt) {
298 +        case 'a':
299 +                return("ascii");
300 +        case 'f':
301 +                return("float");
302 +        case 'd':
303 +                return("double");
304 +        }
305 +        return("unknown");
306 + }
307 +
308 +
309   int
310   main(int argc, char *argv[])
311   {
312 <        char    buf[256];
312 >        EPWheader       *epw = NULL;    /* EPW/WEA input file */
313 >        EPWrecord       erec;           /* current EPW/WEA input record */
314 >        float   dpthist[2];             /* previous dew point temps */
315 >        double  dir, dif;
316 >        int     doheader = 1;           /* output header? */
317 >        double  rotation = 0;           /* site rotation (degrees) */
318          double  elevation;              /* site elevation (meters) */
319 +        int     leap_day = 0;           /* add leap day? */
320 +        int     sun_hours_only = 0;     /* only output sun hours? */
321          int     dir_is_horiz;           /* direct is meas. on horizontal? */
322 +        FILE    *sunsfp = NULL;         /* output file for individual suns */
323 +        FILE    *modsfp = NULL;         /* modifier output file */
324          float   *mtx_data = NULL;       /* our matrix data */
325 <        int     ntsteps = 0;            /* number of rows in matrix */
325 >        int     avgSky = 0;             /* compute average sky r.t. matrix? */
326 >        int     ntsteps = 0;            /* number of time steps */
327 >        int     tstorage = 0;           /* number of allocated time steps */
328 >        int     nstored = 0;            /* number of time steps in matrix */
329          int     last_monthly = 0;       /* month of last report */
298        int     mo, da;                 /* month (1-12) and day (1-31) */
299        double  hr;                     /* hour (local standard time) */
300        double  dir, dif;               /* direct and diffuse values */
330          int     mtx_offset;
331          int     i, j;
332 +        double  timeinterval = 0;
333  
334 <        progname = argv[0];
334 >        fixargv0(argv[0]);
335                                          /* get options */
336          for (i = 1; i < argc && argv[i][0] == '-'; i++)
337                  switch (argv[i][1]) {
338 <                case 'g':
339 <                        grefl = atof(argv[++i]);
338 >                case 'g':                       /* ground reflectance */
339 >                        grefl[0] = atof(argv[++i]);
340 >                        grefl[1] = atof(argv[++i]);
341 >                        grefl[2] = atof(argv[++i]);
342                          break;
343 <                case 'v':
343 >                case 'v':                       /* verbose progress reports */
344                          verbose++;
345                          break;
346 <                case 'o':
346 >                case 'h':                       /* turn off header */
347 >                        doheader = 0;
348 >                        break;
349 >                case 'o':                       /* output format */
350                          switch (argv[i][2]) {
351                          case 'f':
352                          case 'd':
# Line 322 | Line 357 | main(int argc, char *argv[])
357                                  goto userr;
358                          }
359                          break;
360 <                case 'm':
360 >                case 'O':                       /* output type */
361 >                        switch (argv[i][2]) {
362 >                        case '0':
363 >                                output = 0;
364 >                                break;
365 >                        case '1':
366 >                                output = 1;
367 >                                break;
368 >                        default:
369 >                                goto userr;
370 >                        }
371 >                        if (argv[i][3])
372 >                                goto userr;
373 >                        break;
374 >                case 'm':                       /* Reinhart subdivisions */
375                          rhsubdiv = atoi(argv[++i]);
376                          break;
377 <                case 'c':
377 >                case 'c':                       /* sky color */
378                          skycolor[0] = atof(argv[++i]);
379                          skycolor[1] = atof(argv[++i]);
380                          skycolor[2] = atof(argv[++i]);
381                          break;
382 <                case 'd':
383 <                        do_sun = 1;
382 >                case 'D':                       /* output suns to file */
383 >                        if (strcmp(argv[++i], "-")) {
384 >                                sunsfp = fopen(argv[i], "w");
385 >                                if (sunsfp == NULL) {
386 >                                        fprintf(stderr,
387 >                                        "%s: cannot open '%s' for output\n",
388 >                                                        progname, argv[i]);
389 >                                        exit(1);
390 >                                }
391 >                                break;          /* still may output matrix */
392 >                        }
393 >                        sunsfp = stdout;        /* sending to stdout, so... */
394 >                        /* fall through */
395 >                case 'n':                       /* no matrix output */
396 >                        avgSky = -1;
397 >                        rhsubdiv = 1;
398 >                        /* fall through */
399 >                case 'd':                       /* solar (direct) only */
400                          skycolor[0] = skycolor[1] = skycolor[2] = 0;
401 +                        grefl[0] = grefl[1] = grefl[2] = 0;
402                          break;
403 <                case 's':
404 <                        do_sun = 0;
405 <                        if (skycolor[1] <= 1e-4)
406 <                                skycolor[0] = skycolor[1] = skycolor[2] = 1;
403 >                case 'M':                       /* send sun modifiers to file */
404 >                        if ((modsfp = fopen(argv[++i], "w")) == NULL) {
405 >                                fprintf(stderr, "%s: cannot open '%s' for output\n",
406 >                                                progname, argv[i]);
407 >                                exit(1);
408 >                        }
409                          break;
410 +                case 's':                       /* sky only (no direct) */
411 +                        suncolor[0] = suncolor[1] = suncolor[2] = 0;
412 +                        break;
413 +                case 'u':                       /* solar hours only */
414 +                        sun_hours_only = 1;
415 +                        break;
416 +                case 'r':                       /* rotate distribution */
417 +                        if (argv[i][2] && argv[i][2] != 'z')
418 +                                goto userr;
419 +                        rotation = atof(argv[++i]);
420 +                        break;
421 +                case '5':                       /* 5-phase calculation */
422 +                        nsuns = 1;
423 +                        fixed_sun_sa = PI/360.*atof(argv[++i]);
424 +                        if (fixed_sun_sa <= 0) {
425 +                                fprintf(stderr, "%s: missing solar disk size argument for '-5' option\n",
426 +                                                progname);
427 +                                exit(1);
428 +                        }
429 +                        fixed_sun_sa *= fixed_sun_sa*PI;
430 +                        break;
431 +                case 'A':                       /* compute average sky */
432 +                        avgSky = 1;
433 +                        break;
434 +                case 'i':
435 +                        timeinterval = atof(argv[++i]);
436 +                        break;
437                  default:
438                          goto userr;
439                  }
440 <        if (i < argc-1)
440 >        if ((i < argc-1) | (i > argc))
441                  goto userr;
442 <        if (i == argc-1 && freopen(argv[i], "r", stdin) == NULL) {
443 <                fprintf(stderr, "%s: cannot open '%s' for input\n",
349 <                                progname, argv[i]);
442 >        epw = EPWopen(argv[i]);
443 >        if (epw == NULL)
444                  exit(1);
445 <        }
445 >        if ((modsfp != NULL) & (sunsfp == NULL))
446 >                fprintf(stderr, "%s: warning -M output will be empty without -D\n",
447 >                                progname);
448          if (verbose) {
449                  if (i == argc-1)
450                          fprintf(stderr, "%s: reading weather tape '%s'\n",
# Line 358 | Line 454 | main(int argc, char *argv[])
454                                          progname);
455          }
456                                          /* read weather tape header */
457 <        if (scanf("place %[^\r\n] ", buf) != 1)
458 <                goto fmterr;
459 <        if (scanf("latitude %lf\n", &s_latitude) != 1)
460 <                goto fmterr;
461 <        if (scanf("longitude %lf\n", &s_longitude) != 1)
462 <                goto fmterr;
463 <        if (scanf("time_zone %lf\n", &s_meridian) != 1)
368 <                goto fmterr;
369 <        if (scanf("site_elevation %lf\n", &elevation) != 1)
370 <                goto fmterr;
371 <        if (scanf("weather_data_file_units %d\n", &input) != 1)
372 <                goto fmterr;
373 <        switch (input) {                /* translate units */
374 <        case 1:
457 >        s_latitude = epw->loc.latitude;
458 >        s_longitude = -epw->loc.longitude;
459 >        s_meridian = -15.*epw->loc.timezone;
460 >        elevation = epw->loc.elevation;
461 >        switch (epw->isWEA) {           /* translate units */
462 >        case WEAnot:
463 >        case WEAradnorm:
464                  input = 1;              /* radiometric quantities */
465                  dir_is_horiz = 0;       /* direct is perpendicular meas. */
466                  break;
467 <        case 2:
467 >        case WEAradhoriz:
468                  input = 1;              /* radiometric quantities */
469                  dir_is_horiz = 1;       /* solar measured horizontally */
470                  break;
471 <        case 3:
471 >        case WEAphotnorm:
472                  input = 2;              /* photometric quantities */
473                  dir_is_horiz = 0;       /* direct is perpendicular meas. */
474                  break;
# Line 388 | Line 477 | main(int argc, char *argv[])
477          }
478          rh_init();                      /* initialize sky patches */
479          if (verbose) {
480 <                fprintf(stderr, "%s: location '%s'\n", progname, buf);
480 >                fprintf(stderr, "%s: location '%s, %s'\n", progname,
481 >                                epw->loc.city, epw->loc.country);
482                  fprintf(stderr, "%s: (lat,long)=(%.1f,%.1f) degrees north, west\n",
483                                  progname, s_latitude, s_longitude);
484 <                fprintf(stderr, "%s: %d sky patches per time step\n",
485 <                                progname, nskypatch);
484 >                if (avgSky >= 0)
485 >                        fprintf(stderr, "%s: %d sky patches\n",
486 >                                        progname, nskypatch);
487 >                if (sunsfp)
488 >                        fprintf(stderr, "%s: outputting suns to %s\n",
489 >                                        progname, sunsfp==stdout ? "stdout" : "file");
490 >                if (rotation != 0)
491 >                        fprintf(stderr, "%s: rotating output %.0f degrees\n",
492 >                                        progname, rotation);
493          }
494                                          /* convert quantities to radians */
495          s_latitude = DegToRad(s_latitude);
496          s_longitude = DegToRad(s_longitude);
497          s_meridian = DegToRad(s_meridian);
498 +                                        /* initial allocation */
499 +        mtx_data = resize_dmatrix(mtx_data, tstorage=2, nskypatch);
500 +        dpthist[0] = -100;
501                                          /* process each time step in tape */
502 <        while (scanf("%d %d %lf %lf %lf\n", &mo, &da, &hr, &dir, &dif) == 5) {
503 <                double          sda, sta;
504 <                                        /* make space for next time step */
505 <                mtx_offset = 3*nskypatch*ntsteps++;
506 <                mtx_data = resize_dmatrix(mtx_data, ntsteps, nskypatch);
507 <                if (dif <= 1e-4) {
508 <                        memset(mtx_data+mtx_offset, 0, sizeof(float)*3*nskypatch);
509 <                        continue;
510 <                }
511 <                if (verbose && mo != last_monthly)
512 <                        fprintf(stderr, "%s: stepping through month %d...\n",
513 <                                                progname, last_monthly=mo);
502 >        while ((j = EPWread(epw, &erec)) > 0) {
503 >                const int       mo = erec.date.month+1;
504 >                const int       da = erec.date.day;
505 >                const double    hr = erec.date.hour;
506 >                double          sda, sta, st;
507 >                int             sun_in_sky;
508 >                                        /* 3-hour dew point temp */
509 >                if (EPWisset(&erec,dptemp)) {
510 >                        if (dpthist[0] < -99)
511 >                                dpthist[0] = dpthist[1] = erec.dptemp;
512 >                        dew_point = (1./3.)*(dpthist[0] + dpthist[1] + erec.dptemp);
513 >                        dpthist[0] = dpthist[1]; dpthist[1] = erec.dptemp;
514 >                } else
515 >                        dpthist[0] = -100;
516                                          /* compute solar position */
517 <                julian_date = jdate(mo, da);
517 >                if ((mo == 2) & (da == 29)) {
518 >                        julian_date = 60;
519 >                        leap_day = 1;
520 >                } else
521 >                        julian_date = jdate(mo, da) + leap_day;
522                  sda = sdec(julian_date);
523                  sta = stadj(julian_date);
524 <                altitude = salt(sda, hr+sta);
525 <                azimuth = sazi(sda, hr+sta) + PI;
524 >                st = hr + sta;
525 >                
526 >                if (timeinterval > 0) {
527 >                        if (fabs(solar_sunrise(mo, da) - st) <= timeinterval/120)
528 >                                st = (st + timeinterval/120 + solar_sunrise(mo, da))/2;
529 >                        else if (fabs(solar_sunset(mo, da) - st) < timeinterval/120)
530 >                                st = (st - timeinterval/120 + solar_sunset(mo, da))/2;
531 >                }
532 >                altitude = salt(sda, st);
533 >                sun_in_sky = (altitude > -DegToRad(SUN_ANG_DEG/2.));
534 >                if (sun_hours_only & !sun_in_sky)
535 >                        continue;       /* skipping nighttime points */
536 >                azimuth = sazi(sda, st) + PI - DegToRad(rotation);
537 >
538 >                switch (epw->isWEA) {           /* translate units */
539 >                case WEAnot:
540 >                case WEAradnorm:
541 >                        if (!EPWisset(&erec,dirirrad) |
542 >                                        !EPWisset(&erec,horizdiffirrad)) {
543 >                                fprintf(stderr, "%s: missing required irradiances at line %d\n",
544 >                                                progname, epw->lino);
545 >                                exit(1);
546 >                        }
547 >                        dir = erec.dirirrad;
548 >                        dif = erec.horizdiffirrad;
549 >                        break;
550 >                case WEAradhoriz:
551 >                        dir = erec.globhorizirrad - erec.horizdiffirrad;
552 >                        dif = erec.horizdiffirrad;
553 >                        break;
554 >                case WEAphotnorm:
555 >                        dir = erec.dirillum;
556 >                        dif = erec.diffillum;
557 >                        break;
558 >                }
559 >                mtx_offset = 3*nskypatch*nstored;
560 >                nstored += !avgSky | !nstored;
561 >                                        /* make space for next row */
562 >                if (nstored > tstorage) {
563 >                        tstorage += (tstorage>>1) + nstored + 7;
564 >                        mtx_data = resize_dmatrix(mtx_data, tstorage, nskypatch);
565 >                }
566 >                ntsteps++;              /* keep count of time steps */
567 >
568 >                if (dir+dif <= 1e-4) {  /* effectively nighttime? */
569 >                        if (!avgSky | !mtx_offset)
570 >                                memset(mtx_data+mtx_offset, 0,
571 >                                                sizeof(float)*3*nskypatch);
572 >                                        /* output black sun? */
573 >                        if (sunsfp && sun_in_sky)
574 >                                OutputSun(solar_minute(julian_date,hr), 0,
575 >                                                        sunsfp, modsfp);
576 >                        continue;
577 >                }
578 >                if (!sun_in_sky && dir > (input==1 ? 20. : 20.*WHTEFFICACY))
579 >                        fprintf(stderr,
580 >                                "%s: warning - unusually bright at %.1f on %d-%d\n",
581 >                                        progname, hr, mo, da);
582                                          /* convert measured values */
583 <                if (dir_is_horiz && altitude > 0.)
583 >                if (dir_is_horiz && altitude > FTINY)
584                          dir /= sin(altitude);
585                  if (input == 1) {
586                          dir_irrad = dir;
# Line 429 | Line 591 | main(int argc, char *argv[])
591                  }
592                                          /* compute sky patch values */
593                  ComputeSky(mtx_data+mtx_offset);
594 <                if (do_sun)
595 <                        AddDirect(mtx_data+mtx_offset);
594 >                                        /* output sun if requested */
595 >                if (sunsfp && sun_in_sky)
596 >                        OutputSun(solar_minute(julian_date,hr), 1,
597 >                                                sunsfp, modsfp);
598 >
599 >                if (avgSky < 0)         /* no matrix? */
600 >                        continue;
601 >
602 >                AddDirect(mtx_data+mtx_offset);
603 >                                        /* update cumulative sky? */
604 >                for (i = 3*nskypatch*(avgSky&(ntsteps>1)); i--; )
605 >                        mtx_data[i] += mtx_data[mtx_offset+i];
606 >                                        /* monthly reporting */
607 >                if (verbose && mo != last_monthly)
608 >                        fprintf(stderr, "%s: stepping through month %d...\n",
609 >                                                progname, last_monthly=mo);
610 >                                        /* note whether leap-day was given */
611          }
612 <                                        /* check for junk at end */
613 <        while ((i = fgetc(stdin)) != EOF)
614 <                if (!isspace(i)) {
615 <                        fprintf(stderr, "%s: warning - unexpected data past EOT: ",
616 <                                        progname);
617 <                        buf[0] = i; buf[1] = '\0';
618 <                        fgets(buf+1, sizeof(buf)-1, stdin);
619 <                        fputs(buf, stderr); fputc('\n', stderr);
620 <                        break;
621 <                }
612 >        if (j != EOF) {
613 >                fprintf(stderr, "%s: error on input\n", progname);
614 >                exit(1);
615 >        }
616 >        EPWclose(epw); epw = NULL;
617 >        if (!ntsteps) {
618 >                fprintf(stderr, "%s: no valid time steps on input\n", progname);
619 >                exit(1);
620 >        }
621 >        if (avgSky < 0)                 /* no matrix output? */
622 >                goto alldone;
623 >
624 >        dif = 1./(double)ntsteps;       /* average sky? */
625 >        for (i = 3*nskypatch*(avgSky&(ntsteps>1)); i--; )
626 >                mtx_data[i] *= dif;
627                                          /* write out matrix */
628 +        if (outfmt != 'a')
629 +                SET_FILE_BINARY(stdout);
630   #ifdef getc_unlocked
631          flockfile(stdout);
632   #endif
633          if (verbose)
634                  fprintf(stderr, "%s: writing %smatrix with %d time steps...\n",
635 <                                progname, outfmt=='a' ? "" : "binary ", ntsteps);
635 >                                progname, outfmt=='a' ? "" : "binary ", nstored);
636 >        if (doheader) {
637 >                newheader("RADIANCE", stdout);
638 >                printargs(argc, argv, stdout);
639 >                printf("LATLONG= %.8f %.8f\n", RadToDeg(s_latitude),
640 >                                        -RadToDeg(s_longitude));
641 >                printf("NROWS=%d\n", nskypatch);
642 >                printf("NCOLS=%d\n", nstored);
643 >                printf("NCOMP=3\n");
644 >                if ((outfmt == 'f') | (outfmt == 'd'))
645 >                        fputendian(stdout);
646 >                fputformat((char *)getfmtname(outfmt), stdout);
647 >                putchar('\n');
648 >        }
649                                          /* patches are rows (outer sort) */
650          for (i = 0; i < nskypatch; i++) {
651                  mtx_offset = 3*i;
652                  switch (outfmt) {
653                  case 'a':
654 <                        for (j = 0; j < ntsteps; j++) {
655 <                                printf("%.3e %.3e %.3e\n", mtx_data[mtx_offset],
654 >                        for (j = 0; j < nstored; j++) {
655 >                                printf("%.3g %.3g %.3g\n", mtx_data[mtx_offset],
656                                                  mtx_data[mtx_offset+1],
657                                                  mtx_data[mtx_offset+2]);
658                                  mtx_offset += 3*nskypatch;
659                          }
660 <                        if (ntsteps > 1)
660 >                        if (nstored > 1)
661                                  fputc('\n', stdout);
662                          break;
663                  case 'f':
664 <                        for (j = 0; j < ntsteps; j++) {
665 <                                fwrite(mtx_data+mtx_offset, sizeof(float), 3,
664 >                        for (j = 0; j < nstored; j++) {
665 >                                putbinary(mtx_data+mtx_offset, sizeof(float), 3,
666                                                  stdout);
667                                  mtx_offset += 3*nskypatch;
668                          }
669                          break;
670                  case 'd':
671 <                        for (j = 0; j < ntsteps; j++) {
671 >                        for (j = 0; j < nstored; j++) {
672                                  double  ment[3];
673                                  ment[0] = mtx_data[mtx_offset];
674                                  ment[1] = mtx_data[mtx_offset+1];
675                                  ment[2] = mtx_data[mtx_offset+2];
676 <                                fwrite(ment, sizeof(double), 3, stdout);
676 >                                putbinary(ment, sizeof(double), 3, stdout);
677                                  mtx_offset += 3*nskypatch;
678                          }
679                          break;
# Line 484 | Line 681 | main(int argc, char *argv[])
681                  if (ferror(stdout))
682                          goto writerr;
683          }
684 <        if (fflush(stdout) == EOF)
684 > alldone:
685 >        if (fflush(NULL) == EOF)
686                  goto writerr;
687          if (verbose)
688                  fprintf(stderr, "%s: done.\n", progname);
689          exit(0);
690   userr:
691 <        fprintf(stderr, "Usage: %s [-v][-d|-s][-m N][-g refl][-c r g b][-o{f|d}] [tape.wea]\n",
691 >        fprintf(stderr, "Usage: %s [-v][-h][-A][-d|-s|-n][-u][-D file [-M modfile]][-r deg][-m N][-g r g b][-c r g b][-o{f|d}][-O{0|1}] [tape.wea]\n",
692                          progname);
693          exit(1);
694   fmterr:
695 <        fprintf(stderr, "%s: input weather tape format error\n", progname);
695 >        fprintf(stderr, "%s: weather tape format error in header\n", progname);
696          exit(1);
697   writerr:
698          fprintf(stderr, "%s: write error on output\n", progname);
699          exit(1);
700   }
701  
702 +
703   /* Return maximum of two doubles */
704   double dmax( double a, double b )
705   { return (a > b) ? a : b; }
# Line 511 | Line 710 | ComputeSky(float *parr)
710   {
711          int index;                      /* Category index */
712          double norm_diff_illum;         /* Normalized diffuse illuimnance */
514        double zlumin;                  /* Zenith luminance */
713          int i;
714 <        
714 >
715          /* Calculate atmospheric precipitable water content */
716          apwc = CalcPrecipWater(dew_point);
717  
718 <        /* Limit solar altitude to keep circumsolar off zenith */
719 <        if (altitude > DegToRad(87.0))
720 <                altitude = DegToRad(87.0);
718 >        /* Calculate sun zenith angle (don't let it dip below horizon) */
719 >        /* Also limit minimum angle to keep circumsolar off zenith */
720 >        if (altitude <= 0.0)
721 >                sun_zenith = DegToRad(90.0);
722 >        else if (altitude >= DegToRad(87.0))
723 >                sun_zenith = DegToRad(3.0);
724 >        else
725 >                sun_zenith = DegToRad(90.0) - altitude;
726  
524        /* Calculate sun zenith angle */
525        sun_zenith = DegToRad(90.0) - altitude;
526
727          /* Compute the inputs for the calculation of the sky distribution */
728          
729          if (input == 0)                                 /* XXX never used */
# Line 542 | Line 742 | ComputeSky(float *parr)
742                  sky_brightness = CalcSkyBrightness();
743                  sky_clearness =  CalcSkyClearness();
744  
745 +                /* Limit sky clearness */
746 +                if (sky_clearness > 11.9)
747 +                        sky_clearness = 11.9;
748 +                else if (sky_clearness < 1.0)
749 +                        sky_clearness = 1.0;
750 +
751 +                /* Limit sky brightness */
752 +                if (sky_brightness < 0.01)
753 +                        sky_brightness = 0.01;
754 +                else if (sky_brightness > 0.6)
755 +                        sky_brightness = 0.6;
756 +
757                  /* Calculate illuminance */
758                  index = GetCategoryIndex();
759                  diff_illum = diff_irrad * CalcDiffuseIllumRatio(index);
# Line 553 | Line 765 | ComputeSky(float *parr)
765                  index = CalcSkyParamFromIllum();
766          }
767  
768 <        if (bright(skycolor) <= 1e-4) {                 /* 0 sky component? */
769 <                memset(parr, 0, sizeof(float)*3*nskypatch);
770 <                return;
768 >        if (output == 1) {                      /* hack for solar radiance */
769 >                diff_illum = diff_irrad * WHTEFFICACY;
770 >                dir_illum = dir_irrad * WHTEFFICACY;
771          }
772          /* Compute ground radiance (include solar contribution if any) */
773 <        parr[0] = diff_illum * (1./PI/WHTEFFICACY);
773 >        parr[0] = diff_illum;
774          if (altitude > 0)
775 <                parr[0] += dir_illum * sin(altitude) * (1./PI/WHTEFFICACY);
776 <        parr[2] = parr[1] = parr[0];
775 >                parr[0] += dir_illum * sin(altitude);
776 >        parr[2] = parr[1] = parr[0] *= (1./PI/WHTEFFICACY);
777 >        multcolor(parr, grefl);
778  
779 +        if (bright(skycolor) <= 1e-4) {                 /* 0 sky component? */
780 +                memset(parr+3, 0, sizeof(float)*3*(nskypatch-1));
781 +                return;
782 +        }
783          /* Calculate Perez sky model parameters */
784          CalcPerezParam(sun_zenith, sky_clearness, sky_brightness, index);
785  
# Line 572 | Line 789 | ComputeSky(float *parr)
789          /* Calculate relative horizontal illuminance */
790          norm_diff_illum = CalcRelHorzIllum(parr);
791  
792 +        /* Check for zero sky -- make uniform in that case */
793 +        if (norm_diff_illum <= FTINY) {
794 +                for (i = 1; i < nskypatch; i++)
795 +                        setcolor(parr+3*i, 1., 1., 1.);
796 +                norm_diff_illum = PI;
797 +        }
798          /* Normalization coefficient */
799          norm_diff_illum = diff_illum / norm_diff_illum;
800  
578        /* Calculate relative zenith luminance */
579        zlumin = CalcRelLuminance(sun_zenith, 0.0);
580
581        /* Calculate absolute zenith illuminance */
582        zlumin *= norm_diff_illum;
583
801          /* Apply to sky patches to get absolute radiance values */
802          for (i = 1; i < nskypatch; i++) {
803 <                scalecolor(parr+3*i, zlumin*(1./WHTEFFICACY));
803 >                scalecolor(parr+3*i, norm_diff_illum*(1./WHTEFFICACY));
804                  multcolor(parr+3*i, skycolor);
805          }
806   }
807  
808 +
809 + double
810 + solar_sunset(int month, int day)
811 + {
812 +        float W;
813 +        W = -1 * (tan(s_latitude) * tan(sdec(jdate(month, day))));
814 +        return(12 + (M_PI / 2 - atan2(W, sqrt(1 - W * W))) * 180 / (M_PI * 15));
815 + }
816 +
817 +
818 + double
819 + solar_sunrise(int month, int day)
820 + {
821 +        float W;
822 +        W = -1 * (tan(s_latitude) * tan(sdec(jdate(month, day))));
823 +        return(12 - (M_PI / 2 - atan2(W, sqrt(1 - W * W))) * 180 / (M_PI * 15));
824 + }
825 +
826 +
827   /* Add in solar direct to nearest sky patches (GW) */
828   void
829   AddDirect(float *parr)
830   {
831          FVECT   svec;
832 <        double  near_dprod[4];
833 <        int     near_patch[4];
834 <        double  wta[4], wtot;
832 >        double  near_dprod[NSUNPATCH];
833 >        int     near_patch[NSUNPATCH];
834 >        double  wta[NSUNPATCH], wtot;
835          int     i, j, p;
836  
837 <        if (!do_sun || dir_illum < 1e-4)
837 >        if (dir_illum <= 1e-4 || bright(suncolor) <= 1e-4)
838                  return;
839 <                                        /* identify 4 closest patches */
840 <        for (i = 4; i--; )
839 >                                        /* identify nsuns closest patches */
840 >        if (nsuns > NSUNPATCH)
841 >                nsuns = NSUNPATCH;
842 >        else if (nsuns <= 0)
843 >                nsuns = 1;
844 >        for (i = nsuns; i--; )
845                  near_dprod[i] = -1.;
846          vector(svec, altitude, azimuth);
847          for (p = 1; p < nskypatch; p++) {
# Line 609 | Line 849 | AddDirect(float *parr)
849                  double  dprod;
850                  rh_vector(pvec, p);
851                  dprod = DOT(pvec, svec);
852 <                for (i = 0; i < 4; i++)
852 >                for (i = 0; i < nsuns; i++)
853                          if (dprod > near_dprod[i]) {
854 <                                for (j = 4; --j > i; ) {
854 >                                for (j = nsuns; --j > i; ) {
855                                          near_dprod[j] = near_dprod[j-1];
856                                          near_patch[j] = near_patch[j-1];
857                                  }
# Line 621 | Line 861 | AddDirect(float *parr)
861                          }
862          }
863          wtot = 0;                       /* weight by proximity */
864 <        for (i = 4; i--; )
864 >        for (i = nsuns; i--; )
865                  wtot += wta[i] = 1./(1.002 - near_dprod[i]);
866                                          /* add to nearest patch radiances */
867 <        for (i = 4; i--; ) {
867 >        for (i = nsuns; i--; ) {
868                  float   *pdest = parr + 3*near_patch[i];
869 <                float   val_add = wta[i] * dir_illum /
870 <                                (WHTEFFICACY * wtot * rh_dom[near_patch[i]]);
871 <                *pdest++ += val_add;
872 <                *pdest++ += val_add;
873 <                *pdest++ += val_add;
869 >                float   val_add = wta[i] * dir_illum / (WHTEFFICACY * wtot);
870 >
871 >                val_add /= (fixed_sun_sa > 0)   ? fixed_sun_sa
872 >                                                : rh_dom[near_patch[i]] ;
873 >                *pdest++ += val_add*suncolor[0];
874 >                *pdest++ += val_add*suncolor[1];
875 >                *pdest++ += val_add*suncolor[2];
876          }
877   }
878  
879 + /* Output a sun to indicated file if appropriate for this time step */
880 + void
881 + OutputSun(int id, int goodsun, FILE *fp, FILE *mfp)
882 + {
883 +        double  srad;
884 +        FVECT   sv;
885 +
886 +        srad = DegToRad(SUN_ANG_DEG/2.);
887 +        srad = goodsun ? dir_illum/(WHTEFFICACY * PI*srad*srad) : 0;
888 +        vector(sv, altitude, azimuth);
889 +        fprintf(fp, "\nvoid light solar%d\n0\n0\n", id);
890 +        fprintf(fp, "3 %.3e %.3e %.3e\n", srad*suncolor[0],
891 +                        srad*suncolor[1], srad*suncolor[2]);
892 +        fprintf(fp, "\nsolar%d source sun%d\n0\n0\n", id, id);
893 +        fprintf(fp, "4 %.6f %.6f %.6f %.4f\n", sv[0], sv[1], sv[2], SUN_ANG_DEG);
894 +        
895 +        if (mfp != NULL)                /* saving modifier IDs? */
896 +                fprintf(mfp, "solar%d\n", id);
897 + }
898 +
899   /* Initialize Reinhart sky patch positions (GW) */
900   int
901   rh_init(void)
# Line 665 | Line 927 | rh_init(void)
927          for (i = 0; i < NROW*rhsubdiv; i++) {
928                  const float     ralt = alpha*(i + .5);
929                  const int       ninrow = tnaz[i/rhsubdiv]*rhsubdiv;
930 <                const float     dom = (sin(alpha*(i+1)) - sin(alpha*i))/ninrow;
930 >                const float     dom = 2.*PI*(sin(alpha*(i+1)) - sin(alpha*i)) /
931 >                                                (double)ninrow;
932                  for (j = 0; j < ninrow; j++) {
933                          rh_palt[p] = ralt;
934                          rh_pazi[p] = 2.*PI * j / (double)ninrow;
# Line 770 | Line 1033 | double CalcSkyClearness()
1033          double sz_cubed;        /* Sun zenith angle cubed */
1034  
1035          /* Calculate sun zenith angle cubed */
1036 <        sz_cubed = pow(sun_zenith, 3.0);
1036 >        sz_cubed = sun_zenith*sun_zenith*sun_zenith;
1037  
1038          return ((diff_irrad + dir_irrad) / diff_irrad + 1.041 *
1039                          sz_cubed) / (1.0 + 1.041 * sz_cubed);
# Line 801 | Line 1064 | double CalcDiffuseIrradiance()
1064   double CalcDirectIrradiance()
1065   {
1066          return CalcDiffuseIrradiance() * ((sky_clearness - 1.0) * (1 + 1.041
1067 <                        * pow(sun_zenith, 3.0)));
1067 >                        * sun_zenith*sun_zenith*sun_zenith));
1068   }
1069  
1070   /* Calculate sky brightness and clearness from illuminance values */
# Line 827 | Line 1090 | int CalcSkyParamFromIllum()
1090                  sky_clearness = 12.0;
1091  
1092          /* Limit sky brightness */
1093 <        if (sky_brightness < 0.05)
1093 >        if (sky_brightness < 0.01)
1094                          sky_brightness = 0.01;
1095  
1096 +        if (sky_clearness < 1.0000)
1097 +        {
1098 +                sky_clearness = 1.0000;
1099 +        }
1100 +
1101 +        if (sky_brightness > 0.6)
1102 +        {
1103 +                sky_brightness = 0.6;
1104 +        }
1105 +
1106          while (((fabs(diff_irrad - test1) > 10.0) ||
1107                          (fabs(dir_irrad - test2) > 10.0)) && !(counter == 5))
1108          {
# Line 840 | Line 1113 | int CalcSkyParamFromIllum()
1113                  /* Convert illuminance to irradiance */
1114                  index = GetCategoryIndex();
1115                  diff_irrad = diff_illum / CalcDiffuseIllumRatio(index);
1116 <                dir_irrad = dir_illum / CalcDirectIllumRatio(index);
1116 >                dir_irrad = CalcDirectIllumRatio(index);
1117 >                if (dir_irrad > 0.1)
1118 >                        dir_irrad = dir_illum / dir_irrad;
1119          
1120                  /* Calculate sky brightness and clearness */
1121                  sky_brightness = CalcSkyBrightness();
# Line 851 | Line 1126 | int CalcSkyParamFromIllum()
1126                          sky_clearness = 12.0;
1127          
1128                  /* Limit sky brightness */
1129 <                if (sky_brightness < 0.05)
1129 >                if (sky_brightness < 0.01)
1130                          sky_brightness = 0.01;
1131 +
1132 +                if (sky_clearness < 1.0000)
1133 +                {
1134 +                        sky_clearness = 1.0000;
1135 +                }
1136 +
1137 +                if (sky_brightness > 0.6)
1138 +                {
1139 +                        sky_brightness = 0.6;
1140 +                }
1141          }
1142  
1143          return GetCategoryIndex();
# Line 937 | Line 1222 | double CalcRelHorzIllum( float *parr )
1222          double rh_illum = 0.0;  /* Relative horizontal illuminance */
1223  
1224          for (i = 1; i < nskypatch; i++)
1225 <                rh_illum += parr[3*i+1] * rh_cos(i);
1225 >                rh_illum += parr[3*i+1] * rh_cos(i) * rh_dom[i];
1226  
1227 <        return rh_illum * (2.0 * PI / (nskypatch-1));
1227 >        return rh_illum;
1228   }
1229  
1230   /* Calculate earth orbit eccentricity correction factor */

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines