Back to index

radiance  4R0+20100331
pinterp.c
Go to the documentation of this file.
00001 #ifndef lint
00002 static const char    RCSid[] = "$Id: pinterp.c,v 2.42 2005/01/18 03:59:41 greg Exp $";
00003 #endif
00004 /*
00005  * Interpolate and extrapolate pictures with different view parameters.
00006  *
00007  *     Greg Ward     09Dec89
00008  */
00009 
00010 #include "copyright.h"
00011 
00012 #include <ctype.h>
00013 #include <string.h>
00014 
00015 #include "platform.h"
00016 #include "standard.h"
00017 #include "rtprocess.h" /* Windows: must come before color.h */
00018 #include "view.h"
00019 #include "color.h"
00020 
00021 #define LOG2         0.69314718055994530942
00022 
00023 #define pscan(y)     (ourpict+(y)*hresolu)
00024 #define sscan(y)     (ourspict+(y)*hresolu)
00025 #define wscan(y)     (ourweigh+(y)*hresolu)
00026 #define zscan(y)     (ourzbuf+(y)*hresolu)
00027 #define bscan(y)     (ourbpict+(y)*hresolu)
00028 #define averaging    (ourweigh != NULL)
00029 #define blurring     (ourbpict != NULL)
00030 #define usematrix    (hasmatrix & !averaging)
00031 #define zisnorm             ((!usematrix) | (ourview.type != VT_PER))
00032 
00033 #define MAXWT        1000.         /* maximum pixel weight (averaging) */
00034 
00035 #define F_FORE              1             /* fill foreground */
00036 #define F_BACK              2             /* fill background */
00037 
00038 #define PACKSIZ             256           /* max. calculation packet size */
00039 
00040 #define RTCOM        "rtrace -h- -ovl -fff -ld- -i- -I- "
00041 
00042 #define ABS(x)              ((x)>0?(x):-(x))
00043 
00044 struct position {int x,y; float z;};
00045 
00046 #define NSTEPS              64            /* number steps in overlap prescan */
00047 #define MINSTEP             4             /* minimum worthwhile preview step */
00048 
00049 struct bound {int min,max;};
00050 
00051 VIEW   ourview = STDVIEW;          /* desired view */
00052 int    hresolu = 512;                     /* horizontal resolution */
00053 int    vresolu = 512;                     /* vertical resolution */
00054 double pixaspect = 1.0;            /* pixel aspect ratio */
00055 
00056 double zeps = .02;                 /* allowed z epsilon */
00057 
00058 COLR   *ourpict;                   /* output picture (COLR's) */
00059 COLOR  *ourspict;                  /* output pixel sums (averaging) */
00060 float  *ourweigh = NULL;           /* output pixel weights (averaging) */
00061 float  *ourzbuf;                   /* corresponding z-buffer */
00062 COLOR  *ourbpict = NULL;           /* blurred picture (view averaging) */
00063 
00064 VIEW   avgview;                    /* average view for -B option */
00065 int    nvavg;                      /* number of views averaged */
00066 
00067 char   *progname;
00068 
00069 int    fillo = F_FORE|F_BACK;             /* selected fill options */
00070 int    fillsamp = 0;               /* sample separation (0 == inf) */
00071 COLR   backcolr = BLKCOLR;         /* background color */
00072 COLOR  backcolor = BLKCOLOR;              /* background color (float) */
00073 double backz = 0.0;                /* background z value */
00074 int    normdist = 1;               /* i/o normalized distance? */
00075 char   ourfmt[LPICFMT+1] = PICFMT; /* original picture format */
00076 double ourexp = -1;                /* original picture exposure */
00077 int    expadj = 0;                 /* exposure adjustment (f-stops) */
00078 double rexpadj = 1;                /* real exposure adjustment */
00079 
00080 VIEW   theirview;                  /* input view */
00081 int    gotview;                    /* got input view? */
00082 int    wrongformat = 0;            /* input in another format? */
00083 RESOLU tresolu;                    /* input resolution */
00084 double theirexp;                   /* input picture exposure */
00085 MAT4   theirs2ours;                /* transformation matrix */
00086 int    hasmatrix = 0;                     /* has transformation matrix */
00087 
00088 static SUBPROC PDesc = SP_INACTIVE; /* rtrace process descriptor */
00089 unsigned short       queue[PACKSIZ][2];   /* pending pixels */
00090 int    packsiz;                    /* actual packet size */
00091 int    queuesiz = 0;               /* number of pixels pending */
00092 
00093 typedef void fillfunc_t(int x, int y);
00094 
00095 static gethfunc headline;
00096 static int nextview(FILE *fp);
00097 static void compavgview(void);
00098 static void addpicture(char *pfile, char *zspec);
00099 static int pixform(MAT4 xfmat, VIEW *vw1, VIEW *vw2);
00100 static void addscanline(struct bound *xl, int y,
00101        COLR *pline, float *zline, struct position *lasty);
00102 static void addpixel(struct position *p0, struct position *p1,
00103        struct position *p2, COLR pix, double w, double z);
00104 static double movepixel(FVECT pos);
00105 static int getperim(struct bound *xl, struct bound *yl, float *zline, int zfd);
00106 static void backpicture(fillfunc_t *fill, int samp);
00107 static void fillpicture(fillfunc_t *fill);
00108 static int clipaft(void);
00109 static int addblur(void);
00110 static void writepicture(void);
00111 static void writedistance(char *fname);
00112 static fillfunc_t backfill;
00113 static fillfunc_t rcalfill;
00114 static void calstart(char *prog, char *args);
00115 static void caldone(void);
00116 static void clearqueue(void);
00117 static void syserror(char *s);
00118 
00119 fillfunc_t *fillfunc = backfill;   /* selected fill function */
00120 
00121 int
00122 main(                /* interpolate pictures */
00123        int    argc,
00124        char   *argv[]
00125 )
00126 {
00127 #define  check(ol,al)              if (argv[an][ol] || \
00128                             badarg(argc-an-1,argv+an+1,al)) \
00129                             goto badopt
00130        int    gotvfile = 0;
00131        int    doavg = -1;
00132        int    doblur = 0;
00133        char   *zfile = NULL;
00134        char   *expcomp = NULL;
00135        int    i, an, rval;
00136 
00137        progname = argv[0];
00138 
00139        for (an = 1; an < argc && argv[an][0] == '-'; an++) {
00140               rval = getviewopt(&ourview, argc-an, argv+an);
00141               if (rval >= 0) {
00142                      an += rval;
00143                      continue;
00144               }
00145               switch (argv[an][1]) {
00146               case 'e':                          /* exposure */
00147                      check(2,"f");
00148                      expcomp = argv[++an];
00149                      break;
00150               case 't':                          /* threshold */
00151                      check(2,"f");
00152                      zeps = atof(argv[++an]);
00153                      break;
00154               case 'a':                          /* average */
00155                      check(2,NULL);
00156                      doavg = 1;
00157                      break;
00158               case 'B':                          /* blur views */
00159                      check(2,NULL);
00160                      doblur = 1;
00161                      break;
00162               case 'q':                          /* quick (no avg.) */
00163                      check(2,NULL);
00164                      doavg = 0;
00165                      break;
00166               case 'n':                          /* dist. normalized? */
00167                      check(2,NULL);
00168                      normdist = !normdist;
00169                      break;
00170               case 'f':                          /* fill type */
00171                      switch (argv[an][2]) {
00172                      case '0':                          /* none */
00173                             check(3,NULL);
00174                             fillo = 0;
00175                             break;
00176                      case 'f':                          /* foreground */
00177                             check(3,NULL);
00178                             fillo = F_FORE;
00179                             break;
00180                      case 'b':                          /* background */
00181                             check(3,NULL);
00182                             fillo = F_BACK;
00183                             break;
00184                      case 'a':                          /* all */
00185                             check(3,NULL);
00186                             fillo = F_FORE|F_BACK;
00187                             break;
00188                      case 's':                          /* sample */
00189                             check(3,"i");
00190                             fillsamp = atoi(argv[++an]);
00191                             break;
00192                      case 'c':                          /* color */
00193                             check(3,"fff");
00194                             fillfunc = backfill;
00195                             setcolor(backcolor, atof(argv[an+1]),
00196                                    atof(argv[an+2]), atof(argv[an+3]));
00197                             setcolr(backcolr, colval(backcolor,RED),
00198                                           colval(backcolor,GRN),
00199                                           colval(backcolor,BLU));
00200                             an += 3;
00201                             break;
00202                      case 'z':                          /* z value */
00203                             check(3,"f");
00204                             fillfunc = backfill;
00205                             backz = atof(argv[++an]);
00206                             break;
00207                      case 'r':                          /* rtrace */
00208                             check(3,"s");
00209                             fillfunc = rcalfill;
00210                             calstart(RTCOM, argv[++an]);
00211                             break;
00212                      default:
00213                             goto badopt;
00214                      }
00215                      break;
00216               case 'z':                          /* z file */
00217                      check(2,"s");
00218                      zfile = argv[++an];
00219                      break;
00220               case 'x':                          /* x resolution */
00221                      check(2,"i");
00222                      hresolu = atoi(argv[++an]);
00223                      break;
00224               case 'y':                          /* y resolution */
00225                      check(2,"i");
00226                      vresolu = atoi(argv[++an]);
00227                      break;
00228               case 'p':                          /* pixel aspect */
00229                      if (argv[an][2] != 'a')
00230                             goto badopt;
00231                      check(3,"f");
00232                      pixaspect = atof(argv[++an]);
00233                      break;
00234               case 'v':                          /* view file */
00235                      if (argv[an][2] != 'f')
00236                             goto badopt;
00237                      check(3,"s");
00238                      gotvfile = viewfile(argv[++an], &ourview, NULL);
00239                      if (gotvfile < 0)
00240                             syserror(argv[an]);
00241                      else if (gotvfile == 0) {
00242                             fprintf(stderr, "%s: bad view file\n",
00243                                           argv[an]);
00244                             exit(1);
00245                      }
00246                      break;
00247               default:
00248               badopt:
00249                      fprintf(stderr, "%s: command line error at '%s'\n",
00250                                    progname, argv[an]);
00251                      goto userr;
00252               }
00253        }
00254                                           /* check arguments */
00255        if ((argc-an)%2)
00256               goto userr;
00257        if (fillsamp == 1)
00258               fillo &= ~F_BACK;
00259        if (doavg < 0)
00260               doavg = (argc-an) > 2;
00261        if (expcomp != NULL) {
00262               if ((expcomp[0] == '+') | (expcomp[0] == '-')) {
00263                      expadj = atof(expcomp) + (expcomp[0]=='+' ? .5 : -.5);
00264                      if (doavg | doblur)
00265                             rexpadj = pow(2.0, atof(expcomp));
00266                      else
00267                             rexpadj = pow(2.0, (double)expadj);
00268               } else {
00269                      if (!isflt(expcomp))
00270                             goto userr;
00271                      rexpadj = atof(expcomp);
00272                      expadj = log(rexpadj)/LOG2 + (rexpadj>1 ? .5 : -.5);
00273                      if (!(doavg | doblur))
00274                             rexpadj = pow(2.0, (double)expadj);
00275               }
00276        }
00277                                           /* set view */
00278        if (nextview(doblur ? stdin : (FILE *)NULL) == EOF) {
00279               fprintf(stderr, "%s: no view on standard input!\n",
00280                             progname);
00281               exit(1);
00282        }
00283        normaspect(viewaspect(&ourview), &pixaspect, &hresolu, &vresolu);
00284                                           /* allocate frame */
00285        if (doavg) {
00286               ourspict = (COLOR *)bmalloc(hresolu*vresolu*sizeof(COLOR));
00287               ourweigh = (float *)bmalloc(hresolu*vresolu*sizeof(float));
00288               if ((ourspict == NULL) | (ourweigh == NULL))
00289                      syserror(progname);
00290        } else {
00291               ourpict = (COLR *)bmalloc(hresolu*vresolu*sizeof(COLR));
00292               if (ourpict == NULL)
00293                      syserror(progname);
00294        }
00295        if (doblur) {
00296               ourbpict = (COLOR *)bmalloc(hresolu*vresolu*sizeof(COLOR));
00297               if (ourbpict == NULL)
00298                      syserror(progname);
00299        }
00300        ourzbuf = (float *)bmalloc(hresolu*vresolu*sizeof(float));
00301        if (ourzbuf == NULL)
00302               syserror(progname);
00303                                                  /* new header */
00304        newheader("RADIANCE", stdout);
00305        fputnow(stdout);
00306                                                  /* run pictures */
00307        do {
00308               memset((char *)ourzbuf, '\0', hresolu*vresolu*sizeof(float));
00309               for (i = an; i < argc; i += 2)
00310                      addpicture(argv[i], argv[i+1]);
00311               if (fillo&F_BACK)                  /* fill in spaces */
00312                      backpicture(fillfunc, fillsamp);
00313               else
00314                      fillpicture(fillfunc);
00315                                                  /* aft clipping */
00316               clipaft();
00317        } while (addblur() && nextview(stdin) != EOF);
00318                                                  /* close calculation */
00319        caldone();
00320                                                  /* add to header */
00321        printargs(argc, argv, stdout);
00322        compavgview();
00323        if (doblur | gotvfile) {
00324               fputs(VIEWSTR, stdout);
00325               fprintview(&avgview, stdout);
00326               putc('\n', stdout);
00327        }
00328        if ((pixaspect < .99) | (pixaspect > 1.01))
00329               fputaspect(pixaspect, stdout);
00330        if (ourexp > 0)
00331               ourexp *= rexpadj;
00332        else
00333               ourexp = rexpadj;
00334        if ((ourexp < .995) | (ourexp > 1.005))
00335               fputexpos(ourexp, stdout);
00336        if (strcmp(ourfmt, PICFMT))        /* print format if known */
00337               fputformat(ourfmt, stdout);
00338        putc('\n', stdout);
00339                                                  /* write picture */
00340        writepicture();
00341                                                  /* write z file */
00342        if (zfile != NULL)
00343               writedistance(zfile);
00344 
00345        exit(0);
00346 userr:
00347        fprintf(stderr,
00348        "Usage: %s [view opts][-t eps][-z zout][-e spec][-B][-a|-q][-fT][-n] pfile zspec ..\n",
00349                      progname);
00350        exit(1);
00351 #undef check
00352 }
00353 
00354 
00355 static int
00356 headline(                          /* process header string */
00357        char   *s,
00358        void   *p
00359 )
00360 {
00361        char   fmt[32];
00362 
00363        if (isheadid(s))
00364               return(0);
00365        if (formatval(fmt, s)) {
00366               if (globmatch(ourfmt, fmt)) {
00367                      wrongformat = 0;
00368                      strcpy(ourfmt, fmt);
00369               } else
00370                      wrongformat = 1;
00371               return(0);
00372        }
00373        if (nvavg < 2) {
00374               putc('\t', stdout);
00375               fputs(s, stdout);
00376        }
00377        if (isexpos(s)) {
00378               theirexp *= exposval(s);
00379               return(0);
00380        }
00381        if (isview(s) && sscanview(&theirview, s) > 0)
00382               gotview++;
00383        return(0);
00384 }
00385 
00386 
00387 static int
00388 nextview(                          /* get and set next view */
00389        FILE   *fp
00390 )
00391 {
00392        char   linebuf[256];
00393        char   *err;
00394        register int  i;
00395 
00396        if (fp != NULL) {
00397               do                   /* get new view */
00398                      if (fgets(linebuf, sizeof(linebuf), fp) == NULL)
00399                             return(EOF);
00400               while (!isview(linebuf) || !sscanview(&ourview, linebuf));
00401        }
00402                                    /* set new view */
00403        if ((err = setview(&ourview)) != NULL) {
00404               fprintf(stderr, "%s: %s\n", progname, err);
00405               exit(1);
00406        }
00407        if (!nvavg) {               /* first view */
00408               avgview = ourview;
00409               return(nvavg++);
00410        }
00411                                    /* add to average view */
00412        for (i = 0; i < 3; i++) {
00413               avgview.vp[i] += ourview.vp[i];
00414               avgview.vdir[i] += ourview.vdir[i];
00415               avgview.vup[i] += ourview.vup[i];
00416        }
00417        avgview.vdist += ourview.vdist;
00418        avgview.horiz += ourview.horiz;
00419        avgview.vert += ourview.vert;
00420        avgview.hoff += ourview.hoff;
00421        avgview.voff += ourview.voff;
00422        avgview.vfore += ourview.vfore;
00423        avgview.vaft += ourview.vaft;
00424        return(nvavg++);
00425 }
00426 
00427 
00428 static void
00429 compavgview(void)                         /* compute average view */
00430 {
00431        register int  i;
00432        double f;
00433 
00434        if (nvavg < 2)
00435               return;
00436        f = 1.0/nvavg;
00437        for (i = 0; i < 3; i++) {
00438               avgview.vp[i] *= f;
00439               avgview.vdir[i] *= f;
00440               avgview.vup[i] *= f;
00441        }
00442        avgview.vdist *= f;
00443        avgview.horiz *= f;
00444        avgview.vert *= f;
00445        avgview.hoff *= f;
00446        avgview.voff *= f;
00447        avgview.vfore *= f;
00448        avgview.vaft *= f;
00449        if (setview(&avgview) != NULL)            /* in case of emergency... */
00450               avgview = ourview;
00451        pixaspect = viewaspect(&avgview) * hresolu / vresolu;
00452 }
00453 
00454 
00455 static void
00456 addpicture(          /* add picture to output */
00457        char   *pfile,
00458        char   *zspec
00459 )
00460 {
00461        FILE   *pfp;
00462        int    zfd;
00463        char   *err;
00464        COLR   *scanin;
00465        float  *zin;
00466        struct position      *plast;
00467        struct bound  *xlim, ylim;
00468        int    y;
00469                                    /* open picture file */
00470        if ((pfp = fopen(pfile, "r")) == NULL)
00471               syserror(pfile);
00472                                    /* get header with exposure and view */
00473        theirexp = 1.0;
00474        theirview = stdview;
00475        gotview = 0;
00476        if (nvavg < 2)
00477               printf("%s:\n", pfile);
00478        getheader(pfp, headline, NULL);
00479        if (wrongformat || !gotview || !fgetsresolu(&tresolu, pfp)) {
00480               fprintf(stderr, "%s: picture format error\n", pfile);
00481               exit(1);
00482        }
00483        if (ourexp <= 0)
00484               ourexp = theirexp;
00485        else if (ABS(theirexp-ourexp) > .01*ourexp)
00486               fprintf(stderr, "%s: different exposure (warning)\n", pfile);
00487        if ( (err = setview(&theirview)) ) {
00488               fprintf(stderr, "%s: %s\n", pfile, err);
00489               exit(1);
00490        }
00491                                    /* compute transformation */
00492        hasmatrix = pixform(theirs2ours, &theirview, &ourview);
00493                                    /* get z specification or file */
00494        zin = (float *)malloc(scanlen(&tresolu)*sizeof(float));
00495        if (zin == NULL)
00496               syserror(progname);
00497        if ((zfd = open(zspec, O_RDONLY)) == -1) {
00498               double zvalue;
00499               register int  x;
00500               if (!isflt(zspec) || (zvalue = atof(zspec)) <= 0.0)
00501                      syserror(zspec);
00502               for (x = scanlen(&tresolu); x-- > 0; )
00503                      zin[x] = zvalue;
00504        }
00505                                    /* compute transferrable perimeter */
00506        xlim = (struct bound *)malloc(numscans(&tresolu)*sizeof(struct bound));
00507        if (xlim == NULL)
00508               syserror(progname);
00509        if (!getperim(xlim, &ylim, zin, zfd)) {   /* overlapping area? */
00510               free((void *)zin);
00511               free((void *)xlim);
00512               if (zfd != -1)
00513                      close(zfd);
00514               fclose(pfp);
00515               return;
00516        }
00517                                    /* allocate scanlines */
00518        scanin = (COLR *)malloc(scanlen(&tresolu)*sizeof(COLR));
00519        plast = (struct position *)calloc(scanlen(&tresolu),
00520                      sizeof(struct position));
00521        if ((scanin == NULL) | (plast == NULL))
00522               syserror(progname);
00523                                    /* skip to starting point */
00524        for (y = 0; y < ylim.min; y++)
00525               if (freadcolrs(scanin, scanlen(&tresolu), pfp) < 0) {
00526                      fprintf(stderr, "%s: read error\n", pfile);
00527                      exit(1);
00528               }
00529        if (zfd != -1 && lseek(zfd,
00530                      (off_t)ylim.min*scanlen(&tresolu)*sizeof(float),
00531                      SEEK_SET) < 0)
00532               syserror(zspec);
00533                                    /* load image */
00534        for (y = ylim.min; y <= ylim.max; y++) {
00535               if (freadcolrs(scanin, scanlen(&tresolu), pfp) < 0) {
00536                      fprintf(stderr, "%s: read error\n", pfile);
00537                      exit(1);
00538               }
00539               if (zfd != -1 && read(zfd, (char *)zin,
00540                             scanlen(&tresolu)*sizeof(float))
00541                             < scanlen(&tresolu)*sizeof(float))
00542                      syserror(zspec);
00543               addscanline(xlim+y, y, scanin, zin, plast);
00544        }
00545                                    /* clean up */
00546        free((void *)xlim);
00547        free((void *)scanin);
00548        free((void *)zin);
00549        free((void *)plast);
00550        fclose(pfp);
00551        if (zfd != -1)
00552               close(zfd);
00553 }
00554 
00555 
00556 static int
00557 pixform(             /* compute view1 to view2 matrix */
00558        register MAT4 xfmat,
00559        register VIEW *vw1,
00560        register VIEW *vw2
00561 )
00562 {
00563        double m4t[4][4];
00564 
00565        if ((vw1->type != VT_PER) & (vw1->type != VT_PAR))
00566               return(0);
00567        if ((vw2->type != VT_PER) & (vw2->type != VT_PAR))
00568               return(0);
00569        setident4(xfmat);
00570        xfmat[0][0] = vw1->hvec[0];
00571        xfmat[0][1] = vw1->hvec[1];
00572        xfmat[0][2] = vw1->hvec[2];
00573        xfmat[1][0] = vw1->vvec[0];
00574        xfmat[1][1] = vw1->vvec[1];
00575        xfmat[1][2] = vw1->vvec[2];
00576        xfmat[2][0] = vw1->vdir[0];
00577        xfmat[2][1] = vw1->vdir[1];
00578        xfmat[2][2] = vw1->vdir[2];
00579        xfmat[3][0] = vw1->vp[0];
00580        xfmat[3][1] = vw1->vp[1];
00581        xfmat[3][2] = vw1->vp[2];
00582        setident4(m4t);
00583        m4t[0][0] = vw2->hvec[0]/vw2->hn2;
00584        m4t[1][0] = vw2->hvec[1]/vw2->hn2;
00585        m4t[2][0] = vw2->hvec[2]/vw2->hn2;
00586        m4t[3][0] = -DOT(vw2->vp,vw2->hvec)/vw2->hn2;
00587        m4t[0][1] = vw2->vvec[0]/vw2->vn2;
00588        m4t[1][1] = vw2->vvec[1]/vw2->vn2;
00589        m4t[2][1] = vw2->vvec[2]/vw2->vn2;
00590        m4t[3][1] = -DOT(vw2->vp,vw2->vvec)/vw2->vn2;
00591        m4t[0][2] = vw2->vdir[0];
00592        m4t[1][2] = vw2->vdir[1];
00593        m4t[2][2] = vw2->vdir[2];
00594        m4t[3][2] = -DOT(vw2->vp,vw2->vdir);
00595        multmat4(xfmat, xfmat, m4t);
00596        return(1);
00597 }
00598 
00599 
00600 static void
00601 addscanline(  /* add scanline to output */
00602        struct bound  *xl,
00603        int    y,
00604        COLR   *pline,
00605        float  *zline,
00606        struct position      *lasty        /* input/output */
00607 )
00608 {
00609        FVECT  pos;
00610        struct position      lastx, newpos;
00611        double wt;
00612        register int  x;
00613 
00614        lastx.z = 0;
00615        for (x = xl->max; x >= xl->min; x--) {
00616               pix2loc(pos, &tresolu, x, y);
00617               pos[2] = zline[x];
00618               if ((wt = movepixel(pos)) <= FTINY) {
00619                      lasty[x].z = lastx.z = 0;   /* mark invalid */
00620                      continue;
00621               }
00622                                    /* add pixel to our image */
00623               newpos.x = pos[0] * hresolu;
00624               newpos.y = pos[1] * vresolu;
00625               newpos.z = zline[x];
00626               addpixel(&newpos, &lastx, &lasty[x], pline[x], wt, pos[2]);
00627               lasty[x].x = lastx.x = newpos.x;
00628               lasty[x].y = lastx.y = newpos.y;
00629               lasty[x].z = lastx.z = newpos.z;
00630        }
00631 }
00632 
00633 
00634 static void
00635 addpixel(            /* fill in pixel parallelogram */
00636        struct position      *p0,
00637        struct position      *p1,
00638        struct position      *p2,
00639        COLR   pix,
00640        double w,
00641        double z
00642 )
00643 {
00644        double zt = 2.*zeps*p0->z;         /* threshold */
00645        COLOR  pval;                       /* converted+weighted pixel */
00646        int    s1x, s1y, s2x, s2y;         /* step sizes */
00647        int    l1, l2, c1, c2;                    /* side lengths and counters */
00648        int    p1isy;                      /* p0p1 along y? */
00649        int    x1, y1;                            /* p1 position */
00650        register int  x, y;                /* final position */
00651 
00652                                    /* compute vector p0p1 */
00653        if (fillo&F_FORE && ABS(p1->z-p0->z) <= zt) {
00654               s1x = p1->x - p0->x;
00655               s1y = p1->y - p0->y;
00656               l1 = ABS(s1x);
00657               if ( (p1isy = (ABS(s1y) > l1)) )
00658                      l1 = ABS(s1y);
00659               else if (l1 < 1)
00660                      l1 = 1;
00661        } else {
00662               l1 = s1x = s1y = 1;
00663               p1isy = -1;
00664        }
00665                                    /* compute vector p0p2 */
00666        if (fillo&F_FORE && ABS(p2->z-p0->z) <= zt) {
00667               s2x = p2->x - p0->x;
00668               s2y = p2->y - p0->y;
00669               if (p1isy == 1)
00670                      l2 = ABS(s2x);
00671               else {
00672                      l2 = ABS(s2y);
00673                      if (p1isy != 0 && ABS(s2x) > l2)
00674                             l2 = ABS(s2x);
00675               }
00676               if (l2 < 1)
00677                      l2 = 1;
00678        } else
00679               l2 = s2x = s2y = 1;
00680                                    /* fill the parallelogram */
00681        if (averaging) {
00682               colr_color(pval, pix);
00683               scalecolor(pval, w);
00684        }
00685        for (c1 = l1; c1-- > 0; ) {
00686               x1 = p0->x + c1*s1x/l1;
00687               y1 = p0->y + c1*s1y/l1;
00688               for (c2 = l2; c2-- > 0; ) {
00689                      x = x1 + c2*s2x/l2;
00690                      if ((x < 0) | (x >= hresolu))
00691                             continue;
00692                      y = y1 + c2*s2y/l2;
00693                      if ((y < 0) | (y >= vresolu))
00694                             continue;
00695                      if (averaging) {
00696                             if (zscan(y)[x] <= 0 || zscan(y)[x]-z
00697                                           > zeps*zscan(y)[x]) {
00698                                    copycolor(sscan(y)[x], pval);
00699                                    wscan(y)[x] = w;
00700                                    zscan(y)[x] = z;
00701                             } else if (z-zscan(y)[x] <= zeps*zscan(y)[x]) {
00702                                    addcolor(sscan(y)[x], pval);
00703                                    wscan(y)[x] += w;
00704                             }
00705                      } else if (zscan(y)[x] <= 0 || zscan(y)[x]-z
00706                                           > zeps*zscan(y)[x]) {
00707                             copycolr(pscan(y)[x], pix);
00708                             zscan(y)[x] = z;
00709                      }
00710               }
00711        }
00712 }
00713 
00714 
00715 static double
00716 movepixel(                         /* reposition image point */
00717        register FVECT       pos
00718 )
00719 {
00720        FVECT  pt, tdir, odir;
00721        double d;
00722        
00723        if (pos[2] <= 0)            /* empty pixel */
00724               return(0);
00725        if (usematrix) {
00726               pos[0] += theirview.hoff - .5;
00727               pos[1] += theirview.voff - .5;
00728               if (normdist & (theirview.type == VT_PER))
00729                      d = sqrt(1. + pos[0]*pos[0]*theirview.hn2
00730                                    + pos[1]*pos[1]*theirview.vn2);
00731               else
00732                      d = 1.;
00733               pos[2] += d*theirview.vfore;
00734               if (theirview.type == VT_PER) {
00735                      pos[2] /= d;
00736                      pos[0] *= pos[2];
00737                      pos[1] *= pos[2];
00738               }
00739               multp3(pos, pos, theirs2ours);
00740               if (pos[2] <= ourview.vfore)
00741                      return(0);
00742               if (ourview.type == VT_PER) {
00743                      pos[0] /= pos[2];
00744                      pos[1] /= pos[2];
00745               }
00746               pos[0] += .5 - ourview.hoff;
00747               pos[1] += .5 - ourview.voff;
00748               pos[2] -= ourview.vfore;
00749        } else {
00750               if (viewray(pt, tdir, &theirview, pos[0], pos[1]) < -FTINY)
00751                      return(0);
00752               if ((!normdist) & (theirview.type == VT_PER))    /* adjust */
00753                      pos[2] *= sqrt(1. + pos[0]*pos[0]*theirview.hn2
00754                                    + pos[1]*pos[1]*theirview.vn2);
00755               pt[0] += tdir[0]*pos[2];
00756               pt[1] += tdir[1]*pos[2];
00757               pt[2] += tdir[2]*pos[2];
00758               viewloc(pos, &ourview, pt);
00759               if (pos[2] <= 0)
00760                      return(0);
00761        }
00762        if ((pos[0] < 0) | (pos[0] >= 1-FTINY) | (pos[1] < 0) | (pos[1] >= 1-FTINY))
00763               return(0);
00764        if (!averaging)
00765               return(1);
00766                                           /* compute pixel weight */
00767        if (ourview.type == VT_PAR) {
00768               d = DOT(ourview.vdir,tdir);
00769               d = 1. - d*d;
00770        } else {
00771               VSUB(odir, pt, ourview.vp);
00772               d = DOT(odir,tdir);
00773               d = 1. - d*d/DOT(odir,odir);
00774        }
00775        if (d <= 1./MAXWT/MAXWT)
00776               return(MAXWT);              /* clip to maximum weight */
00777        return(1./sqrt(d));
00778 }
00779 
00780 
00781 static int
00782 getperim(            /* compute overlapping image area */
00783        register struct bound       *xl,
00784        struct bound  *yl,
00785        float  *zline,
00786        int    zfd
00787 )
00788 {
00789        int    step;
00790        FVECT  pos;
00791        register int  x, y;
00792                                           /* set up step size */
00793        if (scanlen(&tresolu) < numscans(&tresolu))
00794               step = scanlen(&tresolu)/NSTEPS;
00795        else
00796               step = numscans(&tresolu)/NSTEPS;
00797        if (step < MINSTEP) {                     /* not worth cropping? */
00798               yl->min = 0;
00799               yl->max = numscans(&tresolu) - 1;
00800               x = scanlen(&tresolu) - 1;
00801               for (y = numscans(&tresolu); y--; ) {
00802                      xl[y].min = 0;
00803                      xl[y].max = x;
00804               }
00805               return(1);
00806        }
00807        yl->min = 32000; yl->max = 0;             /* search for points on image */
00808        for (y = step - 1; y < numscans(&tresolu); y += step) {
00809               if (zfd != -1) {
00810                      if (lseek(zfd, (off_t)y*scanlen(&tresolu)*sizeof(float),
00811                                    SEEK_SET) < 0)
00812                             syserror("lseek");
00813                      if (read(zfd, (char *)zline,
00814                                    scanlen(&tresolu)*sizeof(float))
00815                                    < scanlen(&tresolu)*sizeof(float))
00816                             syserror("read");
00817               }
00818               xl[y].min = 32000; xl[y].max = 0;         /* x max */
00819               for (x = scanlen(&tresolu); (x -= step) > 0; ) {
00820                      pix2loc(pos, &tresolu, x, y);
00821                      pos[2] = zline[x];
00822                      if (movepixel(pos) > FTINY) {
00823                             xl[y].max = x + step - 1;
00824                             xl[y].min = x - step + 1;   /* x min */
00825                             if (xl[y].min < 0)
00826                                    xl[y].min = 0;
00827                             for (x = step - 1; x < xl[y].max; x += step) {
00828                                    pix2loc(pos, &tresolu, x, y);
00829                                    pos[2] = zline[x];
00830                                    if (movepixel(pos) > FTINY) {
00831                                           xl[y].min = x - step + 1;
00832                                           break;
00833                                    }
00834                             }
00835                             if (y < yl->min)            /* y limits */
00836                                    yl->min = y - step + 1;
00837                             yl->max = y + step - 1;
00838                             break;
00839                      }
00840               }
00841                                                  /* fill in between */
00842               if (y < step) {
00843                      xl[y-1].min = xl[y].min;
00844                      xl[y-1].max = xl[y].max;
00845               } else {
00846                      if (xl[y].min < xl[y-step].min)
00847                             xl[y-1].min = xl[y].min;
00848                      else
00849                             xl[y-1].min = xl[y-step].min;
00850                      if (xl[y].max > xl[y-step].max)
00851                             xl[y-1].max = xl[y].max;
00852                      else
00853                             xl[y-1].max = xl[y-step].max;
00854               }
00855               for (x = 2; x < step; x++)
00856                      *(xl+y-x) = *(xl+y-1);
00857        }
00858        if (yl->max >= numscans(&tresolu))
00859               yl->max = numscans(&tresolu) - 1;
00860        y -= step;
00861        for (x = numscans(&tresolu) - 1; x > y; x--)     /* fill bottom rows */
00862               *(xl+x) = *(xl+y);
00863        return(yl->max >= yl->min);
00864 }
00865 
00866 
00867 static void
00868 backpicture(                /* background fill algorithm */
00869        fillfunc_t *fill,
00870        int    samp
00871 )
00872 {
00873        int    *yback, xback;
00874        int    y;
00875        register int  x, i;
00876                                                  /* get back buffer */
00877        yback = (int *)malloc(hresolu*sizeof(int));
00878        if (yback == NULL)
00879               syserror(progname);
00880        for (x = 0; x < hresolu; x++)
00881               yback[x] = -2;
00882        /*
00883         * Xback and yback are the pixel locations of suitable
00884         * background values in each direction.
00885         * A value of -2 means unassigned, and -1 means
00886         * that there is no suitable background in this direction.
00887         */
00888                                                  /* fill image */
00889        for (y = 0; y < vresolu; y++) {
00890               xback = -2;
00891               for (x = 0; x < hresolu; x++)
00892                      if (zscan(y)[x] <= 0) {            /* empty pixel */
00893                             /*
00894                              * First, find background from above or below.
00895                              * (farthest assigned pixel)
00896                              */
00897                             if (yback[x] == -2) {
00898                                    for (i = y+1; i < vresolu; i++)
00899                                           if (zscan(i)[x] > 0)
00900                                                  break;
00901                                    if (i < vresolu
00902                             && (y <= 0 || zscan(y-1)[x] < zscan(i)[x]))
00903                                           yback[x] = i;
00904                                    else
00905                                           yback[x] = y-1;
00906                             }
00907                             /*
00908                              * Next, find background from left or right.
00909                              */
00910                             if (xback == -2) {
00911                                    for (i = x+1; i < hresolu; i++)
00912                                           if (zscan(y)[i] > 0)
00913                                                  break;
00914                                    if (i < hresolu
00915                             && (x <= 0 || zscan(y)[x-1] < zscan(y)[i]))
00916                                           xback = i;
00917                                    else
00918                                           xback = x-1;
00919                             }
00920                             /*
00921                              * If we have no background for this pixel,
00922                              * use the given fill function.
00923                              */
00924                             if (xback < 0 && yback[x] < 0)
00925                                    goto fillit;
00926                             /*
00927                              * Compare, and use the background that is
00928                              * farther, unless one of them is next to us.
00929                              * If the background is too distant, call
00930                              * the fill function.
00931                              */
00932                             if ( yback[x] < 0
00933                                    || (xback >= 0 && ABS(x-xback) <= 1)
00934                                    || ( ABS(y-yback[x]) > 1
00935                                           && zscan(yback[x])[x]
00936                                           < zscan(y)[xback] ) ) {
00937                                    if (samp > 0 && ABS(x-xback) >= samp)
00938                                           goto fillit;
00939                                    if (averaging) {
00940                                           copycolor(sscan(y)[x],
00941                                                  sscan(y)[xback]);
00942                                           wscan(y)[x] = wscan(y)[xback];
00943                                    } else
00944                                           copycolr(pscan(y)[x],
00945                                                  pscan(y)[xback]);
00946                                    zscan(y)[x] = zscan(y)[xback];
00947                             } else {
00948                                    if (samp > 0 && ABS(y-yback[x]) > samp)
00949                                           goto fillit;
00950                                    if (averaging) {
00951                                           copycolor(sscan(y)[x],
00952                                                  sscan(yback[x])[x]);
00953                                           wscan(y)[x] =
00954                                                  wscan(yback[x])[x];
00955                                    } else
00956                                           copycolr(pscan(y)[x],
00957                                                  pscan(yback[x])[x]);
00958                                    zscan(y)[x] = zscan(yback[x])[x];
00959                             }
00960                             continue;
00961                      fillit:
00962                             (*fill)(x,y);
00963                             if (fill == rcalfill) {            /* use it */
00964                                    clearqueue();
00965                                    xback = x;
00966                                    yback[x] = y;
00967                             }
00968                      } else {                           /* full pixel */
00969                             yback[x] = -2;
00970                             xback = -2;
00971                      }
00972        }
00973        free((void *)yback);
00974 }
00975 
00976 
00977 static void
00978 fillpicture(         /* paint in empty pixels using fill */
00979        fillfunc_t *fill
00980 )
00981 {
00982        register int  x, y;
00983 
00984        for (y = 0; y < vresolu; y++)
00985               for (x = 0; x < hresolu; x++)
00986                      if (zscan(y)[x] <= 0)
00987                             (*fill)(x,y);
00988        if (fill == rcalfill)
00989               clearqueue();
00990 }
00991 
00992 
00993 static int
00994 clipaft(void)               /* perform aft clipping as indicated */
00995 {
00996        register int  x, y;
00997        int    adjtest = (ourview.type == VT_PER) & zisnorm;
00998        double tstdist;
00999        double yzn2, vx;
01000 
01001        if (ourview.vaft <= FTINY)
01002               return(0);
01003        tstdist = ourview.vaft - ourview.vfore;
01004        for (y = 0; y < vresolu; y++) {
01005               if (adjtest) {                            /* adjust test */
01006                      yzn2 = (y+.5)/vresolu + ourview.voff - .5;
01007                      yzn2 = 1. + yzn2*yzn2*ourview.vn2;
01008                      tstdist = (ourview.vaft - ourview.vfore)*sqrt(yzn2);
01009               }
01010               for (x = 0; x < hresolu; x++)
01011                      if (zscan(y)[x] > tstdist) {
01012                             if (adjtest) {
01013                                    vx = (x+.5)/hresolu + ourview.hoff - .5;
01014                                    if (zscan(y)[x] <= (ourview.vaft -
01015                                                  ourview.vfore) *
01016                                           sqrt(vx*vx*ourview.hn2 + yzn2))
01017                                           continue;
01018                             }
01019                             if (averaging)
01020                                    memset(sscan(y)[x], '\0', sizeof(COLOR));
01021                             else
01022                                    memset(pscan(y)[x], '\0', sizeof(COLR));
01023                             zscan(y)[x] = 0.0;
01024                      }
01025        }
01026        return(1);
01027 }
01028 
01029 
01030 static int
01031 addblur(void)                      /* add to blurred picture */
01032 {
01033        COLOR  cval;
01034        double d;
01035        register int  i;
01036 
01037        if (!blurring)
01038               return(0);
01039        i = hresolu*vresolu;
01040        if (nvavg < 2)
01041               if (averaging)
01042                      while (i--) {
01043                             copycolor(ourbpict[i], ourspict[i]);
01044                             d = 1.0/ourweigh[i];
01045                             scalecolor(ourbpict[i], d);
01046                      }
01047               else
01048                      while (i--)
01049                             colr_color(ourbpict[i], ourpict[i]);
01050        else
01051               if (averaging)
01052                      while (i--) {
01053                             copycolor(cval, ourspict[i]);
01054                             d = 1.0/ourweigh[i];
01055                             scalecolor(cval, d);
01056                             addcolor(ourbpict[i], cval);
01057                      }
01058               else
01059                      while (i--) {
01060                             colr_color(cval, ourpict[i]);
01061                             addcolor(ourbpict[i], cval);
01062                      }
01063                             /* print view */
01064        printf("VIEW%d:", nvavg);
01065        fprintview(&ourview, stdout);
01066        putchar('\n');
01067        return(1);
01068 }
01069 
01070 
01071 static void
01072 writepicture(void)                        /* write out picture (alters buffer) */
01073 {
01074        int    y;
01075        register int  x;
01076        double d;
01077 
01078        fprtresolu(hresolu, vresolu, stdout);
01079        for (y = vresolu-1; y >= 0; y--)
01080               if (blurring) {
01081                      for (x = 0; x < hresolu; x++) {    /* compute avg. */
01082                             d = rexpadj/nvavg;
01083                             scalecolor(bscan(y)[x], d);
01084                      }
01085                      if (fwritescan(bscan(y), hresolu, stdout) < 0)
01086                             syserror(progname);
01087               } else if (averaging) {
01088                      for (x = 0; x < hresolu; x++) {    /* average pixels */
01089                             d = rexpadj/wscan(y)[x];
01090                             scalecolor(sscan(y)[x], d);
01091                      }
01092                      if (fwritescan(sscan(y), hresolu, stdout) < 0)
01093                             syserror(progname);
01094               } else {
01095                      if (expadj)
01096                             shiftcolrs(pscan(y), hresolu, expadj);
01097                      if (fwritecolrs(pscan(y), hresolu, stdout) < 0)
01098                             syserror(progname);
01099               }
01100 }
01101 
01102 
01103 static void
01104 writedistance(                     /* write out z file (alters buffer) */
01105        char   *fname
01106 )
01107 {
01108        int    donorm = normdist & !zisnorm ? 1 :
01109                      (ourview.type == VT_PER) & !normdist & zisnorm ? -1 : 0;
01110        int    fd;
01111        int    y;
01112 
01113        if ((fd = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) == -1)
01114               syserror(fname);
01115        for (y = vresolu-1; y >= 0; y--) {
01116               if (donorm) {
01117                      double vx, yzn2, d;
01118                      register int  x;
01119                      yzn2 = (y+.5)/vresolu + ourview.voff - .5;
01120                      yzn2 = 1. + yzn2*yzn2*ourview.vn2;
01121                      for (x = 0; x < hresolu; x++) {
01122                             vx = (x+.5)/hresolu + ourview.hoff - .5;
01123                             d = sqrt(vx*vx*ourview.hn2 + yzn2);
01124                             if (donorm > 0)
01125                                    zscan(y)[x] *= d;
01126                             else
01127                                    zscan(y)[x] /= d;
01128                      }
01129               }
01130               if (write(fd, (char *)zscan(y), hresolu*sizeof(float))
01131                             < hresolu*sizeof(float))
01132                      syserror(fname);
01133        }
01134        close(fd);
01135 }
01136 
01137 
01138 static void
01139 backfill(                          /* fill pixel with background */
01140        int    x,
01141        int    y
01142 )
01143 {
01144        if (averaging) {
01145               copycolor(sscan(y)[x], backcolor);
01146               wscan(y)[x] = 1;
01147        } else
01148               copycolr(pscan(y)[x], backcolr);
01149        zscan(y)[x] = backz;
01150 }
01151 
01152 
01153 static void
01154 calstart(                    /* start fill calculation */
01155        char   *prog,
01156        char   *args
01157 )
01158 {
01159        char   combuf[512];
01160        char   *argv[64];
01161        int    rval;
01162        register char **wp, *cp;
01163 
01164        if (PDesc.running) {
01165               fprintf(stderr, "%s: too many calculations\n", progname);
01166               exit(1);
01167        }
01168        strcpy(combuf, prog);
01169        strcat(combuf, args);
01170        cp = combuf;
01171        wp = argv;
01172        for ( ; ; ) {
01173               while (isspace(*cp)) /* nullify spaces */
01174                      *cp++ = '\0';
01175               if (!*cp)            /* all done? */
01176                      break;
01177               *wp++ = cp;          /* add argument to list */
01178               while (*++cp && !isspace(*cp))
01179                      ;
01180        }
01181        *wp = NULL;
01182                                           /* start process */
01183        if ((rval = open_process(&PDesc, argv)) < 0)
01184               syserror(progname);
01185        if (rval == 0) {
01186               fprintf(stderr, "%s: command not found\n", argv[0]);
01187               exit(1);
01188        }
01189        packsiz = rval/(6*sizeof(float)) - 1;
01190        if (packsiz > PACKSIZ)
01191               packsiz = PACKSIZ;
01192        queuesiz = 0;
01193 }
01194 
01195 
01196 static void
01197 caldone(void)                               /* done with calculation */
01198 {
01199        if (!PDesc.running)
01200               return;
01201        clearqueue();
01202        close_process(&PDesc);
01203 }
01204 
01205 
01206 static void
01207 rcalfill(                          /* fill with ray-calculated pixel */
01208        int    x,
01209        int    y
01210 )
01211 {
01212        if (queuesiz >= packsiz)    /* flush queue if needed */
01213               clearqueue();
01214                                    /* add position to queue */
01215        queue[queuesiz][0] = x;
01216        queue[queuesiz][1] = y;
01217        queuesiz++;
01218 }
01219 
01220 
01221 static void
01222 clearqueue(void)                          /* process queue */
01223 {
01224        FVECT  orig, dir;
01225        float  fbuf[6*(PACKSIZ+1)];
01226        register float       *fbp;
01227        register int  i;
01228        double vx, vy;
01229 
01230        if (queuesiz == 0)
01231               return;
01232        fbp = fbuf;
01233        for (i = 0; i < queuesiz; i++) {
01234               viewray(orig, dir, &ourview,
01235                             (queue[i][0]+.5)/hresolu,
01236                             (queue[i][1]+.5)/vresolu);
01237               *fbp++ = orig[0]; *fbp++ = orig[1]; *fbp++ = orig[2];
01238               *fbp++ = dir[0]; *fbp++ = dir[1]; *fbp++ = dir[2];
01239        }
01240                                    /* mark end and get results */
01241        memset((char *)fbp, '\0', 6*sizeof(float));
01242        if (process(&PDesc, (char *)fbuf, (char *)fbuf,
01243                      4*sizeof(float)*(queuesiz+1),
01244                      6*sizeof(float)*(queuesiz+1)) !=
01245                      4*sizeof(float)*(queuesiz+1)) {
01246               fprintf(stderr, "%s: error reading from rtrace process\n",
01247                             progname);
01248               exit(1);
01249        }
01250        fbp = fbuf;
01251        for (i = 0; i < queuesiz; i++) {
01252               if (ourexp > 0 && ourexp != 1.0) {
01253                      fbp[0] *= ourexp;
01254                      fbp[1] *= ourexp;
01255                      fbp[2] *= ourexp;
01256               }
01257               if (averaging) {
01258                      setcolor(sscan(queue[i][1])[queue[i][0]],
01259                                    fbp[0], fbp[1], fbp[2]);
01260                      wscan(queue[i][1])[queue[i][0]] = 1;
01261               } else
01262                      setcolr(pscan(queue[i][1])[queue[i][0]],
01263                                    fbp[0], fbp[1], fbp[2]);
01264               if (zisnorm)
01265                      zscan(queue[i][1])[queue[i][0]] = fbp[3];
01266               else {
01267                      vx = (queue[i][0]+.5)/hresolu + ourview.hoff - .5;
01268                      vy = (queue[i][1]+.5)/vresolu + ourview.voff - .5;
01269                      zscan(queue[i][1])[queue[i][0]] = fbp[3] / sqrt(1. +
01270                                    vx*vx*ourview.hn2 + vy*vy*ourview.vn2);
01271               }
01272               fbp += 4;
01273        }
01274        queuesiz = 0;
01275 }
01276 
01277 
01278 static void
01279 syserror(                   /* report error and exit */
01280        char   *s
01281 )
01282 {
01283        perror(s);
01284        exit(1);
01285 }