Example #1
0
static int read_colors(const char *name, const char *mapset,
		       struct Colors *colors)
{
    FILE *fd;
    int stat;
    char buf[1024];

    fd = G_fopen_old_misc(RASTER3D_DIRECTORY, RASTER3D_COLOR_ELEMENT, name, mapset);
    if (!fd)
	return -2;

    /*
     * first line in 4.0 color files is %
     * otherwise it is pre 4.0
     */
    if (fgets(buf, sizeof buf, fd) == NULL) {
	fclose(fd);
	return -1;
    }
    G_fseek(fd, 0L, 0);

    G_strip(buf);
    if (*buf == '%') {		/* 4.0 format */
	stat = read_new_colors(fd, colors);
	colors->version = 0;	/* 4.0 format */
    }
    else {
	stat = read_old_colors(fd, colors);
	colors->version = -1;	/* pre 4.0 format */
    }
    fclose(fd);
    return stat;
}
Example #2
0
static int file_cpy(FILE * from, FILE * to)
{
    char buf[BUFSIZ];
    size_t size;
    int written = 0;

    while (1) {
	size = fread(buf, 1, BUFSIZ, from);
	if (!size) {
	    if (written) {
		fflush(to);
		G_fseek(to, 0L, SEEK_SET);
	    }
	    return (0);
	}
	if (!fwrite(buf, 1, size, to)) {
	    G_warning(_("Unable to write to file"));
	    return (-1);
	}
	written = 1;
    }

    /* NOTREACHED */
    return -1;
}
Example #3
0
/* on error, returns -1, otherwise returns 0 */
struct dxf_file *dxf_open(char *file)
{
    struct dxf_file *dxf;

    dxf = (struct dxf_file *)G_malloc(sizeof(struct dxf_file));

    dxf->name = G_store(file);
    if (!(dxf->fp = fopen(file, "r")))
	return NULL;

    /* get the file size */
    G_fseek(dxf->fp, 0L, SEEK_END);
    dxf->size = G_ftell(dxf->fp);
    rewind(dxf->fp);

    dxf->pos = 0;

    if (dxf->size < 500000)
	dxf->percent = 10;
    else if (dxf->size < 800000)
	dxf->percent = 5;
    else
	dxf->percent = 2;

    /* initialize G_percent() */
    G_percent(0, 100, dxf->percent);

    return dxf;
}
Example #4
0
/*!
  \brief Set struct gvfile position.
 
  Start positions:
  
   - SEEK_SET (start)
   - SEEK_CUR (current position)
   - SEEK_END (end)
  
  \param file pointer to struct gvfile structure
  \param offset offset position
  \param whence start position

  \return 0 OK
  \return -1 error
*/
int dig_fseek(struct gvfile * file, off_t offset, int whence)
{
    if (file->loaded) {	 /* using memory */
	switch (whence) {
	case SEEK_SET:
	    file->current = file->start + offset;
	    break;
	case SEEK_CUR:
	    file->current += offset;
	    break;
	case SEEK_END:
	    file->current = file->start + file->size + offset;
	    break;
	}
	return 0;
    }

    G_fseek(file->file, offset, whence);

    return  0;
}
Example #5
0
/* open the file whose name is pathname in access mode */
FILE* 
open_stream(char* pathname, AMI_stream_type st) {

  FILE* fp = NULL;
  assert(pathname);

  switch (st) {
  case   AMI_READ_STREAM:
    fp = fopen(pathname, "rb");
    break;
  case   AMI_WRITE_STREAM:
    fp = fopen(pathname, "wb");
    break;
  case AMI_APPEND_WRITE_STREAM:
    fp = fopen(pathname, "ab");
    break;
  case AMI_APPEND_STREAM:
    fp = fopen(pathname, "ab+");
    assert(fp);
    G_fseek (fp, 0, SEEK_END);
    break;
  case AMI_READ_WRITE_STREAM: 
      fp = fopen(pathname, "rb+");
      if (!fp) {
	//if file does not exist, create it
      fp = fopen(pathname, "wb+");
      }
      break;
  }
  if (!fp) {
    perror(pathname);
    assert(0);
    exit(1);
  }
  assert(fp);
  return fp;
}
Example #6
0
int get_item(FILE * fd, int *type, long *cat, double **x, double **y,
	     int *count, struct Categories *labels)
{
    static double *X = NULL;
    static double *Y = NULL;
    static int nalloc = 0;
    char buf[1024];
    char lbl[1024];
    char east[256], north[256];
    double e, n;
    long offset;

    *cat = 0;
    *count = 0;
    *type = 0;

    /* scan until we find the start of a new feature */
    while (G_getl2(buf, sizeof buf, fd)) {
	/* skip comments and blank lines */
	if ((*buf == '#') || (*buf == '\0'))
	    continue;

	G_strip(buf);
	if (*buf == 'A' || *buf == 'a') {
	    *type = 'A';
	    break;
	}
	if (*buf == 'L' || *buf == 'l') {
	    *type = 'L';
	    break;
	}
	if (*buf == 'P' || *buf == 'p') {
	    *type = 'P';
	    break;
	}
    }
    if (*type == 0)
	return 0;

    /* read the feature's data */
    while (1) {
	offset = G_ftell(fd);

	if (!G_getl2(buf, (sizeof buf) - 1, fd))
	    break;

	/* skip comments and blank lines */
	if ((*buf == '#') || (*buf == '\0'))
	    continue;

	G_strip(buf);

	/* if we've found the next feature, rewind to the start of it and complete */
	if (*buf == 'A' || *buf == 'a' ||
	    *buf == 'L' || *buf == 'l' || *buf == 'P' || *buf == 'p') {
	    G_fseek(fd, offset, 0);
	    break;
	}

	/* if we found a cat (and optionally a label), read them and continue to scan */
	if (*buf == '=') {
	    if (sscanf(buf + 1, "%ld", cat) != 1)
		continue;
	    /* probably change this as G_getl2() doesn't store the new line (?) */
	    if (sscanf(buf + 1, "%ld%[^\n]", cat, lbl) == 2) {
		G_strip(lbl);
		Rast_set_c_cat((CELL*) cat, (CELL *) cat, lbl, labels);
	    }
	    continue;
	}
	if (sscanf(buf, "%s %s", east, north) != 2) {
	    G_warning(_("Illegal coordinate <%s, %s>, skipping."), east, north);
	    continue;
	}

	if (!G_scan_northing(north, &n, G_projection())) {
	    G_warning(_("Illegal north coordinate <%s>, skipping."), north);
	    continue;
	}

	if (!G_scan_easting(east, &e, G_projection())) {
	    G_warning(_("Illegal east coordinate <%s>, skipping."), east);
	    continue;
	}

	if (*count >= nalloc) {
	    nalloc += 32;
	    X = (double *)G_realloc(X, nalloc * sizeof(double));
	    Y = (double *)G_realloc(Y, nalloc * sizeof(double));
	}
	X[*count] = e;
	Y[*count] = n;
	(*count)++;
    }
    *x = X;
    *y = Y;
    return 1;
}
Example #7
0
int
COGRR1(double x_or, double y_or, double z_or, int n_rows, int n_cols,
       int n_levs, int n_points, struct quadruple *points,
       struct point_3d skip_point)

/*C
   C       INTERPOLATION BY FUNCTIONAL METHOD : TPS + complete regul.
   c
 */
{
    int secpar_loop();
    static double *w2 = NULL;
    static double *wz2 = NULL;
    static double *wz1 = NULL;
    double amaxa;
    double stepix, stepiy, stepiz, RO, xx, yy, zz, xg, yg, zg, xx2;
    double wm, dx, dy, dz, dxx, dyy, dxy, dxz, dyz, dzz, h, bmgd1,
	bmgd2, etar, zcon, r, ww, wz, r2, hcell, zzcell2,
	etarcell, rcell, wwcell, zzcell;
    double x_crs,x_crsd,x_crsdd,x_crsdr2;
    int n1, k1, k2, k, i1, l, l1, n4, n5, m, i;
    int NGST, LSIZE, ngstc, nszc, ngstr, nszr, ngstl, nszl;
    int POINT();
    int ind, ind1;
    static int first_time_z = 1;
    off_t offset, offset1, offset2;
    int bmask = 1;
    static FCELL *cell = NULL;

    int cond1 = (gradient != NULL) || (aspect1 != NULL) || (aspect2 != NULL);
    int cond2 = (ncurv != NULL) || (gcurv != NULL) || (mcurv != NULL);

#define CEULER .57721566
    /*
       C
       c        character*32 fncdsm
       c normalization
       c
     */
    offset1 = nsizr * nsizc;

    stepix = ew_res / dnorm;
    stepiy = ns_res / dnorm;
    stepiz = tb_res / dnorm;

    if (!w2) {
	if (!(w2 = (double *)G_malloc(sizeof(double) * (KMAX2 + 1)))) {
	    clean();
	    G_fatal_error(_("Not enough memory for %s"), "w2");
	}
    }
    if (!wz2) {
	if (!(wz2 = (double *)G_malloc(sizeof(double) * (KMAX2 + 1)))) {
	    clean();
	    G_fatal_error(_("Not enough memory for %s"), "wz2");
	}
    }
    if (!wz1) {
	if (!(wz1 = (double *)G_malloc(sizeof(double) * (KMAX2 + 1)))) {
	    clean();
	    G_fatal_error(_("Not enough memory for %s"), "wz1");
	}
    }

    if (cell == NULL)
	cell = Rast_allocate_f_buf();

    for (i = 1; i <= n_points; i++) {
	points[i - 1].x = (points[i - 1].x - x_or) / dnorm;
	points[i - 1].y = (points[i - 1].y - y_or) / dnorm;
	points[i - 1].z = (points[i - 1].z - z_or) / dnorm;
    }
    if (cv) {
	skip_point.x = (skip_point.x - x_or) / dnorm;
	skip_point.y = (skip_point.y - y_or) / dnorm;
	skip_point.z = (skip_point.z - z_or) / dnorm;
    }
    n1 = n_points + 1;
    /*
       C
       C      GENERATION OF MATRIX
       C
       C      FIRST COLUMN
       C
     */
    A[1] = 0.;
    for (k = 1; k <= n_points; k++) {
	i1 = k + 1;
	A[i1] = 1.;
    }
    /*
       C
       C      OTHER COLUMNS
       C
     */
    RO = rsm;
    for (k = 1; k <= n_points; k++) {
	k1 = k * n1 + 1;
	k2 = k + 1;
	i1 = k1 + k;
	if (rsm < 0.) {		/*indicates variable smoothing */
	    A[i1] = points[k - 1].sm;
	}
	else {
	    A[i1] = RO;		/* constant smoothing */
	}
	for (l = k2; l <= n_points; l++) {
	    xx = points[k - 1].x - points[l - 1].x;
	    yy = points[k - 1].y - points[l - 1].y;
	    zz = points[k - 1].z - points[l - 1].z;
	    r = sqrt(xx * xx + yy * yy + zz * zz);
	    etar = (fi * r) / 2.;
	    if (etar == 0.) {
		/*              printf ("ident. points in segm.  \n");
		   printf ("x[%d]=%lf,x[%d]=%lf,y[%d]=%lf,y[%d]=%lf\n",
		   k - 1, points[k - 1].x, l - 1, points[l - 1].x, k - 1, points[k - 1].y, l - 1, points[l - 1].y); */
	    }
	    i1 = k1 + l;
	    A[i1] = crs(etar);
	}
    }
    /*
       C
       C       SYMMETRISATION
       C
     */
    amaxa = 1.;
    for (k = 1; k <= n1; k++) {
	k1 = (k - 1) * n1;
	k2 = k + 1;
	for (l = k2; l <= n1; l++) {
	    m = (l - 1) * n1 + k;
	    A[m] = A[k1 + l];
	    amaxa = amax1(A[m], amaxa);
	}
    }

    /*
       C        RIGHT SIDE
       C
     */
    n4 = n1 * n1 + 1;
    A[n4] = 0.;
    for (l = 1; l <= n_points; l++) {
	l1 = n4 + l;
	A[l1] = points[l - 1].w;
    }
    n5 = n1 * (n1 + 1);
    for (i = 1; i <= n5; i++)
	A[i] = A[i] / amaxa;

    /*
       SOLVING OF SYSTEM
     */

    if (LINEQS(n1, n1, 1, &NERROR, &DETERM)) {

	for (k = 1; k <= n_points; k++) {
	    l = n4 + k;
	    b[k] = A[l];
	}
	b[n_points + 1] = A[n4];

	POINT(n_points, points, skip_point);
	if (cv)
	    return 1;
	if (devi != NULL && sig1 == 1)
	    return 1;
	/*
	   C
	   C         INTERPOLATION   *  MOST INNER LOOPS !
	   C
	 */
	NGST = 1;
	LSIZE = 0;

	ngstc = (int)(x_or / ew_res + 0.5) + 1;
	nszc = ngstc + n_cols - 1;
	ngstr = (int)(y_or / ns_res + 0.5) + 1;
	nszr = ngstr + n_rows - 1;
	ngstl = (int)(z_or / tb_res + 0.5) + 1;
	nszl = ngstl + n_levs - 1;

	/*        fprintf(stderr," Progress percentage for each segment ..." ); */
	/*fprintf(stderr,"Before loops,ngstl = %d,nszl =%d\n",ngstl,nszl); */
	for (i = ngstl; i <= nszl; i++) {
	    /*fprintf(stderr,"level=%d\n",i); */
	    /*      G_percent(i, nszl, 2); */
	    offset = offset1 * (i - 1);	/* levels offset */
	    zg = (i - ngstl) * stepiz;
	    for (m = 1; m <= n_points; m++) {
		wz = zg - points[m - 1].z;
		wz1[m] = wz;
		wz2[m] = wz * wz;
	    }
	    for (k = ngstr; k <= nszr; k++) {
		yg = (k - ngstr) * stepiy;
		for (m = 1; m <= n_points; m++) {
		    wm = yg - points[m - 1].y;
		    w[m] = wm;
		    w2[m] = wm * wm;
		}
		if ((cellinp != NULL) && (cellout != NULL) && (i == ngstl))
		    Rast_get_f_row(fdcell, cell, n_rows_in - k);

		for (l = ngstc; l <= nszc; l++) {
		    LSIZE = LSIZE + 1;
		    if (maskmap != NULL)
			bmask = BM_get(bitmask, l - 1, k - 1);	/*bug fix 02/03/00 jh */
		    xg = (l - ngstc) * stepix;
		    ww = 0.;
		    wwcell = 0.;
		    dx = 0.;
		    dy = 0.;
		    dz = 0.;
		    dxx = 0.;
		    dxy = 0.;
		    dxz = 0.;
		    dyy = 0.;
		    dyz = 0.;
		    dzz = 0.;
		    /* compute everything for area which is not masked out
		       and where cross_input map doesn't have nulls */
		    if (bmask == 1 && !(cell && Rast_is_f_null_value(&cell[l - 1]))) {
			h = b[n1];
			hcell = b[n1];
			for (m = 1; m <= n_points; m++) {
			    xx = xg - points[m - 1].x;
			    xx2 = xx * xx;
			    if ((cellinp != NULL) && (cellout != NULL) &&
				(i == ngstl)) {
				zcon = (double)(cell[l - 1] * zmult - z_or) - z_orig_in * zmult;	/* bug fix 02/03/00 jh */
				zcon = zcon / dnorm;
				zzcell = zcon - points[m - 1].z;
				zzcell2 = zzcell * zzcell;
				rcell = sqrt(xx2 + w2[m] + zzcell2);
				etarcell = (fi * rcell) / 2.;
				hcell = hcell + b[m] * crs(etarcell);
			    }
			    r2 = xx2 + w2[m] + wz2[m];
			    r = sqrt(r2);
			    etar = (fi * r) / 2.;

                            crs_full(
                              etar,fi,
                              &x_crs,
                              cond1?&x_crsd:NULL,
                              cond2?&x_crsdr2:NULL,
                              cond2?&x_crsdd:NULL
                            );
                            h = h + b[m] * x_crs;
                            if(cond1)
                            {
                                   bmgd1 = b[m] * x_crsd;
			    dx = dx + bmgd1 * xx;
			    dy = dy + bmgd1 * w[m];
			    dz = dz + bmgd1 * wz1[m];
                            }
                            if(cond2)
                            {
                                   bmgd2 = b[m] * x_crsdd;
                                   bmgd1 = b[m] * x_crsdr2;
			    dyy = dyy + bmgd2 * w2[m] + bmgd1 * w2[m];
			    dzz = dzz + bmgd2 * wz2[m] + bmgd1 * wz2[m];
			    dxy = dxy + bmgd2 * xx * w[m] + bmgd1 * xx * w[m];
                                   dxz = dxz + bmgd2 * xx * wz1[m] + bmgd1 * xx * wz1[m];
                                   dyz = dyz + bmgd2 * w[m] * wz1[m] + bmgd1 * w[m] * wz1[m];
                            }                            
			}
			ww = h + wmin;
			if ((cellinp != NULL) && (cellout != NULL) &&
			    (i == ngstl))
			    wwcell = hcell + wmin;
			az[l] = ww;
			if (first_time_z) {
			    first_time_z = 0;
			    zmaxac = zminac = ww;
			    if ((cellinp != NULL) && (cellout != NULL) &&
				(i == ngstl))
				zmaxacell = zminacell = wwcell;
			}
			zmaxac = amax1(ww, zmaxac);
			zminac = amin1(ww, zminac);
			if ((cellinp != NULL) && (cellout != NULL) &&
			    (i == ngstl)) {
			    zmaxacell = amax1(wwcell, zmaxacell);
			    zminacell = amin1(wwcell, zminacell);
			}
			if ((ww > wmax + 0.1 * (wmax - wmin))
			    || (ww < wmin - 0.1 * (wmax - wmin))) {
			    static int once = 0;

			    if (!once) {
				once = 1;
				fprintf(stderr, "WARNING:\n");
				fprintf(stderr,
					"Overshoot -- increase in tension suggested.\n");
				fprintf(stderr,
					"Overshoot occurs at (%d,%d,%d) cell\n",
					l, k, i);
				fprintf(stderr,
					"The w-value is %lf, wmin is %lf,wmax is %lf\n",
					ww, wmin, wmax);
			    }
			}
		    }		/* skip here if you are in masked area, ww should be 0 */
		    az[l] = ww;
		    adx[l] = dx;
		    ady[l] = dy;
		    adz[l] = dz;
		    /*              printf("\n %f", ww); */
		    adxx[l] = dxx;
		    adxy[l] = dxy;
		    adxz[l] = dxz;
		    adyy[l] = dyy;
		    adyz[l] = dyz;
		    adzz[l] = dzz;
		    if ((gradient != NULL) || (aspect1 != NULL) ||
			(aspect2 != NULL)
			|| (ncurv != NULL) || (gcurv != NULL) ||
			(mcurv != NULL))
			if (!(secpar_loop(ngstc, nszc, l))) {
			    clean();
			    G_fatal_error(_("Secpar_loop failed"));
			}
		    if ((cellinp != NULL) && (cellout != NULL) &&
			(i == ngstl)) {
			zero_array_cell[l - 1] = (FCELL) (wwcell);
		    }
		    if (outz != NULL) {
			zero_array1[l - 1] = (float)(az[l] * sciz);
		    }
		    if (gradient != NULL) {
			zero_array2[l - 1] = (float)(adx[l]);
		    }
		    if (aspect1 != NULL) {
			zero_array3[l - 1] = (float)(ady[l]);
		    }
		    if (aspect2 != NULL) {
			zero_array4[l - 1] = (float)(adz[l]);
		    }
		    if (ncurv != NULL) {
			zero_array5[l - 1] = (float)(adxx[l]);
		    }
		    if (gcurv != NULL) {
			zero_array6[l - 1] = (float)(adyy[l]);
		    }
		    if (mcurv != NULL) {
			zero_array7[l - 1] = (float)(adxy[l]);
		    }
		}		/* columns */
		ind = nsizc * (k - 1) + (ngstc - 1);
		ind1 = ngstc - 1;
		offset2 = offset + ind;	/* rows*cols offset */

		if ((cellinp != NULL) && (cellout != NULL) && (i == ngstl)) {
		    G_fseek(Tmp_fd_cell, ((off_t)ind * sizeof(FCELL)), 0);
		    if (!
			(fwrite
			 (zero_array_cell + ind1, sizeof(FCELL),
			  nszc - ngstc + 1, Tmp_fd_cell))) {
			clean();
			G_fatal_error
			    (_("Not enough disk space--cannot write files"));
		    }
		}
		if (outz != NULL) {
		    G_fseek(Tmp_fd_z, (off_t)(offset2 * sizeof(float)), 0);
		    if (!
			(fwrite
			 (zero_array1 + ind1, sizeof(float), nszc - ngstc + 1,
			  Tmp_fd_z))) {
			clean();
			G_fatal_error
			    (_("Not enough disk space--cannot write files"));
		    }
		}
		if (gradient != NULL) {
		    G_fseek(Tmp_fd_dx, (off_t)(offset2 * sizeof(float)), 0);
		    if (!
			(fwrite
			 (zero_array2 + ind1, sizeof(float), nszc - ngstc + 1,
			  Tmp_fd_dx))) {
			clean();
			G_fatal_error
			    (_("Not enough disk space--cannot write files"));
		    }
		}
		if (aspect1 != NULL) {
		    G_fseek(Tmp_fd_dy, (off_t)(offset2 * sizeof(float)), 0);
		    if (!
			(fwrite
			 (zero_array3 + ind1, sizeof(float), nszc - ngstc + 1,
			  Tmp_fd_dy))) {
			clean();
			G_fatal_error
			    (_("Not enough disk space--cannot write files"));
		    }
		}
		if (aspect2 != NULL) {
		    G_fseek(Tmp_fd_dz, (off_t)(offset2 * sizeof(float)), 0);
		    if (!
			(fwrite
			 (zero_array4 + ind1, sizeof(float), nszc - ngstc + 1,
			  Tmp_fd_dz))) {
			clean();
			G_fatal_error
			    (_("Not enough disk space--cannot write files"));
		    }
		}
		if (ncurv != NULL) {
		    G_fseek(Tmp_fd_xx, (off_t)(offset2 * sizeof(float)), 0);
		    if (!
			(fwrite
			 (zero_array5 + ind1, sizeof(float), nszc - ngstc + 1,
			  Tmp_fd_xx))) {
			clean();
			G_fatal_error
			    (_("Not enough disk space--cannot write files"));
		    }
		}
		if (gcurv != NULL) {
		    G_fseek(Tmp_fd_yy, (off_t)(offset2 * sizeof(float)), 0);
		    if (!
			(fwrite
			 (zero_array6 + ind1, sizeof(float), nszc - ngstc + 1,
			  Tmp_fd_yy))) {
			clean();
			G_fatal_error
			    (_("Not enough disk space--cannot write files"));
		    }
		}
		if (mcurv != NULL) {
		    G_fseek(Tmp_fd_xy, (off_t)(offset2 * sizeof(float)), 0);
		    if (!
			(fwrite
			 (zero_array7 + ind1, sizeof(float), nszc - ngstc + 1,
			  Tmp_fd_xy))) {
			clean();
			G_fatal_error
			    (_("Not enough disk space--cannot write files"));
		    }
		}

	    }
	}
    }				/* falls here if LINEQS() returns 0 */
    /*    total++; */
    /*fprintf(stderr,"wminac=%lf,wmaxac=%lf\n",zminac,zmaxac); */
    return 1;

}
Example #8
0
static void rtree_load_to_memory(struct gvfile *fp, off_t rootpos,
				  struct RTree *t, int off_t_size)
{
    struct RTree_Node *newnode = NULL;
    int i, j, loadnode, maxcard;
    struct spidxstack *last;
    static struct spidxstack *s = NULL;
    int top = 0;

    if (!s) {
	s = G_malloc(MAXLEVEL * sizeof(struct spidxstack));
	for (i = 0; i < MAXLEVEL; i++) {
	    s[i].sn.branch = G_malloc(MAXCARD * sizeof(struct RTree_Branch));
	    for (j = 0; j < MAXCARD; j++) {
		s[i].sn.branch[j].rect.boundary = G_malloc(6 * sizeof(RectReal));
	    }
	}
    }

    /* stack size of t->rootlevel + 1 would be enough because of
     * depth-first postorder traversal:
     * only one node per level on stack at any given time */

    /* add root node position to stack */
    last = &(s[top]);
    G_fseek(fp->file, rootpos, SEEK_SET);
    /* read with dig__fread_port_* fns */
    dig__fread_port_I(&(s[top].sn.count), 1, fp);
    dig__fread_port_I(&(s[top].sn.level), 1, fp);
    maxcard = s[top].sn.level ? t->nodecard : t->leafcard;
    for (j = 0; j < maxcard; j++) {
	dig__fread_port_D(s[top].sn.branch[j].rect.boundary, NUMSIDES, fp);
	dig__fread_port_O(&(s[top].pos[j]), 1, fp, off_t_size);
	/* leaf node: vector object IDs are stored in child.id */
	if (s[top].sn.level == 0) {
	    s[top].sn.branch[j].child.id = (int)s[top].pos[j];
	}
	else {
	    s[top].sn.branch[j].child.ptr = NULL;
	}
    }

    s[top].branch_id = i = 0;

    /* some sort of postorder traversal */
    /* root node is loaded last and returned */

    while (top >= 0) {
	last = &(s[top]);
	loadnode = 1;
	/* this is an internal node in the RTree
	 * all its children are read first,
	 * before it is transferred to the RTree in memory */
	if (s[top].sn.level > 0) {
	    for (i = s[top].branch_id; i < t->nodecard; i++) {
		if (s[top].pos[i] > 0) {
		    s[top++].branch_id = i + 1;
		    G_fseek(fp->file, last->pos[i], SEEK_SET);
		    /* read with dig__fread_port_* fns */
		    dig__fread_port_I(&(s[top].sn.count), 1, fp);
		    dig__fread_port_I(&(s[top].sn.level), 1, fp);
		    maxcard = s[top].sn.level ? t->nodecard : t->leafcard;
		    for (j = 0; j < maxcard; j++) {
			dig__fread_port_D(s[top].sn.branch[j].rect.boundary,
					  NUMSIDES, fp);
			dig__fread_port_O(&(s[top].pos[j]), 1, fp,
					  off_t_size);
			/* leaf node
			 * vector object IDs are stored in file as
			 * off_t but always fit into an int, see dig_structs.h
			 * vector object IDs are transferred to child.id */
			if (s[top].sn.level == 0) {
			    s[top].sn.branch[j].child.id =
				(int)s[top].pos[j];
			}
			else {
			    s[top].sn.branch[j].child.ptr = NULL;
			}
		    }
		    s[top].branch_id = 0;
		    loadnode = 0;
		    break;
		}
		else if (last->pos[i] < 0)
		    G_fatal_error("corrupt spatial index");
	    }
	    if (loadnode) {
		/* nothing else found, ready to load */
		s[top].branch_id = t->nodecard;
	    }
	}
	if (loadnode) {
	    /* ready to load node to memory */

	    newnode = RTreeAllocNode(t, s[top].sn.level);
	    /* copy from stack node */
	    RTreeCopyNode(newnode, &(s[top].sn), t);

	    top--;
	    /* update child of parent node
	     * this node is only updated if its level is > 0, i.e.
	     * this is an internal node
	     * children of internal nodes do not have an ID, instead
	     * they point to the next nodes down the tree */
	    if (top >= 0) {
		s[top].sn.branch[s[top].branch_id - 1].child.ptr = newnode;
	    }
	}
    }
    
    t->root = newnode;
}
Example #9
0
/* unused, coor file is never loaded to memory. Remove ? MM 2010 */
int dig_file_load(struct gvfile * file)
{
    int ret, mode, load;
    const char *cmode;
    size_t size;
    STRUCT_STAT sbuf;

    G_debug(2, "dig_file_load ()");

    if (file->file == NULL) {
	G_warning(_("Unable to load file to memory, file not open"));
	return -1;
    }

    /* Get mode */
    mode = GV_MEMORY_NEVER;
    cmode = G__getenv("GV_MEMORY");
    if (cmode != NULL) {
	if (G_strcasecmp(cmode, "ALWAYS") == 0)
	    mode = GV_MEMORY_ALWAYS;
	else if (G_strcasecmp(cmode, "NEVER") == 0)
	    mode = GV_MEMORY_NEVER;
	else if (G_strcasecmp(cmode, "AUTO") == 0)
	    mode = GV_MEMORY_AUTO;
	else
	    G_warning(_("Vector memory mode not supported, using 'AUTO'"));
    }
    G_debug(2, "  requested mode = %d", mode);


    fstat(fileno(file->file), &sbuf);
    size = sbuf.st_size;

    G_debug(2, "  size = %lu", (long unsigned int) size);

    /* Decide if the file should be loaded */
    /* TODO: I don't know how to get size of free memory (portability) to decide if load or not for auto */
    if (mode == GV_MEMORY_AUTO)
	mode = GV_MEMORY_NEVER;
    if (mode == GV_MEMORY_ALWAYS)
	load = 1;
    else
	load = 0;

    if (load) {
	file->start = G_malloc(size);
	if (file->start == NULL)
	    return -1;

	G_fseek(file->file, 0L, 0);
	ret = fread(file->start, size, 1, file->file);	/* Better to read in smaller portions? */
	G_fseek(file->file, 0L, 0);	/* reset to the beginning */

	if (ret <= 0) {
	    G_free(file->start);
	    return -1;
	}

	file->alloc = size;
	file->size = size;
	file->current = file->start;
	file->end = file->start + size;

	file->loaded = 1;
	G_debug(2, "  file was loaded to the memory");
	return 1;
    }
    else {
	G_debug(2, "  file was not loaded to the memory");
    }

    return 0;
}
Example #10
0
int main(int argc, char *argv[]) {
	struct GModule *module;
	struct {
		struct Option *input;
		struct Option *output;
		struct Option *null;
		struct Option *bytes;
		struct Option *order;
		struct Option *north;
		struct Option *south;
		struct Option *top;
		struct Option *bottom;
		struct Option *east;
		struct Option *west;
		struct Option *rows;
		struct Option *cols;
		struct Option *depths;
	} parm;
	struct {
		struct Flag *integer_in;
		struct Flag *sign;
		struct Flag *depth;
		struct Flag *row;
	} flag;
	const char *input;
	const char *output;
	int is_integer;
	int is_signed;
	int bytes;
	int order;
	int byte_swap;
	RASTER_MAP_TYPE map_type;
	off_t file_size;
	struct History history;
	off_t expected;
	/* Need to be allocated later */
	in_cell = NULL;

	G_gisinit(argv[0]);

	/* Set description */
	module = G_define_module();
	G_add_keyword(_("raster3d"));
	G_add_keyword(_("import"));
	G_add_keyword(_("voxel"));
	module->description =
			_("Imports a binary raster file into a GRASS 3D raster map.");

	parm.input = G_define_standard_option(G_OPT_F_BIN_INPUT);
	parm.input->description = _("Name of binary 3D raster file to be imported");

	parm.output = G_define_standard_option(G_OPT_R3_OUTPUT);

	parm.bytes = G_define_option();
	parm.bytes->key = "bytes";
	parm.bytes->type = TYPE_INTEGER;
	parm.bytes->required = YES;
	parm.bytes->options = "1,2,4,8";
	parm.bytes->description = _("Number of bytes per cell in binary file");

	parm.order = G_define_option();
	parm.order->key = "order";
	parm.order->type = TYPE_STRING;
	parm.order->required = NO;
	parm.order->options = "big,little,native,swap";
	parm.order->description = _("Byte order in binary file");
	parm.order->answer = "native";

	parm.north = G_define_option();
	parm.north->key = "north";
	parm.north->type = TYPE_DOUBLE;
	parm.north->required = YES;
	parm.north->description =
			_("Northern limit of geographic region (outer edge)");
	parm.north->guisection = _("Bounds");

	parm.south = G_define_option();
	parm.south->key = "south";
	parm.south->type = TYPE_DOUBLE;
	parm.south->required = YES;
	parm.south->description =
			_("Southern limit of geographic region (outer edge)");
	parm.south->guisection = _("Bounds");

	parm.east = G_define_option();
	parm.east->key = "east";
	parm.east->type = TYPE_DOUBLE;
	parm.east->required = YES;
	parm.east->description =
			_("Eastern limit of geographic region (outer edge)");
	parm.east->guisection = _("Bounds");

	parm.west = G_define_option();
	parm.west->key = "west";
	parm.west->type = TYPE_DOUBLE;
	parm.west->required = YES;
	parm.west->description =
			_("Western limit of geographic region (outer edge)");
	parm.west->guisection = _("Bounds");

	parm.bottom = G_define_option();
	parm.bottom->key = "bottom";
	parm.bottom->type = TYPE_DOUBLE;
	parm.bottom->required = YES;
	parm.bottom->description =
			_("Bottom limit of geographic region (outer edge)");
	parm.bottom->guisection = _("Bounds");

	parm.top = G_define_option();
	parm.top->key = "top";
	parm.top->type = TYPE_DOUBLE;
	parm.top->required = YES;
	parm.top->description = _("Top limit of geographic region (outer edge)");
	parm.top->guisection = _("Bounds");

	parm.rows = G_define_option();
	parm.rows->key = "rows";
	parm.rows->type = TYPE_INTEGER;
	parm.rows->required = YES;
	parm.rows->description = _("Number of rows");
	parm.rows->guisection = _("Bounds");

	parm.cols = G_define_option();
	parm.cols->key = "cols";
	parm.cols->type = TYPE_INTEGER;
	parm.cols->required = YES;
	parm.cols->description = _("Number of columns");
	parm.cols->guisection = _("Bounds");

	parm.depths = G_define_option();
	parm.depths->key = "depths";
	parm.depths->type = TYPE_INTEGER;
	parm.depths->required = YES;
	parm.depths->description = _("Number of depths");
	parm.depths->guisection = _("Bounds");

	parm.null = G_define_option();
	parm.null->key = "null";
	parm.null->type = TYPE_DOUBLE;
	parm.null->required = NO;
	parm.null->description = _("Set Value to NULL");

	flag.row = G_define_flag();
	flag.row->key = 'r';
	flag.row->description = _("Switch the row order in output from "
			"north->south to south->north");

	flag.depth = G_define_flag();
	flag.depth->key = 'd';
	flag.depth->description = _("Switch the depth order in output "
			"from bottom->top to top->bottom");

	flag.integer_in = G_define_flag();
	flag.integer_in->key = 'i';
	flag.integer_in->description =
			_("Binary data is of type integer");

	flag.sign = G_define_flag();
	flag.sign->key = 's';
	flag.sign->description = _("Signed data (two's complement)");

	if (G_parser(argc, argv))
		exit(EXIT_FAILURE);

	input = parm.input->answer;
	output = parm.output->answer;

	if (G_strcasecmp(parm.order->answer, "big") == 0)
		order = 0;
	else if (G_strcasecmp(parm.order->answer, "little") == 0)
		order = 1;
	else if (G_strcasecmp(parm.order->answer, "native") == 0)
		order = G_is_little_endian() ? 1 : 0;
	else if (G_strcasecmp(parm.order->answer, "swap") == 0)
		order = G_is_little_endian() ? 0 : 1;

	byte_swap = order == (G_is_little_endian() ? 0 : 1);

	is_signed = !!flag.sign->answer;

	is_integer = 0;
	bytes = 8;

	if (parm.bytes->answer)
		bytes = atoi(parm.bytes->answer);

	if (!flag.integer_in->answer) {
		if (bytes && bytes < 4)
			G_fatal_error(
					_("bytes=%d; must be 4 or 8 in case of floating point input"),
					bytes);
		if (!bytes)
			bytes = 4;
	} else {
		is_integer = 1;
	}

#ifndef HAVE_LONG_LONG_INT
	if (is_integer && bytes > 4)
	G_fatal_error(_("Integer input doesn't support size=8 in this build"));
#endif

	if (bytes != 1 && bytes != 2 && bytes != 4 && bytes != 8)
		G_fatal_error(_("bytes= must be 1, 2, 4 or 8"));

	region.zone = G_zone();
	region.proj = G_projection();
	region.rows = atoi(parm.rows->answer);
	region.cols = atoi(parm.cols->answer);
	region.depths = atoi(parm.depths->answer);
	region.top = atof(parm.top->answer);
	region.bottom = atof(parm.bottom->answer);

	if (!G_scan_northing(parm.north->answer, &region.north, region.proj))
		G_fatal_error(_("Illegal north coordinate <%s>"), parm.north->answer);
	if (!G_scan_northing(parm.south->answer, &region.south, region.proj))
		G_fatal_error(_("Illegal south coordinate <%s>"), parm.south->answer);
	if (!G_scan_easting(parm.east->answer, &region.east, region.proj))
		G_fatal_error(_("Illegal east coordinate <%s>"), parm.east->answer);
	if (!G_scan_easting(parm.west->answer, &region.west, region.proj))
		G_fatal_error(_("Illegal west coordinate <%s>"), parm.west->answer);

	Rast3d_adjust_region(&region);

	expected = (off_t) region.rows * region.cols * region.depths * bytes;

	fp = fopen(input, "rb");
	if (!fp)
		G_fatal_error(_("Unable to open <%s>"), input);

	/* Find File Size in Byte and Check against byte size */
	G_fseek(fp, 0, SEEK_END);
	file_size = G_ftell(fp);
	G_fseek(fp, 0, SEEK_SET);

	if (file_size != expected) {
		G_warning(_("File Size %lld ... Total Bytes %lld"),
				(long long int) file_size, (long long int) expected);
		G_fatal_error(_("Bytes do not match file size"));
	}

	map_type = (bytes > 4 ? DCELL_TYPE : FCELL_TYPE);

	if(is_integer && bytes >= 4)
		map_type = DCELL_TYPE;

	Rast3d_init_defaults();

	/*Open the new 3D raster map */
	map = Rast3d_open_new_opt_tile_size(output, RASTER3D_USE_CACHE_DEFAULT,
			&region, map_type, 32);

	if (map == NULL)
		G_fatal_error(_("Unable to open 3D raster map"));

	in_cell = G_malloc(bytes);

	bin_to_raster3d(parm.null->answer, map_type, is_integer, is_signed, bytes,
			byte_swap, flag.row->answer, flag.depth->answer);

	if (!Rast3d_close(map))
		G_fatal_error(_("Unable to close 3D raster map"));

	/* write input name to map history */
	Rast3d_read_history(output, G_mapset(), &history);
	Rast_set_history(&history, HIST_DATSRC_1, input);
	Rast3d_write_history(output, &history);

	fclose(fp);
	if (in_cell)
		G_free(in_cell);

	return EXIT_SUCCESS;
}
Example #11
0
int OUTGR()
{
    void *cf1, *cf2, *cf3, *cf4, *cf5, *cf6, *cf7;
    int read_val;
    FCELL *cell;
    float *data;
    int i, iarc, cnt;
    int bmask = 1;
    int x, y;
    float value;

    if ((cellinp != NULL) && (cellout != NULL)) {
	cell = Rast_allocate_f_buf();

	for (i = 0; i < nsizr; i++) {
	    /* seek to the right row */
	    G_fseek
		(Tmp_fd_cell, ((off_t)(nsizr - 1 - i) * nsizc * sizeof(FCELL)),
		 0);
	    fread(cell, sizeof(FCELL), nsizc, Tmp_fd_cell);
	    Rast_put_f_row(fdcout, cell);
	}
    }

  /*** Initialize output g3d region ***/
    current_region.bottom = z_orig_in;
    current_region.top = nsizl * tb_res_in + z_orig_in;

    if (!(data = (float *)G_malloc(sizeof(float) * nsizr * nsizc * nsizl))) {
	clean();
	G_fatal_error(_("Out of memory"));
    }

  /*** Write elevation results ***/
    if (outz != NULL) {

	cf1 = Rast3d_open_new_opt_tile_size(outz, RASTER3D_USE_CACHE_DEFAULT, &current_region, FCELL_TYPE, 32); 
	if (cf1 == NULL) {
	    clean();
	    G_fatal_error(_("Unable to open %s for writing"), outz);
	}

	/* seek to the beginning */
	G_fseek(Tmp_fd_z, 0L, 0);

	/* Read data in from temp file */
	read_val =
	    fread(data, sizeof(float), nsizr * nsizc * nsizl, Tmp_fd_z);
	if (read_val < 0) {
	    clean();
	    G_fatal_error(_("Unable to read data from temp file"));
	}

	cnt = 0;
	for (iarc = 0; iarc < nsizl; iarc++) {

	    for (y = nsizr - 1; y >= 0; y--) {	/* changed by AV */
		for (x = 0; x < nsizc; x++) {
		    if (maskmap != NULL)
			bmask = BM_get(bitmask, x, nsizr - y - 1);
		    else
			bmask = 1;
		    value = data[cnt];
		    if (!bmask)
			Rast3d_set_null_value(&value, 1, FCELL_TYPE);
		    if (Rast3d_put_float(cf1, x, y, iarc, value) == 0) {
			clean();
			G_fatal_error(
				_("Error writing cell (%d,%d,%d) with value %f"),
				x, y, iarc, value);
		    }

		    cnt++;

		}
	    }
	}

	/* Close the file */
	if (Rast3d_close(cf1) == 0) {
	    clean();
	    G_fatal_error(_("Error closing output file %s"), outz);
	} else
            G_message(_("3D raster map <%s> created"), outz);
    }

  /*** Write out the gradient results ***/
    if (gradient != NULL) {

	cf2 = Rast3d_open_new_opt_tile_size(gradient, RASTER3D_USE_CACHE_DEFAULT, &current_region, FCELL_TYPE, 32); 
	if (cf2 == NULL) {
	    clean();
	    G_fatal_error(_("Unable to open %s for writing"), gradient);
	}

	/* seek to the beginning */
	G_fseek(Tmp_fd_dx, 0L, 0);

	/* Read data in from temp file */
	read_val =
	    fread(data, sizeof(float), nsizr * nsizc * nsizl, Tmp_fd_dx);
	if (read_val < 0) {
	    clean();
	    G_fatal_error(_("Unable to read data from temp file"));
	}

	cnt = 0;
	for (iarc = 0; iarc < nsizl; iarc++) {

	    for (y = nsizr - 1; y >= 0; y--) {	/* changed by AV */
		for (x = 0; x < nsizc; x++) {
		    if (maskmap != NULL)
			bmask = BM_get(bitmask, x, nsizr - y - 1);
		    else
			bmask = 1;
		    value = data[cnt];
		    if (!bmask)
			Rast3d_set_null_value(&value, 1, FCELL_TYPE);
		    if (Rast3d_put_float(cf2, x, y, iarc, value) == 0) {
			clean();
			G_fatal_error(
				_("Error writing cell (%d,%d,%d) with value %f"),
				x, y, iarc, value);
		    }

		    cnt++;

		}
	    }
	}

	/* Close the file */
	if (Rast3d_close(cf2) == 0) {
	    clean();
	    G_fatal_error(_("Error closing output file %s"), gradient);
	} else
            G_message(_("3D raster map <%s> created"), gradient);
    }

  /*** Write out aspect1 results ***/
    if (aspect1 != NULL) {

	cf3 = Rast3d_open_new_opt_tile_size(aspect1, RASTER3D_USE_CACHE_DEFAULT, &current_region, FCELL_TYPE, 32); 
	if (cf3 == NULL) {
	    clean();
	    G_fatal_error(_("Unable to open %s for writing"), aspect1);
	}

	/* seek to the beginning */
	G_fseek(Tmp_fd_dy, 0L, 0);

	/* Read data in from temp file */
	read_val =
	    fread(data, sizeof(float), nsizr * nsizc * nsizl, Tmp_fd_dy);
	if (read_val < 0) {
	    clean();
	    G_fatal_error(_("Unable to read data from temp file"));
	}

	cnt = 0;
	for (iarc = 0; iarc < nsizl; iarc++) {

	    for (y = nsizr - 1; y >= 0; y--) {	/* changed by AV */
		for (x = 0; x < nsizc; x++) {
		    if (maskmap != NULL)
			bmask = BM_get(bitmask, x, nsizr - y - 1);
		    else
			bmask = 1;
		    value = data[cnt] * 180 / M_PI;
		    if (!bmask)
			Rast3d_set_null_value(&value, 1, FCELL_TYPE);
		    if (Rast3d_put_float(cf3, x, y, iarc, value) == 0) {
			clean();
			G_fatal_error(
				_("Error writing cell (%d,%d,%d) with value %f"),
				x, y, iarc, value);
		    }

		    cnt++;

		}
	    }
	}

	/* Close the file */
	if (Rast3d_close(cf3) == 0) {
	    clean();
	    G_fatal_error(_("Error closing output file %s"), aspect1);
	} else
            G_message(_("3D raster map <%s> created"), aspect1);
    }

  /*** Write out aspect2 results ***/
    if (aspect2 != NULL) {

	cf4 = Rast3d_open_new_opt_tile_size(aspect2, RASTER3D_USE_CACHE_DEFAULT, &current_region, FCELL_TYPE, 32); 
	if (cf4 == NULL) {
	    clean();
	    G_fatal_error(_("Unable to open %s for writing"), aspect2);
	}

	/* seek to the beginning */
	G_fseek(Tmp_fd_dz, 0L, 0);

	/* Read data in from temp file */
	read_val =
	    fread(data, sizeof(float), nsizr * nsizc * nsizl, Tmp_fd_dz);
	if (read_val < 0) {
	    clean();
	    G_fatal_error(_("Unable to read data from temp file"));
	}

	cnt = 0;
	for (iarc = 0; iarc < nsizl; iarc++) {

	    for (y = nsizr - 1; y >= 0; y--) {	/* changed by AV */
		for (x = 0; x < nsizc; x++) {
		    if (maskmap != NULL)
			bmask = BM_get(bitmask, x, nsizr - y - 1);
		    else
			bmask = 1;
		    value = data[cnt] * 180 / M_PI;
		    if (!bmask)
			Rast3d_set_null_value(&value, 1, FCELL_TYPE);
		    if (Rast3d_put_float(cf4, x, y, iarc, value) == 0) {
			clean();
			G_fatal_error(
				_("Error writing cell (%d,%d,%d) with value %f"),
				x, y, iarc, value);
		    }

		    cnt++;

		}
	    }
	}

	/* Close the file */
	if (Rast3d_close(cf4) == 0) {
	    clean();
	    G_fatal_error(_("Error closing output file %s"), aspect2);
	} else
            G_message(_("3D raster map <%s> created"), aspect2);
    }

  /*** Write out ncurv results ***/
    if (ncurv != NULL) {

	cf5 = Rast3d_open_new_opt_tile_size(ncurv, RASTER3D_USE_CACHE_DEFAULT, &current_region, FCELL_TYPE, 32); 
	if (cf5 == NULL) {
	    clean();
	    G_fatal_error(_("Unable to open %s for writing"), ncurv);
	}

	/* seek to the beginning */
	G_fseek(Tmp_fd_xx, 0L, 0);

	/* Read data in from temp file */
	read_val =
	    fread(data, sizeof(float), nsizr * nsizc * nsizl, Tmp_fd_xx);
	if (read_val < 0) {
	    clean();
	    G_fatal_error(_("Unable to read data from temp file"));
	}

	cnt = 0;
	for (iarc = 0; iarc < nsizl; iarc++) {

	    for (y = nsizr - 1; y >= 0; y--) {	/* changed by AV */
		for (x = 0; x < nsizc; x++) {
		    if (maskmap != NULL)
			bmask = BM_get(bitmask, x, nsizr - y - 1);
		    else
			bmask = 1;
		    value = data[cnt];
		    if (!bmask)
			Rast3d_set_null_value(&value, 1, FCELL_TYPE);
		    if (Rast3d_put_float(cf5, x, y, iarc, value) == 0) {
			clean();
			G_fatal_error(
				_("Error writing cell (%d,%d,%d) with value %f"),
				x, y, iarc, value);
		    }

		    cnt++;

		}
	    }
	}

	/* Close the file */
	if (Rast3d_close(cf5) == 0) {
	    clean();
	    G_fatal_error(_("Error closing output file %s"), ncurv);
	} else
            G_message(_("3D raster map <%s> created"), ncurv);
    }

  /*** Write out gcurv results ***/
    if (gcurv != NULL) {

	cf6 = Rast3d_open_new_opt_tile_size(gcurv, RASTER3D_USE_CACHE_DEFAULT, &current_region, FCELL_TYPE, 32); 
	if (cf6 == NULL) {
	    clean();
	    G_fatal_error(_("Unable to open %s for writing"), gcurv);
	}

	/* seek to the beginning */
	G_fseek(Tmp_fd_yy, 0L, 0);

	/* Read data in from temp file */
	read_val =
	    fread(data, sizeof(float), nsizr * nsizc * nsizl, Tmp_fd_yy);
	if (read_val < 0) {
	    clean();
	    G_fatal_error(_("Unable to read data from temp file"));
	}

	cnt = 0;
	for (iarc = 0; iarc < nsizl; iarc++) {

	    for (y = nsizr - 1; y >= 0; y--) {	/* changed by AV */
		for (x = 0; x < nsizc; x++) {
		    if (maskmap != NULL)
			bmask = BM_get(bitmask, x, nsizr - y - 1);
		    else
			bmask = 1;
		    value = data[cnt];
		    if (!bmask)
			Rast3d_set_null_value(&value, 1, FCELL_TYPE);
		    if (Rast3d_put_float(cf6, x, y, iarc, value) == 0) {
			clean();
			G_fatal_error(
				_("Error writing cell (%d,%d,%d) with value %f"),
				x, y, iarc, value);
		    }

		    cnt++;

		}
	    }
	}

	/* Close the file */
	if (Rast3d_close(cf6) == 0) {
	    clean();
	    G_fatal_error(_("Error closing output file %s"), gcurv);
	} else
            G_message(_("3D raster map <%s> created"), gcurv);
    }

  /*** Write mcurv results ***/
    if (mcurv != NULL) {

	cf7 = Rast3d_open_new_opt_tile_size(mcurv, RASTER3D_USE_CACHE_DEFAULT, &current_region, FCELL_TYPE, 32); 
	if (cf7 == NULL) {
	    clean();
	    G_fatal_error(_("Unable to open %s for writing"), mcurv);
	}

	/* seek to the beginning */
	G_fseek(Tmp_fd_xy, 0L, 0);

	/* Read data in from temp file */
	read_val =
	    fread(data, sizeof(float), nsizr * nsizc * nsizl, Tmp_fd_xy);
	if (read_val < 0) {
	    clean();
	    G_fatal_error(_("Unable to read data from temp file"));
	}

	cnt = 0;
	for (iarc = 0; iarc < nsizl; iarc++) {

	    for (y = nsizr - 1; y >= 0; y--) {	/* changed by AV */
		for (x = 0; x < nsizc; x++) {
		    if (maskmap != NULL)
			bmask = BM_get(bitmask, x, nsizr - y - 1);
		    else
			bmask = 1;
		    value = data[cnt];
		    if (!bmask)
			Rast3d_set_null_value(&value, 1, FCELL_TYPE);
		    if (Rast3d_put_float(cf7, x, y, iarc, value) == 0) {
			clean();
			G_fatal_error(
				_("Error writing cell (%d,%d,%d) with value %f"),
				x, y, iarc, value);
		    }

		    cnt++;

		}
	    }
	}

	/* Close the file */
	if (Rast3d_close(cf7) == 0) {
	    clean();
	    G_fatal_error(_("Error closing output file %s"), mcurv);
	} else
            G_message(_("3D raster map <%s> created"), mcurv);
    }

    G_free(data);

    return 1;
}
Example #12
0
int main(int argc, char *argv[])
{
    char *input;
    char *output;
    char *title;
    char *temp;
    FILE *fd, *ft;
    int cf, direction, sz;
    struct Cell_head cellhd;
    struct History history;
    void *rast, *rast_ptr;
    int row, col;
    int nrows, ncols;
    double x;
    char y[128];
    struct GModule *module;
    struct
    {
	struct Option *input, *output, *title, *mult, *nv, *type;
    } parm;
    struct
    {
	struct Flag *s;
    } flag;
    char *null_val_str;
    DCELL mult;
    RASTER_MAP_TYPE data_type;
    double atof();

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("import"));
    G_add_keyword(_("conversion"));
    G_add_keyword("ASCII");
    module->description =
	_("Converts a GRASS ASCII raster file to binary raster map.");

    parm.input = G_define_standard_option(G_OPT_F_INPUT);
    parm.input->label =
	_("Name of input file to be imported");
    parm.input->description = _("'-' for standard input");

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

    parm.type = G_define_option();
    parm.type->key = "type";
    parm.type->type = TYPE_STRING;
    parm.type->required = NO;
    parm.type->options = "CELL,FCELL,DCELL";
    parm.type->label = _("Storage type for resultant raster map");
    parm.type->description = _("Default: CELL for integer values, DCELL for floating-point values");
    
    parm.title = G_define_option();
    parm.title->key = "title";
    parm.title->key_desc = "phrase";
    parm.title->type = TYPE_STRING;
    parm.title->required = NO;
    parm.title->description = _("Title for resultant raster map");

    parm.mult = G_define_option();
    parm.mult->key = "multiplier";
    parm.mult->type = TYPE_DOUBLE;
    parm.mult->description = _("Default: read from header");
    parm.mult->required = NO;
    parm.mult->label = _("Multiplier for ASCII data");

    parm.nv = G_define_standard_option(G_OPT_M_NULL_VALUE);
    parm.nv->description = _("Default: read from header");
    parm.nv->label = _("String representing NULL value data cell");
    parm.nv->guisection = _("NULL data");
    
    flag.s = G_define_flag();
    flag.s->key = 's';
    flag.s->description =
	_("SURFER (Golden Software) ASCII file will be imported");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    input = parm.input->answer;
    output = parm.output->answer;

    temp = G_tempfile();
    ft = fopen(temp, "w+");
    if (ft == NULL)
	G_fatal_error(_("Unable to open temporary file <%s>"), temp);

    if ((title = parm.title->answer))
	G_strip(title);
    
    if (!parm.mult->answer)
	Rast_set_d_null_value(&mult, 1);
    else if ((sscanf(parm.mult->answer, "%lf", &mult)) != 1)
	G_fatal_error(_("Wrong entry for multiplier: %s"), parm.mult->answer);
    
    null_val_str = parm.nv->answer;

    data_type = -1;
    if (parm.type->answer) {
	switch(parm.type->answer[0]) {
	case 'C':
	    data_type = CELL_TYPE;
	    break;
	case 'F':
	    data_type = FCELL_TYPE;
	    break;
	case 'D':
	    data_type = DCELL_TYPE;
	    break;
	}
    }
    
    if (strcmp(input, "-") == 0) {
	Tmp_file = G_tempfile();
	if (NULL == (Tmp_fd = fopen(Tmp_file, "w+")))
	    G_fatal_error(_("Unable to open temporary file <%s>"), Tmp_file);
	unlink(Tmp_file);
	if (0 > file_cpy(stdin, Tmp_fd))
	    G_fatal_error(_("Unable to read input from stdin"));
	fd = Tmp_fd;
    }
    else
	fd = fopen(input, "r");

    if (fd == NULL) {
	G_fatal_error(_("Unable to read input from <%s>"), input);
    }

    direction = 1;
    sz = 0;
    if (flag.s->answer) {
	sz = getgrdhead(fd, &cellhd);
	/* for Surfer files, the data type is always FCELL_TYPE,
	   the multiplier and the null_val_str are never used */
	data_type = FCELL_TYPE;
	mult = 1.;
	null_val_str = "";
	/* rows in surfer files are ordered from bottom to top,
	   opposite of normal GRASS ordering */
	direction = -1;
    }
    else
	sz = gethead(fd, &cellhd, &data_type, &mult, &null_val_str);

    if (!sz)
	G_fatal_error(_("Can't get cell header"));

    nrows = cellhd.rows;
    ncols = cellhd.cols;
    Rast_set_window(&cellhd);

    if (nrows != Rast_window_rows())
	G_fatal_error(_("OOPS: rows changed from %d to %d"), nrows,
		      Rast_window_rows());
    if (ncols != Rast_window_cols())
	G_fatal_error(_("OOPS: cols changed from %d to %d"), ncols,
		      Rast_window_cols());


    rast_ptr = Rast_allocate_buf(data_type);
    rast = rast_ptr;
    cf = Rast_open_new(output, data_type);
    for (row = 0; row < nrows; row++) {
	G_percent(row, nrows, 2);
	for (col = 0; col < ncols; col++) {
	    if (fscanf(fd, "%s", y) != 1) {
		Rast_unopen(cf);
		G_fatal_error(_("Data conversion failed at row %d, col %d"),
			      row + 1, col + 1);
	    }
	    if (strcmp(y, null_val_str)) {
		x = atof(y);
		if ((float)x == GS_BLANK) {
		    Rast_set_null_value(rast_ptr, 1, data_type);
		}
		else {
		    Rast_set_d_value(rast_ptr,
					 (DCELL) (x * mult), data_type);
		}
	    }
	    else {
		Rast_set_null_value(rast_ptr, 1, data_type);
	    }
	    rast_ptr = G_incr_void_ptr(rast_ptr, Rast_cell_size(data_type));
	}
	fwrite(rast, Rast_cell_size(data_type), ncols, ft);
	rast_ptr = rast;
    }
    G_percent(nrows, nrows, 2);
    G_debug(1, "Creating support files for %s", output);

    sz = 0;
    if (direction < 0) {
	sz = -ncols * Rast_cell_size(data_type);
	G_fseek(ft, sz, SEEK_END);
	sz *= 2;
    }
    else {
	G_fseek(ft, 0L, SEEK_SET);
    }

    for (row = 0; row < nrows; row += 1) {
	fread(rast, Rast_cell_size(data_type), ncols, ft);
	Rast_put_row(cf, rast, data_type);
	G_fseek(ft, sz, SEEK_CUR);
    }
    fclose(ft);
    unlink(temp);

    Rast_close(cf);

    if (title)
	Rast_put_cell_title(output, title);

    Rast_short_history(output, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(output, &history);

    G_done_msg(" ");

    exit(EXIT_SUCCESS);
}
Example #13
0
/*!
  \brief Open feature index file
  
  \param[in,out] Map pointer to Map_info struct
  \param[out] offset pointer to Format_info_offset (OGR or PG)
  
  \return 0 on success
  \return -1 on error
*/
int Vect_open_fidx(struct Map_info *Map, struct Format_info_offset *offset)
{
    char elem[GPATH_MAX];
    char buf[5];		/* used for format version */
    long length;
    int Version_Major, Version_Minor, Back_Major, Back_Minor, byte_order;
    
    struct gvfile fp;
    struct Port_info port;
    
    G_debug(1, "Vect_open_fidx(): name = %s mapset = %s format = %d",
	    Map->name, Map->mapset, Map->format);
    
    sprintf(elem, "%s/%s", GV_DIRECTORY, Map->name);
    dig_file_init(&fp);
    fp.file = G_fopen_old(elem, GV_FIDX_ELEMENT, Map->mapset);
    if (fp.file == NULL) {
        G_debug(1, "unable to open fidx file for vector map <%s>",
                Vect_get_full_name(Map));
	return -1;
    }

    /* Header */
    if (0 >= dig__fread_port_C(buf, 5, &fp))
	return -1;
    Version_Major = buf[0];
    Version_Minor = buf[1];
    Back_Major    = buf[2];
    Back_Minor    = buf[3];
    byte_order    = buf[4];
    
    /* check version numbers */
    if (Version_Major > 5 || Version_Minor > 0) {
	if (Back_Major > 5 || Back_Minor > 0) {
	    G_fatal_error(_("Feature index format version %d.%d is not supported by this release."
			   " Try to rebuild topology or upgrade GRASS."),
			  Version_Major, Version_Minor);
	    return -1;
	}
	G_warning(_("Your GRASS version does not fully support feature index format %d.%d of the vector."
		   " Consider to rebuild topology or upgrade GRASS."),
		  Version_Major, Version_Minor);
    }

    dig_init_portable(&port, byte_order);
    dig_set_cur_port(&port);

    /* Body */
    /* bytes 6 - 9 : header size */
    if (0 >= dig__fread_port_L(&length, 1, &fp))
	return -1;
    G_debug(4, "  header size %ld", length);

    G_fseek(fp.file, length, SEEK_SET);

    /* number of records  */
    if (0 >= dig__fread_port_I(&(offset->array_num), 1, &fp))
	return -1;
    
    /* alloc space */
    offset->array = (int *) G_malloc(offset->array_num * sizeof(int));
    offset->array_alloc = offset->array_num;
    
    /* offsets */
    if (0 >= dig__fread_port_I(offset->array,
			       offset->array_num, &fp))
	return -1;

    fclose(fp.file);

    G_debug(3, "%d records read from fidx", offset->array_num);

    return 0;
}
Example #14
0
int
ask_gis_files(char *type, char *file, char *xname, char *xmapset,
	      int position)
{
    static int use = 1;
    static Objects objects[] = {
	OTHER(pick, &use),
	{0}
    };

    char msg[100];
    FILE *fd;
    int width;
    int len1, len2, len;
    long offset;
    long *page_offset;
    int col, nlist;
    int line;
    int stat;
    char buf[100];
    int top, bottom, left, right, center;
    int topx, bottomx, leftx, rightx, widthx;
    char name[GNAME_MAX], mapset[GMAPSET_MAX], cur_mapset[GMAPSET_MAX];
    int new_mapset;

    Menu_msg("");

    fd = fopen(file, "r");
    if (fd == NULL)
	G_fatal_error("ask_gis_files: can't read tempfile");
    if (fread(&len1, sizeof(len1), 1, fd) != 1
	|| fread(&len2, sizeof(len2), 1, fd) != 1 || len1 <= 0 || len2 <= 0) {
	fclose(fd);
	return 0;
    }

    sprintf(msg, "Double click on %s file to be plotted", type);

    /*
     * build a popup window at center of the screen.
     * 35% the height and wide enough to hold 2 columms of file names
     *
     * the window is for choosing file names and will be laid out in 2 columns
     *
     *             ------------------------------------------
     *             |     CANCEL           | (MORE) | (LESS) | 
     *             ------------------------------------------
     *             |             mapset                     |
     *             ------------------------------------------
     *             |      name1        |   name2            |
     *             ------------------------------------------
     *             |      name3        |   name4            |
     *             ------------------------------------------
     *             |      name5        |   name6            |
     *             |                   .                    |
     *             |                   .                    |
     *             |                   .                    |
     *             ------------------------------------------
     */

    /* height of 1 line, based on NLINES taking up 35% vertical space */
    height = (.35 * (SCREEN_BOTTOM - SCREEN_TOP)) / NLINES + 1;

    /* size of text, 80% of line height */
    text_size = .8 * height;
    size = text_size - 1;	/* fudge for computing pixels width of text */

    /* indent for the text */
    edge = .1 * height + 1;

    /* this is a fudge to determine the length of the largest text */
    len1 = 2 * len1;		/* name in 2 columns */
    len2 += strlen("mapset ");
    len = (len1 > len2 ? len1 : len2);

    /* width is for max chars plus sidecar for more/less */
    width = len * size + height;
    widthx = strlen(msg) * size;
    if (widthx < width)
	widthx = width;

    /* define the window */
    top = (SCREEN_TOP + SCREEN_BOTTOM - height * NLINES) / 2;
    bottom = top + height * NLINES;

    center = (SCREEN_LEFT + SCREEN_RIGHT) / 2;
    if (position > 0) {
	right = (center + SCREEN_RIGHT + width) / 2;
	if (right >= SCREEN_RIGHT)
	    right = SCREEN_RIGHT - 1;
	left = right - width;
    }
    else if (position < 0) {
	left = (center + SCREEN_LEFT - width) / 2;
	if (left <= SCREEN_LEFT)
	    left = SCREEN_LEFT + 1;
	right = left + width;
    }
    else {
	left = center + width / 2;
	right = left + width;
    }

    topx = top - 3 * height;
    bottomx = topx + 2 * height;
    leftx = (left + right - widthx) / 2;
    if (leftx < SCREEN_LEFT)
	leftx = SCREEN_LEFT;
    rightx = leftx + widthx;

    /* save what is under these areas, so they can be restored */
    R_panel_save(tempfile1, top, bottom + 1, left, right + 1);
    R_panel_save(tempfile2, topx, bottomx + 1, leftx, rightx + 1);

    /* fill it top with GREY, pick area with white */
    R_standard_color(WHITE);
    R_box_abs(left, top, right, bottom);
    R_standard_color(GREY);
    R_box_abs(leftx, topx, rightx, bottomx);

    R_standard_color(BLACK);
    Outline_box(top, bottom, left, right);
    right -= height;		/* reduce it to exclude sidecar */
    Outline_box(top, bottom, left, right);

    /* print messages above the files */
    dotext(msg, topx, topx + height, leftx, rightx, 1);
    dotext("Double click here to cancel", topx + height, bottomx, leftx,
	   rightx, 1);
    cancel.top = topx;
    cancel.bottom = bottomx;
    cancel.left = leftx;
    cancel.right = rightx;

    /* start the mouse in the cancel box */
    Set_mouse_xy((leftx + rightx) / 2, (topx + bottomx) / 2);

    dobox(&less, "", WHITE, top, right, right + height, 0);
    dobox(&more, "", WHITE, bottom - height, right, right + height, 0);

    /* as we read the file of names, keep track of pages so we can
     * page backward
     */
    page = 0;
    page_offset = (long *)G_calloc(npages = 1, sizeof(long));
    *page_offset = G_ftell(fd);

    nlist = sizeof(list) / sizeof(list[0]);
    for (stat = -1; stat < 0;) {
	line = 0;
	count = 0;
	*cur_mapset = 0;
	col = 0;
	while (1) {
	    offset = G_ftell(fd);
	    if (fgets(buf, sizeof buf, fd) == NULL
		|| sscanf(buf, "%s %s", name, mapset) != 2)
		break;
	    if (new_mapset = (strcmp(cur_mapset, mapset) != 0)) {
		if (line)
		    line++;
		if (col)
		    line++;
		col = 0;
	    }
	    if (count >= nlist || line + new_mapset >= NLINES) {
		if (page + 1 == npages) {
		    npages++;
		    page_offset =
			(long *)G_realloc(page_offset, npages * sizeof(long));
		    page_offset[npages - 1] = offset;
		}
		break;
	    }
	    if (new_mapset) {
		struct box dummy;
		char label[GMAPSET_MAX + 7];

		strcpy(cur_mapset, mapset);
		sprintf(label, "Mapset %s", mapset);
		dobox(&dummy, label, WHITE, top + line * height, left, right,
		      0);
		line++;
	    }
	    if (col) {
		dobox(&list[count].box, name, GREY, top + line * height,
		      left + width / 2, right, 0);
		line++;
		col = 0;
	    }
	    else {
		dobox(&list[count].box, name, GREY, top + line * height, left,
		      left + width / 2, 0);
		col = 1;
	    }
	    strcpy(list[count].name, name);
	    strcpy(list[count].mapset, mapset);
	    count++;
	}
	downarrow(&more, page + 1 < npages ? BLACK : WHITE);
	uparrow(&less, page > 0 ? BLACK : WHITE);
	which = -1;
	switch (Input_pointer(objects)) {
	case -1:		/* more or less */
	    break;
	case -2:		/* cancel */
	    stat = 0;
	    continue;
	default:		/* file picked */
	    strcpy(xname, list[which].name);
	    strcpy(xmapset, list[which].mapset);
	    stat = 1;
	    continue;
	}
	G_fseek(fd, page_offset[page], 0);
	R_standard_color(WHITE);
	R_box_abs(left + 1, top + 1, right - 1, bottom - 1);
    }

    /* all done. restore what was under the window */
    right += height;		/* move it back over the sidecar */
    R_standard_color(WHITE);
    R_box_abs(left, top, right, bottom);
    R_panel_restore(tempfile1);
    R_panel_restore(tempfile2);
    R_panel_delete(tempfile1);
    R_panel_delete(tempfile2);
    R_flush();

    G_free(page_offset);
    return stat;
}