Esempio n. 1
0
int draw_outline(void)
{
    int raster_size;

    row = col = top = 0;	/* get started for read of first */
    bottom = 1;			/*   line from raster map */
    scan_length = read_next();
    k = 0;
    raster_size = Rast_cell_size(map_type);
    while (read_next()) {	/* read rest of file, one row at *//*   a time */
	n1 = Rast_row_to_northing((double)row - 1., &(PS.w));
	n2 = Rast_row_to_northing((double)row, &(PS.w));
	n3 = Rast_row_to_northing((double)row + 1., &(PS.w));

	for (col = 0; col < scan_length - 1; col++) {
	    e1 = Rast_col_to_easting((double)col - 1., &(PS.w));
	    e2 = Rast_col_to_easting((double)col, &(PS.w));
	    e3 = Rast_col_to_easting((double)col + 1., &(PS.w));
	    tl = G_incr_void_ptr(buffer[top], col * raster_size);
	    /* top left in window */
	    tr = G_incr_void_ptr(buffer[top], (col + 1) * raster_size);
	    /* top right in window */
	    bl = G_incr_void_ptr(buffer[bottom], col * raster_size);
	    /* bottom left in window */
	    br = G_incr_void_ptr(buffer[bottom], (col + 1) * raster_size);
	    /* bottom right in window */
	    draw_boundaries();
	    if (k == 3)
		k = 0;
	}
	row++;
    }

    return 0;
}				/* draw_outlines */
Esempio n. 2
0
static int
Rast3d_tile2xdrTile(RASTER3D_Map * map, const void *tile, int rows, int cols,
		 int depths, int xRedundant, int yRedundant, int zRedundant,
		 int nofNum, int type)
{
    int y, z;

    if (!Rast3d_init_copy_to_xdr(map, type)) {
	Rast3d_error("Rast3d_tile2xdrTile: error in Rast3d_init_copy_to_xdr");
	return 0;
    }


    if (nofNum == map->tileSize) {
	if (!Rast3d_copy_to_xdr(tile, map->tileSize)) {
	    Rast3d_error("Rast3d_tile2xdrTile: error in Rast3d_copy_to_xdr");
	    return 0;
	}
	return 1;
    }

    if (xRedundant) {
	for (z = 0; z < depths; z++) {
	    for (y = 0; y < rows; y++) {
		if (!Rast3d_copy_to_xdr(tile, cols)) {
		    Rast3d_error("Rast3d_tile2xdrTile: error in Rast3d_copy_to_xdr");
		    return 0;
		}
		tile = G_incr_void_ptr(tile, map->tileX * Rast3d_length(type));
	    }
	    if (yRedundant)
		tile =
		    G_incr_void_ptr(tile,
				    map->tileX * yRedundant *
				    Rast3d_length(type));
	}
	return 1;
    }

    if (yRedundant) {
	for (z = 0; z < depths; z++) {
	    if (!Rast3d_copy_to_xdr(tile, map->tileX * rows)) {
		Rast3d_error("Rast3d_tile2xdrTile: error in Rast3d_copy_to_xdr");
		return 0;
	    }
	    tile = G_incr_void_ptr(tile, map->tileXY * Rast3d_length(type));
	}
	return 1;
    }

    if (!Rast3d_copy_to_xdr(tile, map->tileXY * depths)) {
	Rast3d_error("Rast3d_tile2xdrTile: error in Rast3d_copy_to_xdr");
	return 0;
    }
    return 1;
}
Esempio n. 3
0
static void put_data_gdal(int fd, const void *rast, int row, int n,
			  int zeros_r_nulls, RASTER_MAP_TYPE map_type)
{
#ifdef HAVE_GDAL
    struct fileinfo *fcb = &R__.fileinfo[fd];
    int size = Rast_cell_size(map_type);
    DCELL null_val = fcb->gdal->null_val;
    const void *src;
    void *work_buf, *dst;
    GDALDataType datatype;
    CPLErr err;
    int i;

    if (row < 0 || row >= fcb->cellhd.rows)
	return;

    if (n <= 0)
	return;

    work_buf = G__alloca(n * size);

    switch (map_type) {
    case CELL_TYPE:
	datatype = GDT_Int32;
	break;
    case FCELL_TYPE:
	datatype = GDT_Float32;
	break;
    case DCELL_TYPE:
	datatype = GDT_Float64;
	break;
    }

    src = rast;
    dst = work_buf;

    for (i = 0; i < n; i++) {
	if (Rast_is_null_value(src, map_type) ||
	    (zeros_r_nulls && !*(CELL *) src))
	    Rast_set_d_value(dst, null_val, map_type);
	else
	    memcpy(dst, src, size);
	src = G_incr_void_ptr(src, size);
	dst = G_incr_void_ptr(dst, size);
    }

    err = Rast_gdal_raster_IO(fcb->gdal->band, GF_Write, 0, row, n, 1,
			      work_buf, n, 1, datatype, 0, 0);

    G__freea(work_buf);

    if (err != CE_None)
	G_fatal_error(_("Error writing data via GDAL for row %d of <%s>"),
		      row, fcb->name);
#endif
}
Esempio n. 4
0
/*!
  \brief Draw raster row in RGB mode

  \param A_row row number
  \param r_raster red data buffer
  \param g_raster green data buffer
  \param b_raster blue data buffer
  \param r_colors colors used for red channel
  \param g_colors colors used for green channel
  \param b_colors colors used for blue channel
  \param r_type raster type used for red channel
  \param g_type raster type used for red channel
  \param b_type raster type used for red channel

  \return
*/
int D_draw_raster_RGB(int A_row,
		      const void *r_raster, const void *g_raster,
		      const void *b_raster, struct Colors *r_colors,
		      struct Colors *g_colors, struct Colors *b_colors,
		      RASTER_MAP_TYPE r_type, RASTER_MAP_TYPE g_type,
		      RASTER_MAP_TYPE b_type)
{
    static unsigned char *r_buf, *g_buf, *b_buf, *n_buf;
    static int nalloc;

    int r_size = Rast_cell_size(r_type);
    int g_size = Rast_cell_size(g_type);
    int b_size = Rast_cell_size(b_type);
    int ncols = src[0][1] - src[0][0];
    int i;

    /* reallocate color_buf if necessary */
    if (nalloc < ncols) {
	nalloc = ncols;
	r_buf = G_realloc(r_buf, nalloc);
	g_buf = G_realloc(g_buf, nalloc);
	b_buf = G_realloc(b_buf, nalloc);
	n_buf = G_realloc(n_buf, nalloc);
    }

    /* convert cell values to bytes */
    Rast_lookup_colors(r_raster, r_buf, n_buf, n_buf, n_buf, ncols,
			   r_colors, r_type);
    Rast_lookup_colors(g_raster, n_buf, g_buf, n_buf, n_buf, ncols,
			   g_colors, g_type);
    Rast_lookup_colors(b_raster, n_buf, n_buf, b_buf, n_buf, ncols,
			   b_colors, b_type);

    if (D__overlay_mode)
	for (i = 0; i < ncols; i++) {
	    n_buf[i] = (Rast_is_null_value(r_raster, r_type) ||
			Rast_is_null_value(g_raster, g_type) ||
			Rast_is_null_value(b_raster, b_type));

	    r_raster = G_incr_void_ptr(r_raster, r_size);
	    g_raster = G_incr_void_ptr(g_raster, g_size);
	    b_raster = G_incr_void_ptr(b_raster, b_size);
	}

    A_row = COM_raster(ncols, A_row, r_buf, g_buf, b_buf,
		       D__overlay_mode ? n_buf : NULL);

    return (A_row < src[1][1])
	? A_row : -1;
}
Esempio n. 5
0
static int calc_mu(int *fds, double *mu, int bands)
{
    int i;
    int rows = Rast_window_rows();
    int cols = Rast_window_cols();
    void *rowbuf = NULL;

    for (i = 0; i < bands; i++) {
	RASTER_MAP_TYPE maptype;
	int row, col;
	double sum = 0.;

	maptype = Rast_get_map_type(fds[i]);

	/* don't assume each image is of the same type */
	if (rowbuf)
	    G_free(rowbuf);
	if ((rowbuf = Rast_allocate_buf(maptype)) == NULL)
	    G_fatal_error(_("Unable allocate memory for row buffer"));

	G_message(_("Computing means for band %d..."), i + 1);
	for (row = 0; row < rows; row++) {
	    void *ptr = rowbuf;

	    G_percent(row, rows - 1, 2);

	    Rast_get_row(fds[i], rowbuf, row, maptype);

	    for (col = 0; col < cols; col++) {
		/* skip null cells */
		if (Rast_is_null_value(ptr, maptype)) {
		    ptr = G_incr_void_ptr(ptr, Rast_cell_size(maptype));
		    continue;
		}

		sum += Rast_get_d_value(ptr, maptype);
		ptr = G_incr_void_ptr(ptr, Rast_cell_size(maptype));
	    }
	}

	mu[i] = sum / (double)(rows * cols);
    }

    if (rowbuf)
	G_free(rowbuf);

    return 0;
}
Esempio n. 6
0
static int draw_cell(int A_row,
		     const void *array,
		     struct Colors *colors, RASTER_MAP_TYPE data_type)
{
    static unsigned char *red, *grn, *blu, *set;
    static int nalloc;

    int ncols = src[0][1] - src[0][0];
    int i;

    if (nalloc < ncols) {
	nalloc = ncols;
	red = G_realloc(red, nalloc);
	grn = G_realloc(grn, nalloc);
	blu = G_realloc(blu, nalloc);
	set = G_realloc(set, nalloc);
    }

    Rast_lookup_colors(array, red, grn, blu, set, ncols, colors,
			   data_type);

    if (D__overlay_mode)
	for (i = 0; i < ncols; i++) {
	    set[i] = Rast_is_null_value(array, data_type);
	    array = G_incr_void_ptr(array, Rast_cell_size(data_type));
	}

    A_row =
	COM_raster(ncols, A_row, red, grn, blu, D__overlay_mode ? set : NULL);

    return (A_row < src[1][1])
	? A_row : -1;
}
Esempio n. 7
0
static void embed_nulls(int fd, void *buf, int row, RASTER_MAP_TYPE map_type,
			int null_is_zero, int with_mask)
{
    struct fileinfo *fcb = &R__.fileinfo[fd];
    size_t size = Rast_cell_size(map_type);
    char *null_buf;
    int i;

    /* this is because without null file the nulls can be only due to 0's
       in data row or mask */
    if (null_is_zero && !fcb->null_file_exists
	&& (R__.auto_mask <= 0 || !with_mask))
	return;

    null_buf = G_alloca(R__.rd_window.cols);

    get_null_value_row(fd, null_buf, row, with_mask);

    for (i = 0; i < R__.rd_window.cols; i++) {
	/* also check for nulls which might be already embedded by quant
	   rules in case of fp map. */
	if (null_buf[i] || Rast_is_null_value(buf, map_type)) {
	    /* G__set_[f/d]_null_value() sets it to 0 is the embedded mode
	       is not set and calls G_set_[f/d]_null_value() otherwise */
	    Rast__set_null_value(buf, 1, null_is_zero, map_type);
	}
	buf = G_incr_void_ptr(buf, size);
    }

    G_freea(null_buf);
}
Esempio n. 8
0
static void *get_cell_ptr(void *array, int cols, int row, int col,
			  RASTER_MAP_TYPE map_type)
{
    return G_incr_void_ptr(array,
			   ((row * (size_t) cols) +
			    col) * Rast_cell_size(map_type));
}
Esempio n. 9
0
int blank_array(void *array, int nrows, int ncols, RASTER_MAP_TYPE map_type,
		int value)
{
    /* flood fill initialize the array to either 0 or NULL */
    /*  "value" can be either 0 (for 0.0) or -1 (for NULL) */
    int row, col;
    void *ptr;

    ptr = array;

    switch (value) {
    case 0:
	/* fill with 0 */
	/* simpler to use Rast_raster_cpy() or similar ?? */

	for (row = 0; row < nrows; row++) {
	    for (col = 0; col < ncols; col++) {
		Rast_set_c_value(ptr, 0, map_type);
		ptr = G_incr_void_ptr(ptr, Rast_cell_size(map_type));
	    }
	}
	break;

    case -1:
	/* fill with NULL */
	/* alloc for col+1, do we come up (nrows) short? no. */
	Rast_set_null_value(array, nrows * ncols, map_type);
	break;

    default:
	return -1;
    }

    return 0;
}
Esempio n. 10
0
int Rast3d_copy_to_xdr(const void *src, int nofNum)
{
    int i;

    if (useXdr == RASTER3D_NO_XDR) {
	Rast3d_copy_values(src, 0, srcType, xdrTmp, 0, type, nofNum);
	xdrTmp = G_incr_void_ptr(xdrTmp, nofNum * Rast3d_extern_length(type));
	return 1;
    }

    for (i = 0; i < nofNum; i++, src = G_incr_void_ptr(src, eltLength)) {

	if (Rast3d_is_null_value_num(src, srcType)) {
	    Rast3d_set_xdr_null_num(xdrTmp, isFloat);
	    if (!xdr_setpos(xdrs, xdr_getpos(xdrs) + externLength)) {
		Rast3d_error("Rast3d_copy_to_xdr: positioning xdr failed");
		return 0;
	    }
	}
	else {
	    if (type == srcType) {
		if (xdrFun(xdrs, src) < 0) {
		    Rast3d_error("Rast3d_copy_to_xdr: writing xdr failed");
		    return 0;
		}
	    }
	    else {
		if (type == FCELL_TYPE)
		    *((float *)tmp) = (float)*((double *)src);
		else
		    *((double *)tmp) = (double)*((float *)src);
		if (xdrFun(xdrs, tmp) < 0) {
		    Rast3d_error("Rast3d_copy_to_xdr: writing xdr failed");
		    return 0;
		}
	    }
	}

	xdrTmp = G_incr_void_ptr(xdrTmp, externLength);
    }

    return 1;
}
Esempio n. 11
0
int Rast3d_copy_from_xdr(int nofNum, void *dst)
{
    int i;

    if (useXdr == RASTER3D_NO_XDR) {
	Rast3d_copy_values(xdrTmp, 0, type, dst, 0, dstType, nofNum);
	xdrTmp = G_incr_void_ptr(xdrTmp, nofNum * Rast3d_extern_length(type));
	return 1;
    }

    for (i = 0; i < nofNum; i++, dst = G_incr_void_ptr(dst, eltLength)) {

	if (Rast3d_is_xdr_null_num(xdrTmp, isFloat)) {
	    Rast3d_set_null_value(dst, 1, dstType);
	    if (!xdr_setpos(xdrs, xdr_getpos(xdrs) + externLength)) {
		Rast3d_error("Rast3d_copy_from_xdr: positioning xdr failed");
		return 0;
	    }
	}
	else {
	    if (type == dstType) {
		if (xdrFun(xdrs, dst) < 0) {
		    Rast3d_error("Rast3d_copy_from_xdr: reading xdr failed");
		    return 0;
		}
	    }
	    else {
		if (xdrFun(xdrs, tmp) < 0) {
		    Rast3d_error("Rast3d_copy_from_xdr: reading xdr failed");
		    return 0;
		}
		if (type == FCELL_TYPE)
		    *((double *)dst) = (double)*((float *)tmp);
		else
		    *((float *)dst) = (float)*((double *)tmp);
	    }
	}

	xdrTmp = G_incr_void_ptr(xdrTmp, externLength);
    }

    return 1;
}
Esempio n. 12
0
void
G3d_range_updateFromTile(G3D_Map * map, const void *tile, int rows, int cols,
			 int depths, int xRedundant, int yRedundant,
			 int zRedundant, int nofNum, int type)
{
    int y, z, cellType;
    struct FPRange *range;

    range = &(map->range);
    cellType = G3d_g3dType2cellType(type);

    if (nofNum == map->tileSize) {
	G_row_update_fp_range(tile, map->tileSize, range, cellType);
	return;
    }

    if (xRedundant) {
	for (z = 0; z < depths; z++) {
	    for (y = 0; y < rows; y++) {
		G_row_update_fp_range(tile, cols, range, cellType);
		tile = G_incr_void_ptr(tile, map->tileX * G3d_length(type));
	    }
	    if (yRedundant)
		tile =
		    G_incr_void_ptr(tile,
				    map->tileX * yRedundant *
				    G3d_length(type));
	}
	return;
    }

    if (yRedundant) {
	for (z = 0; z < depths; z++) {
	    G_row_update_fp_range(tile, map->tileX * rows, range, cellType);
	    tile = G_incr_void_ptr(tile, map->tileXY * G3d_length(type));
	}
	return;
    }

    G_row_update_fp_range(tile, map->tileXY * depths, range, cellType);
}
Esempio n. 13
0
File: range.c Progetto: caomw/grass
/*!
 * \brief Update range structure based on raster row (floating-point)
 *
 * This routine updates the <i>range</i> data just like
 * Rast_update_range(), but for <i>n</i> values from the <i>cell</i>
 * array.
 *
 * \param cell raster values
 * \param n number of values
 * \param range pointer to Range structure which holds range info
 * \param data_type raster type (CELL, FCELL, DCELL)
 */
void Rast_row_update_fp_range(const void *rast, int n,
			      struct FPRange *range,
			      RASTER_MAP_TYPE data_type)
{
    size_t size = Rast_cell_size(data_type);
    DCELL val = 0.0;

    while (n-- > 0) {
	switch (data_type) {
	case CELL_TYPE:
	    val = (DCELL) * ((CELL *) rast);
	    break;
	case FCELL_TYPE:
	    val = (DCELL) * ((FCELL *) rast);
	    break;
	case DCELL_TYPE:
	    val = *((DCELL *) rast);
	    break;
	}

	if (Rast_is_null_value(rast, data_type)) {
	    rast = G_incr_void_ptr(rast, size);
	    continue;
	}
	if (range->first_time) {
	    range->first_time = 0;
	    range->min = val;
	    range->max = val;
	}
	else {
	    if (val < range->min)
		range->min = val;
	    if (val > range->max)
		range->max = val;
	}

	rast = G_incr_void_ptr(rast, size);
    }
}
Esempio n. 14
0
void
Rast3d_copy_values(const void *src, int offsSrc, int typeSrc, void *dst,
                   int offsDst, int typeDst, int nElts)
{
    int eltLength;

    if ((typeSrc == FCELL_TYPE) && (typeDst == DCELL_TYPE)) {
        Rast3d_copy_float2Double(src, offsSrc, dst, offsDst, nElts);
        return;
    }

    if ((typeSrc == DCELL_TYPE) && (typeDst == FCELL_TYPE)) {
        Rast3d_copy_double2Float(src, offsSrc, dst, offsDst, nElts);
        return;
    }

    eltLength = Rast3d_length(typeSrc);

    src = G_incr_void_ptr(src, eltLength * offsSrc);
    dst = G_incr_void_ptr(dst, eltLength * offsDst);

    memcpy(dst, src, nElts * eltLength);
}
Esempio n. 15
0
int mask_raster_array(void *rast, int ncols,
		      int change_null, RASTER_MAP_TYPE data_type)
{
    DCELL x;

    while (ncols-- > 0) {
	x = Rast_get_d_value(rast, data_type);
	if (change_null && Rast_is_null_value(rast, data_type))
	    Rast_set_d_value(rast, new_null, data_type);
	if (mask_d_select(&x, &d_mask))
	    Rast_set_null_value(rast, 1, data_type);
	rast = G_incr_void_ptr(rast, Rast_cell_size(data_type));
    }

    return 0;
}
Esempio n. 16
0
void *read_raster(void *buf, const int fd, const RASTER_MAP_TYPE rtype)
{
    void *tmpbuf = buf;
    int rows = Rast_window_rows();
    int i;

    G_message(_("Reading raster map..."));

    for (i = 0; i < rows; i++) {
	G_percent(i + 1, rows, 10);

	Rast_get_row(fd, tmpbuf, i, rtype);
	tmpbuf =
	    G_incr_void_ptr(tmpbuf, Rast_cell_size(rtype) * Rast_window_cols());
    }

    return tmpbuf;
}
Esempio n. 17
0
/*!
 * \brief Looks up the category label for each raster value (DCELL).
 * 
 * Looks up the category label for each raster value in the
 * <i>rast_row</i> and updates the marks for labels found.
 *
 * <b>Note:</b> Non-zero mark for i-th label stores the number of of
 * raster cells read so far which are labeled with i-th label and fall
 * into i-th data range.
 *
 * \param rast_row raster row to update stats
 * \param ncols number of columns
 * \param pcats pointer to Categories structure
 *
 * \return -1 on error
 * \return 1 on success
 */
int Rast_mark_cats(const void *rast_row,
		   int ncols, struct Categories *pcats,
		   RASTER_MAP_TYPE data_type)
{
    size_t size = Rast_cell_size(data_type);
    CELL i;

    while (ncols-- > 0) {
	i = Rast_quant_get_cell_value(&pcats->q,
				      Rast_get_d_value(rast_row, data_type));
	if (Rast_is_c_null_value(&i))
	    continue;
	if (i > pcats->ncats)
	    return -1;
	pcats->marks[i]++;
	rast_row = G_incr_void_ptr(rast_row, size);
    }
    return 1;
}
Esempio n. 18
0
static void get_map_row(int fd, void *rast, int row, RASTER_MAP_TYPE data_type,
			int null_is_zero, int with_mask)
{
    struct fileinfo *fcb = &R__.fileinfo[fd];
    int size = Rast_cell_size(data_type);
    CELL *temp_buf = NULL;
    void *buf;
    int type;
    int i;

    if (fcb->reclass_flag && data_type != CELL_TYPE) {
	temp_buf = G_alloca(R__.rd_window.cols * sizeof(CELL));
	buf = temp_buf;
	type = CELL_TYPE;
    }
    else {
	buf = rast;
	type = data_type;
    }

    get_map_row_no_reclass(fd, buf, row, type, null_is_zero, with_mask);

    if (!fcb->reclass_flag)
	return;

    /* if the map is reclass table, get and
       reclass CELL row and copy results to needed type  */

    do_reclass_int(fd, buf, null_is_zero);

    if (data_type == CELL_TYPE)
	return;

    for (i = 0; i < R__.rd_window.cols; i++) {
	Rast_set_c_value(rast, temp_buf[i], data_type);
	rast = G_incr_void_ptr(rast, size);
    }

    G_freea(temp_buf);
}
Esempio n. 19
0
/*---------------------------------------------------------------------------------------*/
void P_Aux_to_Raster(double **matrix, int fd)
{
    int ncols, col, nrows, row;
    void *ptr, *raster;

    nrows = Rast_window_rows();
    ncols = Rast_window_cols();

    raster = Rast_allocate_buf(DCELL_TYPE);

    for (row = 0; row < nrows; row++) {
	G_percent(row, nrows, 2);

	Rast_set_d_null_value(raster, ncols);

	for (col = 0, ptr = raster; col < ncols;
	     col++, ptr = G_incr_void_ptr(ptr, Rast_cell_size(DCELL_TYPE))) {
	    Rast_set_d_value(ptr, (DCELL) (matrix[row][col]), DCELL_TYPE);
	}
	Rast_put_d_row(fd, raster);
    }
    G_percent(row, nrows, 2);
}
Esempio n. 20
0
int rectify(char *name, char *mapset, struct cache *ebuffer,
            double aver_z, char *result, char *interp_method)
{
    struct Cell_head cellhd;
    int ncols, nrows;
    int row, col;
    double row_idx, col_idx;
    int infd, outfd;
    RASTER_MAP_TYPE map_type;
    int cell_size;
    void *trast, *tptr;
    double n1, e1, z1;
    double nx, ex, nx1, ex1, zx1;
    struct cache *ibuffer;

    select_current_env();
    Rast_get_cellhd(name, mapset, &cellhd);

    /* open the file to be rectified
     * set window to cellhd first to be able to read file exactly
     */
    Rast_set_input_window(&cellhd);
    infd = Rast_open_old(name, mapset);
    map_type = Rast_get_map_type(infd);
    cell_size = Rast_cell_size(map_type);

    ibuffer = readcell(infd, seg_mb_img, 0);

    Rast_close(infd);		/* (pmx) 17 april 2000 */

    G_message(_("Rectify <%s@%s> (location <%s>)"),
	      name, mapset, G_location());
    select_target_env();
    G_set_window(&target_window);
    G_message(_("into  <%s@%s> (location <%s>) ..."),
	      result, G_mapset(), G_location());

    nrows = target_window.rows;
    ncols = target_window.cols;

    if (strcmp(interp_method, "nearest") != 0) {
	map_type = DCELL_TYPE;
	cell_size = Rast_cell_size(map_type);
    }

    /* open the result file into target window
     * this open must be first since we change the window later
     * raster maps open for writing are not affected by window changes
     * but those open for reading are
     */

    outfd = Rast_open_new(result, map_type);
    trast = Rast_allocate_output_buf(map_type);

    for (row = 0; row < nrows; row++) {
	n1 = target_window.north - (row + 0.5) * target_window.ns_res;

	G_percent(row, nrows, 2);

	Rast_set_null_value(trast, ncols, map_type);
	tptr = trast;
	for (col = 0; col < ncols; col++) {
	    DCELL *zp = CPTR(ebuffer, row, col);

	    e1 = target_window.west + (col + 0.5) * target_window.ew_res;
	    
	    /* if target cell has no elevation, set to aver_z */
	    if (Rast_is_d_null_value(zp)) {
		G_warning(_("No elevation available at row = %d, col = %d"), row, col);
		z1 = aver_z;
	    }
	    else
		z1 = *zp;

	    /* target coordinates e1, n1 to photo coordinates ex1, nx1 */
	    I_ortho_ref(e1, n1, z1, &ex1, &nx1, &zx1, &group.camera_ref,
			group.XC, group.YC, group.ZC, group.M);

	    G_debug(5, "\t\tAfter ortho ref (photo cords): ex = %f \t nx =  %f",
		    ex1, nx1);

	    /* photo coordinates ex1, nx1 to image coordinates ex, nx */
	    I_georef(ex1, nx1, &ex, &nx, group.E21, group.N21, 1);

	    G_debug(5, "\t\tAfter geo ref: ex = %f \t nx =  %f", ex, nx);

	    /* convert to row/column indices of source raster */
	    row_idx = (cellhd.north - nx) / cellhd.ns_res;
	    col_idx = (ex - cellhd.west) / cellhd.ew_res;

	    /* resample data point */
	    interpolate(ibuffer, tptr, map_type, &row_idx, &col_idx, &cellhd);

	    tptr = G_incr_void_ptr(tptr, cell_size);
	}
	Rast_put_row(outfd, trast, map_type);
    }
    G_percent(1, 1, 1);

    Rast_close(outfd);		/* (pmx) 17 april 2000 */
    G_free(trast);

    close(ibuffer->fd);
    release_cache(ibuffer);

    Rast_get_cellhd(result, G_mapset(), &cellhd);

    if (cellhd.proj == 0) {	/* x,y imagery */
	cellhd.proj = target_window.proj;
	cellhd.zone = target_window.zone;
    }

    if (target_window.proj != cellhd.proj) {
	cellhd.proj = target_window.proj;
	G_warning(_("Raster map <%s@%s>: projection don't match current settings"),
		  name, mapset);
    }

    if (target_window.zone != cellhd.zone) {
	cellhd.zone = target_window.zone;
	G_warning(_("Raster map <%s@%s>: zone don't match current settings"),
		  name, mapset);
    }

    select_current_env();

    return 1;
}
Esempio n. 21
0
int main(int argc, char **argv)
{
    char *mapname,		/* ptr to name of output layer  */
     *setname,			/* ptr to name of input mapset  */
     *ipolname;			/* name of interpolation method */

    int fdi,			/* input map file descriptor    */
      fdo,			/* output map file descriptor   */
      method,			/* position of method in table  */
      permissions,		/* mapset permissions           */
      cell_type,		/* output celltype              */
      cell_size,		/* size of a cell in bytes      */
      row, col,			/* counters                     */
      irows, icols,		/* original rows, cols          */
      orows, ocols, have_colors,	/* Input map has a colour table */
      overwrite,		/* Overwrite                    */
      curr_proj;		/* output projection (see gis.h) */

    void *obuffer,		/* buffer that holds one output row     */
     *obufptr;			/* column ptr in output buffer  */
    struct cache *ibuffer;	/* buffer that holds the input map      */
    func interpolate;		/* interpolation routine        */

    double xcoord1, xcoord2,	/* temporary x coordinates      */
      ycoord1, ycoord2,		/* temporary y coordinates      */
      col_idx,			/* column index in input matrix */
      row_idx,			/* row index in input matrix    */
      onorth, osouth,		/* save original border coords  */
      oeast, owest, inorth, isouth, ieast, iwest;
    char north_str[30], south_str[30], east_str[30], west_str[30];

    struct Colors colr;		/* Input map colour table       */
    struct History history;

    struct pj_info iproj,	/* input map proj parameters    */
      oproj;			/* output map proj parameters   */

    struct Key_Value *in_proj_info,	/* projection information of    */
     *in_unit_info,		/* input and output mapsets     */
     *out_proj_info, *out_unit_info;

    struct GModule *module;

    struct Flag *list,		/* list files in source location */
     *nocrop,			/* don't crop output map        */
     *print_bounds,		/* print output bounds and exit */
     *gprint_bounds;		/* same but print shell style	*/

    struct Option *imapset,	/* name of input mapset         */
     *inmap,			/* name of input layer          */
     *inlocation,		/* name of input location       */
     *outmap,			/* name of output layer         */
     *indbase,			/* name of input database       */
     *interpol,			/* interpolation method:
				   nearest neighbor, bilinear, cubic */
     *memory,			/* amount of memory for cache   */
     *res;			/* resolution of target map     */
    struct Cell_head incellhd,	/* cell header of input map     */
      outcellhd;		/* and output map               */


    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("projection"));
    G_add_keyword(_("transformation"));
    module->description =
	_("Re-projects a raster map from given location to the current location.");

    inmap = G_define_standard_option(G_OPT_R_INPUT);
    inmap->description = _("Name of input raster map to re-project");
    inmap->required = NO;
    inmap->guisection = _("Source");

    inlocation = G_define_option();
    inlocation->key = "location";
    inlocation->type = TYPE_STRING;
    inlocation->required = YES;
    inlocation->description = _("Location containing input raster map");
    inlocation->gisprompt = "old,location,location";
    inlocation->key_desc = "name";

    imapset = G_define_standard_option(G_OPT_M_MAPSET);
    imapset->label = _("Mapset containing input raster map");
    imapset->description = _("default: name of current mapset");
    imapset->guisection = _("Source");

    indbase = G_define_option();
    indbase->key = "dbase";
    indbase->type = TYPE_STRING;
    indbase->required = NO;
    indbase->description = _("Path to GRASS database of input location");
    indbase->gisprompt = "old,dbase,dbase";
    indbase->key_desc = "path";
    indbase->guisection = _("Source");

    outmap = G_define_standard_option(G_OPT_R_OUTPUT);
    outmap->required = NO;
    outmap->description = _("Name for output raster map (default: same as 'input')");
    outmap->guisection = _("Target");

    ipolname = make_ipol_list();
    
    interpol = G_define_option();
    interpol->key = "method";
    interpol->type = TYPE_STRING;
    interpol->required = NO;
    interpol->answer = "nearest";
    interpol->options = ipolname;
    interpol->description = _("Interpolation method to use");
    interpol->guisection = _("Target");
    interpol->descriptions = make_ipol_desc();

    memory = G_define_option();
    memory->key = "memory";
    memory->type = TYPE_INTEGER;
    memory->required = NO;
    memory->description = _("Cache size (MiB)");

    res = G_define_option();
    res->key = "resolution";
    res->type = TYPE_DOUBLE;
    res->required = NO;
    res->description = _("Resolution of output raster map");
    res->guisection = _("Target");

    list = G_define_flag();
    list->key = 'l';
    list->description = _("List raster maps in input location and exit");

    nocrop = G_define_flag();
    nocrop->key = 'n';
    nocrop->description = _("Do not perform region cropping optimization");

    print_bounds = G_define_flag();
    print_bounds->key = 'p';
    print_bounds->description =
	_("Print input map's bounds in the current projection and exit");
    print_bounds->guisection = _("Target");
    
    gprint_bounds = G_define_flag();
    gprint_bounds->key = 'g';
    gprint_bounds->description =
	_("Print input map's bounds in the current projection and exit (shell style)");
    gprint_bounds->guisection = _("Target");

    /* The parser checks if the map already exists in current mapset,
       we switch out the check and do it
       in the module after the parser */
    overwrite = G_check_overwrite(argc, argv);

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


    /* get the method */
    for (method = 0; (ipolname = menu[method].name); method++)
	if (strcmp(ipolname, interpol->answer) == 0)
	    break;

    if (!ipolname)
	G_fatal_error(_("<%s=%s> unknown %s"),
		      interpol->key, interpol->answer, interpol->key);
    interpolate = menu[method].method;

    mapname = outmap->answer ? outmap->answer : inmap->answer;
    if (mapname && !list->answer && !overwrite &&
	G_find_raster(mapname, G_mapset()))
	G_fatal_error(_("option <%s>: <%s> exists."), "output", mapname);

    setname = imapset->answer ? imapset->answer : G_store(G_mapset());
    if (strcmp(inlocation->answer, G_location()) == 0 &&
        (!indbase->answer || strcmp(indbase->answer, G_gisdbase()) == 0))
#if 0
	G_fatal_error(_("Input and output locations can not be the same"));
#else
	G_warning(_("Input and output locations are the same"));
#endif
    G_get_window(&outcellhd);

    if(gprint_bounds->answer && !print_bounds->answer)
	print_bounds->answer = gprint_bounds->answer;
    curr_proj = G_projection();

    /* Get projection info for output mapset */
    if ((out_proj_info = G_get_projinfo()) == NULL)
	G_fatal_error(_("Unable to get projection info of output raster map"));

    if ((out_unit_info = G_get_projunits()) == NULL)
	G_fatal_error(_("Unable to get projection units of output raster map"));

    if (pj_get_kv(&oproj, out_proj_info, out_unit_info) < 0)
	G_fatal_error(_("Unable to get projection key values of output raster map"));

    /* Change the location           */
    G__create_alt_env();
    G__setenv("GISDBASE", indbase->answer ? indbase->answer : G_gisdbase());
    G__setenv("LOCATION_NAME", inlocation->answer);

    permissions = G__mapset_permissions(setname);
    if (permissions < 0)	/* can't access mapset       */
	G_fatal_error(_("Mapset <%s> in input location <%s> - %s"),
		      setname, inlocation->answer,
		      permissions == 0 ? _("permission denied")
		      : _("not found"));

    /* if requested, list the raster maps in source location - MN 5/2001 */
    if (list->answer) {
	int i;
	char **list;
	G_verbose_message(_("Checking location <%s> mapset <%s>"),
			  inlocation->answer, setname);
	list = G_list(G_ELEMENT_RASTER, G__getenv("GISDBASE"),
		      G__getenv("LOCATION_NAME"), setname);
	for (i = 0; list[i]; i++) {
	    fprintf(stdout, "%s\n", list[i]);
	}
	fflush(stdout);
	exit(EXIT_SUCCESS);	/* leave r.proj after listing */
    }

    if (!inmap->answer)
	G_fatal_error(_("Required parameter <%s> not set"), inmap->key);

    if (!G_find_raster(inmap->answer, setname))
	G_fatal_error(_("Raster map <%s> in location <%s> in mapset <%s> not found"),
		      inmap->answer, inlocation->answer, setname);

    /* Read input map colour table */
    have_colors = Rast_read_colors(inmap->answer, setname, &colr);

    /* Get projection info for input mapset */
    if ((in_proj_info = G_get_projinfo()) == NULL)
	G_fatal_error(_("Unable to get projection info of input map"));

    if ((in_unit_info = G_get_projunits()) == NULL)
	G_fatal_error(_("Unable to get projection units of input map"));

    if (pj_get_kv(&iproj, in_proj_info, in_unit_info) < 0)
	G_fatal_error(_("Unable to get projection key values of input map"));

    G_free_key_value(in_proj_info);
    G_free_key_value(in_unit_info);
    G_free_key_value(out_proj_info);
    G_free_key_value(out_unit_info);
    if (G_verbose() > G_verbose_std())
	pj_print_proj_params(&iproj, &oproj);

    /* this call causes r.proj to read the entire map into memeory */
    Rast_get_cellhd(inmap->answer, setname, &incellhd);

    Rast_set_input_window(&incellhd);

    if (G_projection() == PROJECTION_XY)
	G_fatal_error(_("Unable to work with unprojected data (xy location)"));

    /* Save default borders so we can show them later */
    inorth = incellhd.north;
    isouth = incellhd.south;
    ieast = incellhd.east;
    iwest = incellhd.west;
    irows = incellhd.rows;
    icols = incellhd.cols;

    onorth = outcellhd.north;
    osouth = outcellhd.south;
    oeast = outcellhd.east;
    owest = outcellhd.west;
    orows = outcellhd.rows;
    ocols = outcellhd.cols;


    if (print_bounds->answer) {
	G_message(_("Input map <%s@%s> in location <%s>:"),
	    inmap->answer, setname, inlocation->answer);

	if (pj_do_proj(&iwest, &isouth, &iproj, &oproj) < 0)
	    G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)"));
	if (pj_do_proj(&ieast, &inorth, &iproj, &oproj) < 0)
	    G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)"));

	G_format_northing(inorth, north_str, curr_proj);
	G_format_northing(isouth, south_str, curr_proj);
	G_format_easting(ieast, east_str, curr_proj);
	G_format_easting(iwest, west_str, curr_proj);

	if(gprint_bounds->answer) {
	    fprintf(stdout, "n=%s s=%s w=%s e=%s rows=%d cols=%d\n",
		north_str, south_str, west_str, east_str, irows, icols);
	}
	else {
	    fprintf(stdout, "Source cols: %d\n", icols);
	    fprintf(stdout, "Source rows: %d\n", irows);
	    fprintf(stdout, "Local north: %s\n",  north_str);
	    fprintf(stdout, "Local south: %s\n", south_str);
	    fprintf(stdout, "Local west: %s\n", west_str);
	    fprintf(stdout, "Local east: %s\n", east_str);
	}

	/* somehow approximate local ewres, nsres ?? (use 'g.region -m' on lat/lon side) */

	exit(EXIT_SUCCESS);
    }


    /* Cut non-overlapping parts of input map */
    if (!nocrop->answer)
	bordwalk(&outcellhd, &incellhd, &oproj, &iproj);

    /* Add 2 cells on each side for bilinear/cubic & future interpolation methods */
    /* (should probably be a factor based on input and output resolution) */
    incellhd.north += 2 * incellhd.ns_res;
    incellhd.east += 2 * incellhd.ew_res;
    incellhd.south -= 2 * incellhd.ns_res;
    incellhd.west -= 2 * incellhd.ew_res;
    if (incellhd.north > inorth)
	incellhd.north = inorth;
    if (incellhd.east > ieast)
	incellhd.east = ieast;
    if (incellhd.south < isouth)
	incellhd.south = isouth;
    if (incellhd.west < iwest)
	incellhd.west = iwest;

    Rast_set_input_window(&incellhd);

    /* And switch back to original location */

    G__switch_env();

    /* Adjust borders of output map */

    if (!nocrop->answer)
	bordwalk(&incellhd, &outcellhd, &iproj, &oproj);

#if 0
    outcellhd.west = outcellhd.south = HUGE_VAL;
    outcellhd.east = outcellhd.north = -HUGE_VAL;
    for (row = 0; row < incellhd.rows; row++) {
	ycoord1 = Rast_row_to_northing((double)(row + 0.5), &incellhd);
	for (col = 0; col < incellhd.cols; col++) {
	    xcoord1 = Rast_col_to_easting((double)(col + 0.5), &incellhd);
	    pj_do_proj(&xcoord1, &ycoord1, &iproj, &oproj);
	    if (xcoord1 > outcellhd.east)
		outcellhd.east = xcoord1;
	    if (ycoord1 > outcellhd.north)
		outcellhd.north = ycoord1;
	    if (xcoord1 < outcellhd.west)
		outcellhd.west = xcoord1;
	    if (ycoord1 < outcellhd.south)
		outcellhd.south = ycoord1;
	}
    }
#endif

    if (res->answer != NULL)	/* set user defined resolution */
	outcellhd.ns_res = outcellhd.ew_res = atof(res->answer);

    G_adjust_Cell_head(&outcellhd, 0, 0);
    Rast_set_output_window(&outcellhd);

    G_message(" ");
    G_message(_("Input:"));
    G_message(_("Cols: %d (%d)"), incellhd.cols, icols);
    G_message(_("Rows: %d (%d)"), incellhd.rows, irows);
    G_message(_("North: %f (%f)"), incellhd.north, inorth);
    G_message(_("South: %f (%f)"), incellhd.south, isouth);
    G_message(_("West: %f (%f)"), incellhd.west, iwest);
    G_message(_("East: %f (%f)"), incellhd.east, ieast);
    G_message(_("EW-res: %f"), incellhd.ew_res);
    G_message(_("NS-res: %f"), incellhd.ns_res);
    G_message(" ");

    G_message(_("Output:"));
    G_message(_("Cols: %d (%d)"), outcellhd.cols, ocols);
    G_message(_("Rows: %d (%d)"), outcellhd.rows, orows);
    G_message(_("North: %f (%f)"), outcellhd.north, onorth);
    G_message(_("South: %f (%f)"), outcellhd.south, osouth);
    G_message(_("West: %f (%f)"), outcellhd.west, owest);
    G_message(_("East: %f (%f)"), outcellhd.east, oeast);
    G_message(_("EW-res: %f"), outcellhd.ew_res);
    G_message(_("NS-res: %f"), outcellhd.ns_res);
    G_message(" ");

    /* open and read the relevant parts of the input map and close it */
    G__switch_env();
    Rast_set_input_window(&incellhd);
    fdi = Rast_open_old(inmap->answer, setname);
    cell_type = Rast_get_map_type(fdi);
    ibuffer = readcell(fdi, memory->answer);
    Rast_close(fdi);

    G__switch_env();
    Rast_set_output_window(&outcellhd);

    if (strcmp(interpol->answer, "nearest") == 0) {
	fdo = Rast_open_new(mapname, cell_type);
	obuffer = (CELL *) Rast_allocate_output_buf(cell_type);
    }
    else {
	fdo = Rast_open_fp_new(mapname);
	cell_type = FCELL_TYPE;
	obuffer = (FCELL *) Rast_allocate_output_buf(cell_type);
    }

    cell_size = Rast_cell_size(cell_type);

    xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2);
    /**/ ycoord1 = ycoord2 = outcellhd.north - (outcellhd.ns_res / 2);
    /**/ G_important_message(_("Projecting..."));
    G_percent(0, outcellhd.rows, 2);

    for (row = 0; row < outcellhd.rows; row++) {
	obufptr = obuffer;

	for (col = 0; col < outcellhd.cols; col++) {
	    /* project coordinates in output matrix to       */
	    /* coordinates in input matrix                   */
	    if (pj_do_proj(&xcoord1, &ycoord1, &oproj, &iproj) < 0)
		Rast_set_null_value(obufptr, 1, cell_type);
	    else {
		/* convert to row/column indices of input matrix */
		col_idx = (xcoord1 - incellhd.west) / incellhd.ew_res;
		row_idx = (incellhd.north - ycoord1) / incellhd.ns_res;

		/* and resample data point               */
		interpolate(ibuffer, obufptr, cell_type,
			    &col_idx, &row_idx, &incellhd);
	    }

	    obufptr = G_incr_void_ptr(obufptr, cell_size);
	    xcoord2 += outcellhd.ew_res;
	    xcoord1 = xcoord2;
	    ycoord1 = ycoord2;
	}

	Rast_put_row(fdo, obuffer, cell_type);

	xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2);
	ycoord2 -= outcellhd.ns_res;
	ycoord1 = ycoord2;
	G_percent(row, outcellhd.rows - 1, 2);
    }

    Rast_close(fdo);

    if (have_colors > 0) {
	Rast_write_colors(mapname, G_mapset(), &colr);
	Rast_free_colors(&colr);
    }

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

    G_done_msg(NULL);
    exit(EXIT_SUCCESS);
}
Esempio n. 22
0
static int
G3d_xdrTile2tile(G3D_Map * map, void *tile, int rows, int cols, int depths,
		 int xRedundant, int yRedundant, int zRedundant, int nofNum,
		 int type)
{
    int y, z, xLength, yLength, length;

    if (!G3d_initCopyFromXdr(map, type)) {
	G3d_error("G3d_xdrTile2tile: error in G3d_initCopyFromXdr");
	return 0;
    }

    if (nofNum == map->tileSize) {
	if (!G3d_copyFromXdr(map->tileSize, tile)) {
	    G3d_error("G3d_xdrTile2tile: error in G3d_copyFromXdr");
	    return 0;
	}
	return 1;
    }

    length = G3d_length(type);
    xLength = xRedundant * length;
    yLength = map->tileX * yRedundant * length;

    if (xRedundant) {
	for (z = 0; z < depths; z++) {
	    for (y = 0; y < rows; y++) {
		if (!G3d_copyFromXdr(cols, tile)) {
		    G3d_error("G3d_xdrTile2tile: error in G3d_copyFromXdr");
		    return 0;
		}
		tile = G_incr_void_ptr(tile, cols * length);
		G3d_setNullValue(tile, xRedundant, type);
		tile = G_incr_void_ptr(tile, xLength);
	    }
	    if (yRedundant) {
		G3d_setNullValue(tile, map->tileX * yRedundant, type);
		tile = G_incr_void_ptr(tile, yLength);
	    }
	}
	if (!zRedundant)
	    return 1;

	G3d_setNullValue(tile, map->tileXY * zRedundant, type);
	return 1;
    }

    if (yRedundant) {
	for (z = 0; z < depths; z++) {
	    if (!G3d_copyFromXdr(map->tileX * rows, tile)) {
		G3d_error("G3d_xdrTile2tile: error in G3d_copyFromXdr");
		return 0;
	    }
	    tile = G_incr_void_ptr(tile, map->tileX * rows * length);
	    G3d_setNullValue(tile, map->tileX * yRedundant, type);
	    tile = G_incr_void_ptr(tile, yLength);
	}
	if (!zRedundant)
	    return 1;

	G3d_setNullValue(tile, map->tileXY * zRedundant, type);
	return 1;
    }

    if (!G3d_copyFromXdr(map->tileXY * depths, tile)) {
	G3d_error("G3d_xdrTile2tile: error in G3d_copyFromXdr");
	return 0;
    }

    if (!zRedundant)
	return 1;

    tile = G_incr_void_ptr(tile, map->tileXY * depths * length);
    G3d_setNullValue(tile, map->tileXY * zRedundant, type);

    return 1;
}
Esempio n. 23
0
int main(int argc, char **argv)
{
    struct Cell_head window;
    RASTER_MAP_TYPE raster_type, mag_raster_type = -1;
    int layer_fd;
    void *raster_row, *ptr;
    int nrows, ncols;
    int aspect_c = -1;
    float aspect_f = -1.0;

    double scale;
    int skip, no_arrow;
    char *mag_map = NULL;
    void *mag_raster_row = NULL, *mag_ptr = NULL;
    double length = -1;
    int mag_fd = -1;
    struct FPRange range;
    double mag_min, mag_max;

    struct GModule *module;
    struct Option *opt1, *opt2, *opt3, *opt4, *opt5,
	*opt6, *opt7, *opt8, *opt9;
    struct Flag *align;

    double t, b, l, r;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("display"));
    G_add_keyword(_("raster"));
    module->description =
	_("Draws arrows representing cell aspect direction "
	  "for a raster map containing aspect data.");

    opt1 = G_define_standard_option(G_OPT_R_MAP);
    opt1->description = _("Name of raster aspect map to be displayed");

    opt2 = G_define_option();
    opt2->key = "type";
    opt2->type = TYPE_STRING;
    opt2->required = NO;
    opt2->answer = "grass";
    opt2->options = "grass,compass,agnps,answers";
    opt2->description = _("Type of existing raster aspect map");

    opt3 = G_define_option();
    opt3->key = "arrow_color";
    opt3->type = TYPE_STRING;
    opt3->required = NO;
    opt3->answer = "green";
    opt3->gisprompt = "old_color,color,color";
    opt3->description = _("Color for drawing arrows");
    opt3->guisection = _("Colors");
    
    opt4 = G_define_option();
    opt4->key = "grid_color";
    opt4->type = TYPE_STRING;
    opt4->required = NO;
    opt4->answer = "gray";
    opt4->gisprompt = "old_color,color,color_none";
    opt4->description = _("Color for drawing grid or \"none\"");
    opt4->guisection = _("Colors");

    opt5 = G_define_option();
    opt5->key = "x_color";
    opt5->type = TYPE_STRING;
    opt5->required = NO;
    opt5->answer = DEFAULT_FG_COLOR;
    opt5->gisprompt = "old_color,color,color_none";
    opt5->description = _("Color for drawing X's (null values)");
    opt5->guisection = _("Colors");

    opt6 = G_define_option();
    opt6->key = "unknown_color";
    opt6->type = TYPE_STRING;
    opt6->required = NO;
    opt6->answer = "red";
    opt6->gisprompt = "old_color,color,color_none";
    opt6->description = _("Color for showing unknown information");
    opt6->guisection = _("Colors");

    opt9 = G_define_option();
    opt9->key = "skip";
    opt9->type = TYPE_INTEGER;
    opt9->required = NO;
    opt9->answer = "1";
    opt9->description = _("Draw arrow every Nth grid cell");

    opt7 = G_define_option();
    opt7->key = "magnitude_map";
    opt7->type = TYPE_STRING;
    opt7->required = NO;
    opt7->multiple = NO;
    opt7->gisprompt = "old,cell,raster";
    opt7->description =
	_("Raster map containing values used for arrow length");

    opt8 = G_define_option();
    opt8->key = "scale";
    opt8->type = TYPE_DOUBLE;
    opt8->required = NO;
    opt8->answer = "1.0";
    opt8->description = _("Scale factor for arrows (magnitude map)");

    align = G_define_flag();
    align->key = 'a';
    align->description = _("Align grids with raster cells");


    /* Check command line */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    layer_name = opt1->answer;

    arrow_color = D_translate_color(opt3->answer);
    x_color = D_translate_color(opt5->answer);
    unknown_color = D_translate_color(opt6->answer);

    if (strcmp("none", opt4->answer) == 0)
	grid_color = -1;
    else
	grid_color = D_translate_color(opt4->answer);


    if (strcmp("grass", opt2->answer) == 0)
	map_type = 1;
    else if (strcmp("agnps", opt2->answer) == 0)
	map_type = 2;
    else if (strcmp("answers", opt2->answer) == 0)
	map_type = 3;
    else if (strcmp("compass", opt2->answer) == 0)
	map_type = 4;


    scale = atof(opt8->answer);
    if (scale <= 0.0)
	G_fatal_error(_("Illegal value for scale factor"));

    skip = atoi(opt9->answer);
    if (skip <= 0)
	G_fatal_error(_("Illegal value for skip factor"));


    if (opt7->answer) {
	if (map_type != 1 && map_type != 4)
	    G_fatal_error(_("Magnitude is only supported for GRASS and compass aspect maps."));

	mag_map = opt7->answer;
    }
    else if (scale != 1.0)
	G_warning(_("Scale option requires magnitude_map"));


    /* Setup driver and check important information */
    if (D_open_driver() != 0)
      	G_fatal_error(_("No graphics device selected. "
			"Use d.mon to select graphics device."));
    
    D_setup(0);

    /* Read in the map window associated with window */
    G_get_window(&window);

    if (align->answer) {
	struct Cell_head wind;

	Rast_get_cellhd(layer_name, "", &wind);

	/* expand window extent by one wind resolution */
	wind.west += wind.ew_res * ((int)((window.west - wind.west) / wind.ew_res) - (window.west < wind.west));
	wind.east += wind.ew_res * ((int)((window.east - wind.east) / wind.ew_res) + (window.east > wind.east));
	wind.south += wind.ns_res * ((int)((window.south - wind.south) / wind.ns_res) - (window.south < wind.south));
	wind.north += wind.ns_res * ((int)((window.north - wind.north) / wind.ns_res) + (window.north > wind.north));

	wind.rows = (wind.north - wind.south) / wind.ns_res;
	wind.cols = (wind.east - wind.west) / wind.ew_res;

	Rast_set_window(&wind);

	nrows = wind.rows;
	ncols = wind.cols;

	t = (wind.north - window.north) * nrows / (wind.north - wind.south);
	b = t + (window.north - window.south) * nrows / (wind.north - wind.south);
	l = (window.west - wind.west) * ncols / (wind.east - wind.west);
	r = l + (window.east - window.west) * ncols / (wind.east - wind.west);
    } else {
        nrows = window.rows;
        ncols = window.cols;

	t = 0;
	b = nrows;
	l = 0;
	r = ncols;
    }

    D_set_src(t, b, l, r);
    D_update_conversions();

    /* figure out arrow scaling if using a magnitude map */
    if (opt7->answer) {
	Rast_init_fp_range(&range);	/* really needed? */
	if (Rast_read_fp_range(mag_map, "", &range) != 1)
	    G_fatal_error(_("Problem reading range file"));
	Rast_get_fp_range_min_max(&range, &mag_min, &mag_max);

	scale *= 1.5 / fabs(mag_max);
	G_debug(3, "scaling=%.2f  rast_max=%.2f", scale, mag_max);
    }

    if (grid_color > 0) {	/* ie not "none" */
	/* Set color */
	D_use_color(grid_color);

	/* Draw vertical grids */
	for (col = 0; col < ncols; col++)
	    D_line_abs(col, 0, col, nrows);

	/* Draw horizontal grids */
	for (row = 0; row < nrows; row++)
	    D_line_abs(0, row, ncols, row);
    }

    /* open the raster map */
    layer_fd = Rast_open_old(layer_name, "");

    raster_type = Rast_get_map_type(layer_fd);

    /* allocate the cell array */
    raster_row = Rast_allocate_buf(raster_type);


    if (opt7->answer) {
	/* open the magnitude raster map */
	mag_fd = Rast_open_old(mag_map, "");

	mag_raster_type = Rast_get_map_type(mag_fd);

	/* allocate the cell array */
	mag_raster_row = Rast_allocate_buf(mag_raster_type);
    }


    /* loop through cells, find value, determine direction (n,s,e,w,ne,se,sw,nw),
       and call appropriate function to draw an arrow on the cell */

    for (row = 0; row < nrows; row++) {
	Rast_get_row(layer_fd, raster_row, row, raster_type);
	ptr = raster_row;

	if (opt7->answer) {
	    Rast_get_row(mag_fd, mag_raster_row, row, mag_raster_type);
	    mag_ptr = mag_raster_row;
	}

	for (col = 0; col < ncols; col++) {

	    if (row % skip != 0)
		no_arrow = TRUE;
	    else
		no_arrow = FALSE;

	    if (col % skip != 0)
		no_arrow = TRUE;

	    /* find aspect direction based on cell value */
	    if (raster_type == CELL_TYPE)
		aspect_f = *((CELL *) ptr);
	    else if (raster_type == FCELL_TYPE)
		aspect_f = *((FCELL *) ptr);
	    else if (raster_type == DCELL_TYPE)
		aspect_f = *((DCELL *) ptr);


	    if (opt7->answer) {

		if (mag_raster_type == CELL_TYPE)
		    length = *((CELL *) mag_ptr);
		else if (mag_raster_type == FCELL_TYPE)
		    length = *((FCELL *) mag_ptr);
		else if (mag_raster_type == DCELL_TYPE)
		    length = *((DCELL *) mag_ptr);

		length *= scale;

		if (Rast_is_null_value(mag_ptr, mag_raster_type)) {
		    G_debug(5, "Invalid arrow length [NULL]. Skipping.");
		    no_arrow = TRUE;
		}
		else if (length <= 0.0) {	/* use fabs() or theta+=180? */
		    G_debug(5, "Illegal arrow length [%.3f]. Skipping.",
			    length);
		    no_arrow = TRUE;
		}
	    }

	    if (no_arrow) {
		ptr = G_incr_void_ptr(ptr, Rast_cell_size(raster_type));
		if (opt7->answer)
		    mag_ptr =
			G_incr_void_ptr(mag_ptr,
					Rast_cell_size(mag_raster_type));
		no_arrow = FALSE;
		continue;
	    }

	    /* treat AGNPS and ANSWERS data like old zero-as-null CELL */
	    /*   TODO: update models */
	    if (map_type == 2 || map_type == 3) {
		if (Rast_is_null_value(ptr, raster_type))
		    aspect_c = 0;
		else
		    aspect_c = (int)(aspect_f + 0.5);
	    }


	    /** Now draw the arrows **/

	    /* case switch for standard GRASS aspect map 
	       measured in degrees counter-clockwise from east */
	    if (map_type == 1) {
		D_use_color(arrow_color);

		if (Rast_is_null_value(ptr, raster_type)) {
		    D_use_color(x_color);
		    draw_x();
		    D_use_color(arrow_color);
		}
		else if (aspect_f >= 0.0 && aspect_f <= 360.0) {
		    if (opt7->answer)
			arrow_mag(aspect_f, length);
		    else
			arrow_360(aspect_f);
		}
		else {
		    D_use_color(unknown_color);
		    unknown_();
		    D_use_color(arrow_color);
		}
	    }


	    /* case switch for AGNPS type aspect map */
	    else if (map_type == 2) {
		D_use_color(arrow_color);
		switch (aspect_c) {
		case 0:
		    D_use_color(x_color);
		    draw_x();
		    D_use_color(arrow_color);
		    break;
		case 1:
		    arrow_n();
		    break;
		case 2:
		    arrow_ne();
		    break;
		case 3:
		    arrow_e();
		    break;
		case 4:
		    arrow_se();
		    break;
		case 5:
		    arrow_s();
		    break;
		case 6:
		    arrow_sw();
		    break;
		case 7:
		    arrow_w();
		    break;
		case 8:
		    arrow_nw();
		    break;
		default:
		    D_use_color(unknown_color);
		    unknown_();
		    D_use_color(arrow_color);
		    break;
		}
	    }


	    /* case switch for ANSWERS type aspect map */
	    else if (map_type == 3) {
		D_use_color(arrow_color);
		if (aspect_c >= 15 && aspect_c <= 360)	/* start at zero? */
		    arrow_360((double)aspect_c);
		else if (aspect_c == 400) {
		    D_use_color(unknown_color);
		    unknown_();
		    D_use_color(arrow_color);
		}
		else {
		    D_use_color(x_color);
		    draw_x();
		    D_use_color(arrow_color);
		}
	    }

	    /* case switch for compass type aspect map
	       measured in degrees clockwise from north */
	    else if (map_type == 4) {
		D_use_color(arrow_color);

		if (Rast_is_null_value(ptr, raster_type)) {
		    D_use_color(x_color);
		    draw_x();
		    D_use_color(arrow_color);
		}
		else if (aspect_f >= 0.0 && aspect_f <= 360.0) {
		    if (opt7->answer)
			arrow_mag(90 - aspect_f, length);
		    else
			arrow_360(90 - aspect_f);
		}
		else {
		    D_use_color(unknown_color);
		    unknown_();
		    D_use_color(arrow_color);
		}
	    }

	    ptr = G_incr_void_ptr(ptr, Rast_cell_size(raster_type));
	    if (opt7->answer)
		mag_ptr =
		    G_incr_void_ptr(mag_ptr, Rast_cell_size(mag_raster_type));
	}
    }

    Rast_close(layer_fd);
    if (opt7->answer)
	Rast_close(mag_fd);

    D_save_command(G_recreate_command());
    D_close_driver();

    exit(EXIT_SUCCESS);
}
Esempio n. 24
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    int infile;
    const char *mapset;
    size_t cell_size;
    int ytile, xtile, y, overlap;
    int *outfiles;
    void *inbuf;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("tiling"));
    module->description =
	_("Splits a raster map into tiles.");

    parm.rastin = G_define_standard_option(G_OPT_R_INPUT);

    parm.rastout = G_define_option();
    parm.rastout->key = "output";
    parm.rastout->type = TYPE_STRING;
    parm.rastout->required = YES;
    parm.rastout->multiple = NO;
    parm.rastout->description = _("Output base name");

    parm.width = G_define_option();
    parm.width->key = "width";
    parm.width->type = TYPE_INTEGER;
    parm.width->required = YES;
    parm.width->multiple = NO;
    parm.width->description = _("Width of tiles (columns)");

    parm.height = G_define_option();
    parm.height->key = "height";
    parm.height->type = TYPE_INTEGER;
    parm.height->required = YES;
    parm.height->multiple = NO;
    parm.height->description = _("Height of tiles (rows)");

    parm.overlap = G_define_option();
    parm.overlap->key = "overlap";
    parm.overlap->type = TYPE_INTEGER;
    parm.overlap->required = NO;
    parm.overlap->multiple = NO;
    parm.overlap->description = _("Overlap of tiles");

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

    G_get_set_window(&src_w);
    overlap = parm.overlap->answer ? atoi(parm.overlap->answer) : 0;

    mapset = G_find_raster2(parm.rastin->answer, "");
    if (mapset == NULL)
        G_fatal_error(_("Raster map <%s> not found"), parm.rastin->answer);

    /* set window to old map */
    Rast_get_cellhd(parm.rastin->answer, "", &src_w);
    dst_w = src_w;
    dst_w.cols = atoi(parm.width->answer);
    dst_w.rows = atoi(parm.height->answer);
    G_adjust_Cell_head(&dst_w, 1, 1);

    xtiles = (src_w.cols + dst_w.cols - 1) / dst_w.cols;
    ytiles = (src_w.rows + dst_w.rows - 1) / dst_w.rows;

    G_debug(1, "X: %d * %d, Y: %d * %d",
	    xtiles, dst_w.cols, ytiles, dst_w.rows);

    src_w.cols = xtiles * dst_w.cols + 2 * overlap;
    src_w.rows = ytiles * dst_w.rows + 2 * overlap;
    src_w.west = src_w.west - overlap * src_w.ew_res;
    src_w.east = src_w.west + (src_w.cols + 2 * overlap) * src_w.ew_res;
    src_w.north = src_w.north + overlap * src_w.ns_res;
    src_w.south = src_w.north - (src_w.rows + 2 * overlap) * src_w.ns_res;

    Rast_set_input_window(&src_w);

    /* set the output region */
    ovl_w = dst_w;
    ovl_w.cols = ovl_w.cols + 2 * overlap;
    ovl_w.rows = ovl_w.rows + 2 * overlap;

    G_adjust_Cell_head(&ovl_w, 1, 1);
    Rast_set_output_window(&ovl_w);

    infile = Rast_open_old(parm.rastin->answer, "");
    map_type = Rast_get_map_type(infile);
    cell_size = Rast_cell_size(map_type);

    inbuf = Rast_allocate_input_buf(map_type);

    outfiles = G_malloc(xtiles * sizeof(int));

    G_debug(1, "X: %d * %d, Y: %d * %d",
	    xtiles, dst_w.cols, ytiles, dst_w.rows);

    G_message(_("Generating %d x %d = %d tiles..."), xtiles, ytiles, xtiles * ytiles);
    for (ytile = 0; ytile < ytiles; ytile++) {
	G_debug(1, "reading y tile: %d", ytile);
	G_percent(ytile, ytiles, 2);
	for (xtile = 0; xtile < xtiles; xtile++) {
	    char name[GNAME_MAX];
	    sprintf(name, "%s-%03d-%03d", parm.rastout->answer, ytile, xtile);
	    outfiles[xtile] = Rast_open_new(name, map_type);
	}
	
	for (y = 0; y < ovl_w.rows; y++) {
	    int row = ytile * dst_w.rows + y;
	    G_debug(1, "reading row: %d", row);
	    Rast_get_row(infile, inbuf, row, map_type);
	    
	    for (xtile = 0; xtile < xtiles; xtile++) {
		int cells = xtile * dst_w.cols;
		void *ptr = G_incr_void_ptr(inbuf, cells * cell_size);
		Rast_put_row(outfiles[xtile], ptr, map_type);
	    }
	}

	for (xtile = 0; xtile < xtiles; xtile++) {
	    Rast_close(outfiles[xtile]);
	    write_support_files(xtile, ytile, overlap);
	}
    }

    Rast_close(infile);

    return EXIT_SUCCESS;
}
Esempio n. 25
0
static int cell_draw( char *name,
                      char *mapset,
                      struct Colors *colors,
                      RASTER_MAP_TYPE data_type,
                      char *format )
{
  int cellfile;
  void *xarray = 0;
  int row;
  int ncols, nrows;
  static unsigned char *red, *grn, *blu, *set;
  int i;
  void *ptr = 0;
  int big_endian;
  long one = 1;
  FILE *fo = 0;
  size_t raster_size;
#ifdef NAN
  double dnul = NAN;
  float fnul = ( float )( NAN );
#else
  double dnul = strtod( "NAN", 0 );
  float fnul = strtof( "NAN", 0 );
  // another possibility would be nan()/nanf() - C99
  // and 0./0. if all fails
#endif

  assert( dnul != dnul );
  assert( fnul != fnul );

  big_endian = !( *( ( char * )( &one ) ) );

  ncols = G_window_cols();
  nrows = G_window_rows();

  /* Make sure map is available */
  if ( ( cellfile = G_open_cell_old( name, mapset ) ) == -1 )
    G_fatal_error( ( "Unable to open raster map <%s>" ), name );

  /* Allocate space for cell buffer */
  xarray = G_allocate_raster_buf( data_type );
  red = G_malloc( ncols );
  grn = G_malloc( ncols );
  blu = G_malloc( ncols );
  set = G_malloc( ncols );

  /* some buggy C libraries require BOTH setmode() and fdopen(bin) */
  // Do not use Q_OS_WIN, we are in C file, no Qt headers
#ifdef WIN32
  if ( _setmode( _fileno( stdout ), _O_BINARY ) == -1 )
    G_fatal_error( "Cannot set stdout mode" );
#endif
  // Unfortunately this is not sufficient on Windows to switch stdout to binary mode
  fo = fdopen( fileno( stdout ), "wb" );

  raster_size = G_raster_size( data_type );
  //fprintf( fo, "%d %d", data_type, raster_size );
  //exit(0);
  /* loop for array rows */
  for ( row = 0; row < nrows; row++ )
  {
    G_get_raster_row( cellfile, xarray, row, data_type );
    ptr = xarray;

    G_lookup_raster_colors( xarray, red, grn, blu, set, ncols, colors,
                            data_type );

    for ( i = 0; i < ncols; i++ )
    {
      unsigned char alpha = 255;
      //G_debug ( 0, "row = %d col = %d", row, i );
      if ( G_is_null_value( ptr, data_type ) )
      {
        alpha = 0;
      }

      if ( strcmp( format, "color" ) == 0 )
      {
        // We need data suitable for QImage 32-bpp
        // the data are stored in QImage as QRgb which is unsigned int.
        // Because it depends on byte order of the platform we have to
        // consider byte order (well, middle endian ignored)
        if ( big_endian )
        {
          // I have never tested this
          fprintf( fo, "%c%c%c%c", alpha, red[i], grn[i], blu[i] );
        }
        else
        {
          fprintf( fo, "%c%c%c%c", blu[i], grn[i], red[i], alpha );
        }
      }
      else
      {
        if ( data_type == CELL_TYPE )
        {
          //G_debug ( 0, "valx = %d", *((CELL *) ptr));
        }
        if ( G_is_null_value( ptr, data_type ) )
        {
          // see comments in QgsGrassRasterProvider::noDataValue()
          if ( data_type == CELL_TYPE )
          {
            //int nul = -2000000000;
            int nul = INT_MIN;
            fwrite( &nul, 4, 1, fo );
          }
          else if ( data_type == DCELL_TYPE )
          {
            //double nul = -1e+300;
            fwrite( &dnul, 8, 1, fo );
          }
          else if ( data_type == FCELL_TYPE )
          {
            //double nul = -1e+30;
            fwrite( &fnul, 4, 1, fo );
          }
        }
        else
        {
          fwrite( ptr, raster_size, 1, fo );
        }
      }
      ptr = G_incr_void_ptr( ptr, raster_size );
    }
  }

  G_close_cell( cellfile );
  fclose( fo );

  return ( 0 );
}
Esempio n. 26
0
int main( int argc, char **argv )
{
  char *name = nullptr;
  struct Option *map;
  struct Cell_head window;

  G_gisinit( argv[0] );

  G_define_module();

  map = G_define_standard_option( G_OPT_R_OUTPUT );

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

  name = map->answer;

#ifdef Q_OS_WIN
  _setmode( _fileno( stdin ), _O_BINARY );
  _setmode( _fileno( stdout ), _O_BINARY );
  //setvbuf( stdin, NULL, _IONBF, BUFSIZ );
  // setting _IONBF on stdout works on windows correctly, data written immediately even without fflush(stdout)
  //setvbuf( stdout, NULL, _IONBF, BUFSIZ );
#endif

  QgsGrassDataFile stdinFile;
  stdinFile.open( stdin );
  QDataStream stdinStream( &stdinFile );

  QFile stdoutFile;
  stdoutFile.open( stdout, QIODevice::WriteOnly | QIODevice::Unbuffered );
  QDataStream stdoutStream( &stdoutFile );

  qint32 proj, zone;
  stdinStream >> proj >> zone;

  QgsRectangle extent;
  qint32 rows, cols;
  stdinStream >> extent >> cols >> rows;
  checkStream( stdinStream );

  QString err = QgsGrass::setRegion( &window, extent, rows, cols );
  if ( !err.isEmpty() )
  {
    G_fatal_error( "Cannot set region: %s", err.toUtf8().constData() );
  }
  window.proj = ( int ) proj;
  window.zone = ( int ) zone;

  G_set_window( &window );

  Qgis::DataType qgis_type;
  qint32 type;
  stdinStream >> type;
  checkStream( stdinStream );
  qgis_type = ( Qgis::DataType )type;

  RASTER_MAP_TYPE grass_type;
  switch ( qgis_type )
  {
    case Qgis::Int32:
      grass_type = CELL_TYPE;
      break;
    case Qgis::Float32:
      grass_type = FCELL_TYPE;
      break;
    case Qgis::Float64:
      grass_type = DCELL_TYPE;
      break;
    default:
      G_fatal_error( "QGIS data type %d not supported", qgis_type );
      return 1;
  }

  cf = Rast_open_new( name, grass_type );
  if ( cf < 0 )
  {
    G_fatal_error( "Unable to create raster map <%s>", name );
    return 1;
  }

  void *buf = Rast_allocate_buf( grass_type );

  int expectedSize = cols * QgsRasterBlock::typeSize( qgis_type );
  bool isCanceled = false;
  QByteArray byteArray;
  for ( int row = 0; row < rows; row++ )
  {
    stdinStream >> isCanceled;
    checkStream( stdinStream );
    if ( isCanceled )
    {
      break;
    }
    double noDataValue;
    stdinStream >> noDataValue;
    stdinStream >> byteArray;
    checkStream( stdinStream );

    if ( byteArray.size() != expectedSize )
    {
      G_fatal_error( "Wrong byte array size, expected %d bytes, got %d, row %d / %d", expectedSize, byteArray.size(), row, rows );
      return 1;
    }

    qint32 *cell = nullptr;
    float *fcell = nullptr;
    double *dcell = nullptr;
    if ( grass_type == CELL_TYPE )
      cell = ( qint32 * ) byteArray.data();
    else if ( grass_type == FCELL_TYPE )
      fcell = ( float * ) byteArray.data();
    else if ( grass_type == DCELL_TYPE )
      dcell = ( double * ) byteArray.data();

    void *ptr = buf;
    for ( int col = 0; col < cols; col++ )
    {
      if ( grass_type == CELL_TYPE )
      {
        if ( ( CELL )cell[col] == ( CELL )noDataValue )
        {
          Rast_set_c_null_value( ( CELL * )ptr, 1 );
        }
        else
        {
          Rast_set_c_value( ptr, ( CELL )( cell[col] ), grass_type );
        }
      }
      else if ( grass_type == FCELL_TYPE )
      {
        if ( ( FCELL )fcell[col] == ( FCELL )noDataValue )
        {
          Rast_set_f_null_value( ( FCELL * )ptr, 1 );
        }
        else
        {
          Rast_set_f_value( ptr, ( FCELL )( fcell[col] ), grass_type );
        }
      }
      else if ( grass_type == DCELL_TYPE )
      {
        if ( ( DCELL )dcell[col] == ( DCELL )noDataValue )
        {
          Rast_set_d_null_value( ( DCELL * )ptr, 1 );
        }
        else
        {
          Rast_set_d_value( ptr, ( DCELL )dcell[col], grass_type );
        }
      }

      ptr = G_incr_void_ptr( ptr, Rast_cell_size( grass_type ) );
    }
    Rast_put_row( cf, buf, grass_type );

#ifndef Q_OS_WIN
    // Because stdin is somewhere buffered on Windows (not clear if in QProcess or by Windows)
    // we cannot in QgsGrassImport wait for this because it hangs. Setting _IONBF on stdin does not help
    // and there is no flush() on QProcess.
    // OTOH, smaller stdin buffer is probably blocking QgsGrassImport so that the import can be canceled immediately.
    stdoutStream << ( bool )true; // row written
    stdoutFile.flush();
#endif
  }

  if ( isCanceled )
  {
    Rast_unopen( cf );
  }
  else
  {
    Rast_close( cf );
    struct History history;
    Rast_short_history( name, "raster", &history );
    Rast_command_history( &history );
    Rast_write_history( name, &history );
  }

  exit( EXIT_SUCCESS );
}
Esempio n. 27
0
int main(int argc, char *argv[])
{
    int out_fd;
    CELL *result, *rp;
    int nrows, ncols;
    int row, col;
    struct GModule *module;
    struct Option *in_opt, *out_opt;
    struct Option *method_opt, *size_opt;
    char *mapset;
    struct Map_info In;
    double radius;
    struct ilist *List;
    struct Cell_head region;
    BOUND_BOX box;
    struct line_pnts *Points;
    struct line_cats *Cats;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("vector, raster, aggregation");
    module->description = "Makes each cell value a "
	"function of the attribute values assigned to the vector points or centroids "
	"around it, and stores new cell values in an output raster map layer.";

    in_opt = G_define_standard_option(G_OPT_V_INPUT);
    out_opt = G_define_standard_option(G_OPT_R_OUTPUT);

    method_opt = G_define_option();
    method_opt->key = "method";
    method_opt->type = TYPE_STRING;
    method_opt->required = YES;
    method_opt->options = "count";
    method_opt->answer = "count";
    method_opt->description = "Neighborhood operation";

    size_opt = G_define_option();
    size_opt->key = "size";
    size_opt->type = TYPE_DOUBLE;
    size_opt->required = YES;
    size_opt->description = "Neighborhood diameter in map units";

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

    radius = atof(size_opt->answer) / 2;

    /* open input vector */
    if ((mapset = G_find_vector2(in_opt->answer, "")) == NULL) {
	G_fatal_error(_("Vector map <%s> not found in the current mapset"),
		      in_opt->answer);
    }

    Vect_set_open_level(2);
    Vect_open_old(&In, in_opt->answer, mapset);

    G_get_set_window(&region);
    nrows = G_window_rows();
    ncols = G_window_cols();

    result = G_allocate_raster_buf(CELL_TYPE);
    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();
    List = Vect_new_list();

    /*open the new cellfile */
    out_fd = G_open_raster_new(out_opt->answer, CELL_TYPE);
    if (out_fd < 0)
	G_fatal_error(_("Unable to create raster map <%s>"), out_opt->answer);

    box.T = PORT_DOUBLE_MAX;
    box.B = -PORT_DOUBLE_MAX;

    for (row = 0; row < nrows; row++) {
	double x, y;

	G_percent(row, nrows, 1);

	y = G_row_to_northing(row + 0.5, &region);
	box.N = y + radius;
	box.S = y - radius;

	G_set_null_value(result, ncols, CELL_TYPE);
	rp = result;

	for (col = 0; col < ncols; col++) {
	    int i, count;
	    CELL value;

	    x = G_col_to_easting(col + 0.5, &region);

	    box.E = x + radius;
	    box.W = x - radius;

	    Vect_select_lines_by_box(&In, &box, GV_POINTS, List);
	    G_debug(3, "  %d lines in box", List->n_values);

	    count = 0;

	    for (i = 0; i < List->n_values; i++) {
		double distance;

		Vect_read_line(&In, Points, Cats, List->value[i]);
		distance =
		    Vect_points_distance(x, y, 0.0, Points->x[0],
					 Points->y[0], 0.0, 0);

		if (distance <= radius) {
		    count++;
		}
	    }

	    if (count > 0) {
		value = count;
		G_set_raster_value_d(rp, value, CELL_TYPE);
	    }
	    rp = G_incr_void_ptr(rp, G_raster_size(CELL_TYPE));
	}

	G_put_raster_row(out_fd, result, CELL_TYPE);
    }
    G_percent(row, nrows, 1);

    Vect_close(&In);
    G_close_cell(out_fd);

    exit(EXIT_SUCCESS);
}
Esempio n. 28
0
/* ************************************************************************* */
void rast3d_cross_section(void *map,RASTER3D_Region region, int elevfd, int outfd)
{
    int col, row;
    int rows, cols, depths, typeIntern;
    FCELL *fcell = NULL;
    DCELL *dcell = NULL;
    void *elevrast;
    void *ptr;
    int intvalue;
    float fvalue;
    double dvalue;
    double elevation = 0;
    double north, east;
    struct Cell_head window;
 
    Rast_get_window(&window);
    
    rows = region.rows;
    cols = region.cols;
    depths = region.depths;
    
    /*Typ of the RASTER3D Tile */
    typeIntern = Rast3d_tile_type_map(map);

    /*Allocate mem for the output maps row */
    if (typeIntern == FCELL_TYPE)
        fcell = Rast_allocate_f_buf();
    else if (typeIntern == DCELL_TYPE)
        dcell = Rast_allocate_d_buf();

    /*Mem for the input map row */
    elevrast = Rast_allocate_buf(globalElevMapType);

    for (row = 0; row < rows; row++) {
        G_percent(row, rows - 1, 10);

        /*Read the input map row */
        Rast_get_row(elevfd, elevrast, row, globalElevMapType);

        for (col = 0, ptr = elevrast; col < cols; col++, ptr =
            G_incr_void_ptr(ptr, Rast_cell_size(globalElevMapType))) {

            if (Rast_is_null_value(ptr, globalElevMapType)) {
                if (typeIntern == FCELL_TYPE)
                    Rast_set_null_value(&fcell[col], 1, FCELL_TYPE);
                else if (typeIntern == DCELL_TYPE)
                    Rast_set_null_value(&dcell[col], 1, DCELL_TYPE);
                continue;
            }

            /*Read the elevation value */
            if (globalElevMapType == CELL_TYPE) {
                intvalue = *(CELL *) ptr;
                elevation = intvalue;
            } else if (globalElevMapType == FCELL_TYPE) {
                fvalue = *(FCELL *) ptr;
                elevation = fvalue;
            } else if (globalElevMapType == DCELL_TYPE) {
                dvalue = *(DCELL *) ptr;
                elevation = dvalue;
            }

            /* Compute the coordinates */
            north = Rast_row_to_northing((double)row + 0.5, &window);
            east = Rast_col_to_easting((double)col + 0.5, &window);

            /* Get the voxel value */
            if (typeIntern == FCELL_TYPE)
                Rast3d_get_region_value(map, north, east, elevation, &fcell[col], FCELL_TYPE);

            if (typeIntern == DCELL_TYPE)
                Rast3d_get_region_value(map, north, east, elevation, &dcell[col], DCELL_TYPE);
        }

        /*Write the data to the output map */
        if (typeIntern == FCELL_TYPE)
            Rast_put_f_row(outfd, fcell);

        if (typeIntern == DCELL_TYPE)
            Rast_put_d_row(outfd, dcell);
    }
    G_debug(3, "\nDone\n");

    /*Free the mem */
    if (elevrast)
        G_free(elevrast);
    if (dcell)
        G_free(dcell);
    if (fcell)
        G_free(fcell);
}
Esempio n. 29
0
int main(int argc, char *argv[])
{

    int i, row, col;		/* counters */
    unsigned long filesize;

    int endianness;		/* 0=little, 1=big */
    int data_format;		/* 0=double  1=float  2=32bit signed int  5=8bit unsigned int (ie text) */
    int data_type;		/* 0=numbers  1=text */
    int format_block;		/* combo of endianness, 0, data_format, and type */
    int realflag = 0;		/* 0=only real values used */

    /* should type be specifically uint32 ??? */

    char array_name[32];	/* variable names must start with a letter (case 
				   sensitive) followed by letters, numbers, or 
				   underscores. 31 chars max. */
    int name_len;
    int mrows, ncols;		/* text/data/map array dimensions */

    int val_i;			/* for misc use */
    float val_f;		/* for misc use */
    double val_d;		/* for misc use */

    char *infile, *outfile, *maptitle, *basename;
    struct Cell_head region;
    void *raster, *ptr;
    RASTER_MAP_TYPE map_type;

    struct Option *inputfile, *outputfile;
    struct GModule *module;

    int fd;
    FILE *fp1;


    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("export"));
    module->description = _("Exports a GRASS raster to a binary MAT-File.");

    /* Define the different options */

    inputfile = G_define_standard_option(G_OPT_R_INPUT);

    outputfile = G_define_option();
    outputfile->key = "output";
    outputfile->type = TYPE_STRING;
    outputfile->required = YES;
    outputfile->gisprompt = "new_file,file,output";
    outputfile->description = _("Name for the output binary MAT-File");

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

    infile = inputfile->answer;
    basename = G_store(outputfile->answer);
    G_basename(basename, "mat");
    outfile = G_malloc(strlen(basename) + 5);
    sprintf(outfile, "%s.mat", basename);

    fd = Rast_open_old(infile, "");

    map_type = Rast_get_map_type(fd);

    /* open bin file for writing */
    fp1 = fopen(outfile, "wb");
    if (NULL == fp1)
	G_fatal_error(_("Unable to open output file <%s>"), outfile);


    /* Check Endian State of Host Computer */
    if (G_is_little_endian())
	endianness = 0;		/* ie little endian */
    else
	endianness = 1;		/* ie big endian */
    G_debug(1, "Machine is %s endian.\n", endianness ? "big" : "little");

    G_get_window(&region);


    /********** Write map **********/

    /** write text element (map name) **/
    strncpy(array_name, "map_name", 31);
    mrows = 1;
    ncols = strlen(infile);
    data_format = 5;		/* 0=double  1=float  2=32bit signed int  5=8bit unsigned int(text) */
    data_type = 1;		/* 0=numbers  1=text */

    G_verbose_message(_("Exporting <%s>"), infile);

    /* 4 byte data format */
    format_block = endianness * 1000 + data_format * 10 + data_type;
    fwrite(&format_block, sizeof(int), 1, fp1);
    /* fprintf(stderr, "name data format is [%04ld]\n", format_block); */

    /* 4 byte number of rows & columns */
    fwrite(&mrows, sizeof(int), 1, fp1);
    fwrite(&ncols, sizeof(int), 1, fp1);

    /* 4 byte real/imag flag   0=real vals only */
    fwrite(&realflag, sizeof(int), 1, fp1);

    /* length of array_name+1 */
    name_len = strlen(array_name) + 1;
    fwrite(&name_len, sizeof(int), 1, fp1);

    /* array name */
    fprintf(fp1, "%s%c", array_name, '\0');

    /* array data */
    fprintf(fp1, "%s", infile);


    /********** Write title (if there is one) **********/
    maptitle = Rast_get_cell_title(infile, "");
    if (strlen(maptitle) >= 1) {

	/** write text element (map title) **/
	strncpy(array_name, "map_title", 31);
	mrows = 1;
	ncols = strlen(maptitle);
	data_format = 5;	/* 0=double  1=float  2=32bit signed int  5=8bit unsigned int(text) */
	data_type = 1;		/* 0=numbers  1=text */

	/* 4 byte data format */
	format_block = endianness * 1000 + data_format * 10 + data_type;
	fwrite(&format_block, sizeof(int), 1, fp1);

	/* 4 byte number of rows & columns */
	fwrite(&mrows, sizeof(int), 1, fp1);
	fwrite(&ncols, sizeof(int), 1, fp1);

	/* 4 byte real/imag flag   0=real vals only */
	fwrite(&realflag, sizeof(int), 1, fp1);

	/* length of array_name+1 */
	name_len = strlen(array_name) + 1;
	fwrite(&name_len, sizeof(int), 1, fp1);

	/* array name */
	fprintf(fp1, "%s%c", array_name, '\0');

	/* array data */
	fprintf(fp1, "%s", maptitle);
    }

    /***** Write bounds *****/
    G_verbose_message("");
    G_verbose_message(_("Using the Current Region settings:"));
    G_verbose_message(_("northern edge=%f"), region.north);
    G_verbose_message(_("southern edge=%f"), region.south);
    G_verbose_message(_("eastern edge=%f"), region.east);
    G_verbose_message(_("western edge=%f"), region.west);
    G_verbose_message(_("nsres=%f"), region.ns_res);
    G_verbose_message(_("ewres=%f"), region.ew_res);
    G_verbose_message(_("rows=%d"), region.rows);
    G_verbose_message(_("cols=%d"), region.cols);
    G_verbose_message("");

    for (i = 0; i < 4; i++) {
	switch (i) {
	case 0:
	    strncpy(array_name, "map_northern_edge", 31);
	    val_d = region.north;
	    break;
	case 1:
	    strncpy(array_name, "map_southern_edge", 31);
	    val_d = region.south;
	    break;
	case 2:
	    strncpy(array_name, "map_eastern_edge", 31);
	    val_d = region.east;
	    break;
	case 3:
	    strncpy(array_name, "map_western_edge", 31);
	    val_d = region.west;
	    break;
	default:
	    fclose(fp1);
	    G_fatal_error("please contact development team");
	    break;
	}

	/** write data element **/
	data_format = 0;	/* 0=double  1=float  2=32bit signed int  5=8bit unsigned int(text) */
	data_type = 0;		/* 0=numbers  1=text */
	mrows = 1;
	ncols = 1;

	/* 4 byte data format */
	format_block = endianness * 1000 + data_format * 10 + data_type;
	fwrite(&format_block, sizeof(int), 1, fp1);
	/* fprintf(stderr, "bounds data format is [%04ld]\n", format_block); */

	/* 4 byte number of rows , 4 byte number of colums */
	fwrite(&mrows, sizeof(int), 1, fp1);
	fwrite(&ncols, sizeof(int), 1, fp1);

	/* 4 byte real/imag flag   0=only real */
	fwrite(&realflag, sizeof(int), 1, fp1);

	/* length of array_name+1 */
	name_len = strlen(array_name) + 1;
	fwrite(&name_len, sizeof(int), 1, fp1);

	/* array name */
	fprintf(fp1, "%s%c", array_name, '\0');

	/* write array data, by increasing column */
	fwrite(&val_d, sizeof(double), 1, fp1);

	/** end of data element **/
    }



    /***** Write map data *****/
    strncpy(array_name, "map_data", 31);

    switch (map_type) {		/* data_format: 0=double  1=float  2=32bit signed int  5=8bit unsigned int (ie text) */

    case CELL_TYPE:
	data_format = 2;
	G_verbose_message(_("Exporting raster as integer values"));
	break;

    case FCELL_TYPE:
	data_format = 1;
	G_verbose_message(_("Exporting raster as floating point values"));
	break;

    case DCELL_TYPE:
	data_format = 0;
	G_verbose_message(_("Exporting raster as double FP values"));
	break;

    default:
	fclose(fp1);
	G_fatal_error("Please contact development team");
	break;
    }

    data_type = 0;		/* 0=numbers  1=text */

    mrows = region.rows;
    ncols = region.cols;

    /* 4 byte data format */
    format_block = (endianness * 1000) + (data_format * 10) + data_type;
    fwrite(&format_block, sizeof(int), 1, fp1);

    G_debug(3, "map data format is [%04d]\n", format_block);

    /* 4 byte number of rows & columns */
    fwrite(&mrows, sizeof(int), 1, fp1);
    fwrite(&ncols, sizeof(int), 1, fp1);

    /* 4 byte real/imag flag   0=only real */
    fwrite(&realflag, sizeof(int), 1, fp1);

    /* length of array_name+1 */
    name_len = strlen(array_name) + 1;
    fwrite(&name_len, sizeof(int), 1, fp1);

    /* array name */
    fprintf(fp1, "%s%c", array_name, '\0');

    /* data array, by increasing column */
    raster =
	G_calloc((Rast_window_rows() + 1) * (Rast_window_cols() + 1),
		 Rast_cell_size(map_type));

    G_debug(1, "mem alloc is %d bytes\n",	/* I think _cols()+1 is unneeded? */
	    Rast_cell_size(map_type) * (Rast_window_rows() +
				       1) * (Rast_window_cols() + 1));

    G_verbose_message(_("Reading in map ... "));

    /* load entire map into memory */
    for (row = 0, ptr = raster; row < mrows; row++,
	 ptr =
	 G_incr_void_ptr(ptr,
			 (Rast_window_cols() + 1) * Rast_cell_size(map_type))) {
	Rast_get_row(fd, ptr, row, map_type);
	G_percent(row, mrows, 2);
    }
    G_percent(row, mrows, 2);	/* finish it off */


    G_verbose_message(_("Writing out map..."));

    /* then write it to disk */
    /* NoGood: fwrite(raster, Rast_cell_size(map_type), mrows*ncols, fp1); */
    for (col = 0; col < ncols; col++) {
	for (row = 0; row < mrows; row++) {

	    ptr = raster;
	    ptr =
		G_incr_void_ptr(ptr,
				(col +
				 row * (ncols +
					1)) * Rast_cell_size(map_type));

	    if (!Rast_is_null_value(ptr, map_type)) {
		if (map_type == CELL_TYPE) {
		    val_i = *((CELL *) ptr);
		    fwrite(&val_i, sizeof(int), 1, fp1);
		}
		else if (map_type == FCELL_TYPE) {
		    val_f = *((FCELL *) ptr);
		    fwrite(&val_f, sizeof(float), 1, fp1);
		}
		else if (map_type == DCELL_TYPE) {
		    val_d = *((DCELL *) ptr);
		    fwrite(&val_d, sizeof(double), 1, fp1);
		}
	    }
	    else {		/* ie if NULL cell -> write IEEE NaN value */
		if (map_type == CELL_TYPE) {
		    val_i = *((CELL *) ptr);	/* int has no NaN value, so use whatever GRASS uses */
		    fwrite(&val_i, sizeof(int), 1, fp1);
		}
		else if (map_type == FCELL_TYPE) {
		    if (endianness)	/* ie big */
			fprintf(fp1, "%c%c%c%c", 0xff, 0xf8, 0, 0);
		    else	/* ie little */
			fprintf(fp1, "%c%c%c%c", 0, 0, 0xf8, 0xff);
		}
		else if (map_type == DCELL_TYPE) {
		    if (endianness)
			fprintf(fp1, "%c%c%c%c%c%c%c%c", 0xff, 0xf8, 0, 0, 0,
				0, 0, 0);
		    else
			fprintf(fp1, "%c%c%c%c%c%c%c%c", 0, 0, 0, 0, 0, 0,
				0xf8, 0xff);
		}
	    }
	}
	G_percent(col, ncols, 2);
    }
    G_percent(col, ncols, 2);	/* finish it off */

    /*** end of data element ***/


    /* done! */
    filesize = G_ftell(fp1);
    fclose(fp1);

    G_verbose_message(_("%ld bytes written to '%s'"), filesize, outfile);

    G_done_msg("");

    G_free(basename);
    G_free(outfile);

    exit(EXIT_SUCCESS);
}
Esempio n. 30
0
static int cell_draw( char *name,
                      char *mapset,
                      struct Colors *colors,
                      RASTER_MAP_TYPE data_type,
                      char *format )
{
  int cellfile;
  void *xarray;
  int row;
  int ncols, nrows;
  static unsigned char *red, *grn, *blu, *set;
  int i;
  void *ptr;
  int big_endian;
  long one = 1;
  FILE *fo;
  int raster_size;

  big_endian = !( *(( char * )( &one ) ) );

  ncols = G_window_cols();
  nrows = G_window_rows();

  /* Make sure map is available */
  if (( cellfile = G_open_cell_old( name, mapset ) ) == -1 )
    G_fatal_error(( "Unable to open raster map <%s>" ), name );

  /* Allocate space for cell buffer */
  xarray = G_allocate_raster_buf( data_type );
  red = G_malloc( ncols );
  grn = G_malloc( ncols );
  blu = G_malloc( ncols );
  set = G_malloc( ncols );

  /* some buggy C libraries require BOTH setmode() and fdopen(bin) */
#ifdef WIN32
  if ( _setmode( _fileno( stdout ), _O_BINARY ) == -1 )
    G_fatal_error( "Cannot set stdout mode" );
#endif
  // Unfortunately this is not sufficient on Windows to switch stdout to binary mode
  fo = fdopen( fileno( stdout ), "wb" );

  raster_size = G_raster_size( data_type );
  //fprintf( fo, "%d %d", data_type, raster_size );
  //exit(0);
  /* loop for array rows */
  for ( row = 0; row < nrows; row++ )
  {
    G_get_raster_row( cellfile, xarray, row, data_type );
    ptr = xarray;

    G_lookup_raster_colors( xarray, red, grn, blu, set, ncols, colors,
                            data_type );

    for ( i = 0; i < ncols; i++ )
    {
      unsigned char alpha = 255;
      //G_debug ( 0, "row = %d col = %d", row, i );
      if ( G_is_null_value( ptr, data_type ) )
      {
        alpha = 0;
      }

      if ( strcmp( format, "color" ) == 0 )
      {
        // We need data suitable for QImage 32-bpp
        // the data are stored in QImage as QRgb which is unsigned int.
        // Because it depends on byte order of the platform we have to
        // consider byte order (well, middle endian ignored)
        if ( big_endian )
        {
          // I have never tested this
          fprintf( fo, "%c%c%c%c", alpha, red[i], grn[i], blu[i] );
        }
        else
        {
          fprintf( fo, "%c%c%c%c", blu[i], grn[i], red[i], alpha );
        }
      }
      else
      {
        if ( data_type == CELL_TYPE )
        {
          //G_debug ( 0, "valx = %d", *((CELL *) ptr));
        }
        if ( G_is_null_value( ptr, data_type ) )
        {
          if ( data_type == CELL_TYPE )
          {
            int nul = -2147483647;
            fwrite( &nul , 4, 1, fo );
          }
          else if ( data_type == DCELL_TYPE )
          {
            double nul = 2.2250738585072014e-308;
            fwrite( &nul , 8, 1, fo );
          }
          else if ( data_type == FCELL_TYPE )
          {
            double nul = 1.17549435e-38F;
            fwrite( &nul , 4, 1, fo );
          }
        }
        else
        {
          fwrite( ptr, raster_size, 1, fo );
        }
      }
      ptr = G_incr_void_ptr( ptr, raster_size );
    }
  }

  G_close_cell( cellfile );
  return ( 0 );
}