Ejemplo n.º 1
0
int main(int argc, char *argv[])
{
    int i;
    int print_flag = 0;
    int flat_flag; 
    int set_flag;
    double x;
    int ival;
    int row_flag = 0, col_flag = 0;
    struct Cell_head window, temp_window;
    const char *value;
    const char *name;
    const char *mapset;
    char **rast_ptr, **vect_ptr;

    struct GModule *module;
    struct
    {
	struct Flag
	    *update, *print, *gprint, *flprint, *lprint, *eprint, *nangle,
	    *center, *res_set, *dist_res, *dflt, *z, *savedefault,
	    *bbox, *gmt_style, *wms_style;
    } flag;
    struct
    {
	struct Option
	    *north, *south, *east, *west, *top, *bottom,
	    *res, *nsres, *ewres, *res3, *tbres, *rows, *cols,
	    *save, *region, *raster, *raster3d, *align,
	    *zoom, *vect;
    } parm;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("general"));
    G_add_keyword(_("settings"));
    module->description =
	_("Manages the boundary definitions for the " "geographic region.");

    /* flags */

    flag.dflt = G_define_flag();
    flag.dflt->key = 'd';
    flag.dflt->description = _("Set from default region");
    flag.dflt->guisection = _("Existing");

    flag.savedefault = G_define_flag();
    flag.savedefault->key = 's';
    flag.savedefault->label = _("Save as default region");
    flag.savedefault->description = _("Only possible from the PERMANENT mapset");
    flag.savedefault->guisection = _("Existing");

    flag.print = G_define_flag();
    flag.print->key = 'p';
    flag.print->description = _("Print the current region");
    flag.print->guisection = _("Print");

    flag.lprint = G_define_flag();
    flag.lprint->key = 'l';
    flag.lprint->description = _("Print the current region in lat/long "
				 "using the current ellipsoid/datum");
    flag.lprint->guisection = _("Print");

    flag.eprint = G_define_flag();
    flag.eprint->key = 'e';
    flag.eprint->description = _("Print the current region extent");
    flag.eprint->guisection = _("Print");

    flag.center = G_define_flag();
    flag.center->key = 'c';
    flag.center->description =
	_("Print the current region map center coordinates");
    flag.center->guisection = _("Print");

    flag.gmt_style = G_define_flag();
    flag.gmt_style->key = 't';
    flag.gmt_style->description =
	_("Print the current region in GMT style");
    flag.gmt_style->guisection = _("Print");

    flag.wms_style = G_define_flag();
    flag.wms_style->key = 'w';
    flag.wms_style->description =
	_("Print the current region in WMS style");
    flag.wms_style->guisection = _("Print");

    flag.dist_res = G_define_flag();
    flag.dist_res->key = 'm';
    flag.dist_res->description =
	_("Print region resolution in meters (geodesic)");
    flag.dist_res->guisection = _("Print");

    flag.nangle = G_define_flag();
    flag.nangle->key = 'n';
    flag.nangle->label = _("Print the convergence angle (degrees CCW)");
    flag.nangle->description =
	_("The difference between the projection's grid north and true north, "
	  "measured at the center coordinates of the current region.");
    flag.nangle->guisection = _("Print");

    flag.z = G_define_flag();
    flag.z->key = '3';
    flag.z->description = _("Print also 3D settings");
    flag.z->guisection = _("Print");

    flag.bbox = G_define_flag();
    flag.bbox->key = 'b';
    flag.bbox->description =
	_("Print the maximum bounding box in lat/long on WGS84");
    flag.bbox->guisection = _("Print");

    flag.gprint = G_define_flag();
    flag.gprint->key = 'g';
    flag.gprint->description = _("Print in shell script style");
    flag.gprint->guisection = _("Print");

    flag.flprint = G_define_flag();
    flag.flprint->key = 'f';
    flag.flprint->description = _("Print in shell script style, but in one line (flat)");
    flag.flprint->guisection = _("Print");

    flag.res_set = G_define_flag();
    flag.res_set->key = 'a';
    flag.res_set->description =
	_("Align region to resolution (default = align to bounds, "
	  "works only for 2D resolution)");
    flag.res_set->guisection = _("Bounds");

    flag.update = G_define_flag();
    flag.update->key = 'u';
    flag.update->description = _("Do not update the current region");
    flag.update->guisection = _("Effects");

    /* parameters */

    parm.region = G_define_standard_option(G_OPT_M_REGION);
    parm.region->description = _("Set current region from named region");
    parm.region->guisection = _("Existing");

    parm.raster = G_define_standard_option(G_OPT_R_MAP);
    parm.raster->key = "raster";
    parm.raster->required = NO;
    parm.raster->multiple = YES;
    parm.raster->description = _("Set region to match raster map(s)");
    parm.raster->guisection = _("Existing");

    parm.raster3d = G_define_standard_option(G_OPT_R3_MAP);
    parm.raster3d->key = "raster_3d";
    parm.raster3d->required = NO;
    parm.raster3d->multiple = NO;
    parm.raster3d->description =
	_("Set region to match 3D raster map(s) (both 2D and 3D "
	  "values)");
    parm.raster3d->guisection = _("Existing");

    parm.vect = G_define_standard_option(G_OPT_V_MAP);
    parm.vect->key = "vector";
    parm.vect->required = NO;
    parm.vect->multiple = YES;
    parm.vect->label = _("Set region to match vector map(s)");
    parm.vect->description = NULL;
    parm.vect->guisection = _("Existing");

    parm.north = G_define_option();
    parm.north->key = "n";
    parm.north->key_desc = "value";
    parm.north->required = NO;
    parm.north->multiple = NO;
    parm.north->type = TYPE_STRING;
    parm.north->description = _("Value for the northern edge");
    parm.north->guisection = _("Bounds");

    parm.south = G_define_option();
    parm.south->key = "s";
    parm.south->key_desc = "value";
    parm.south->required = NO;
    parm.south->multiple = NO;
    parm.south->type = TYPE_STRING;
    parm.south->description = _("Value for the southern edge");
    parm.south->guisection = _("Bounds");

    parm.east = G_define_option();
    parm.east->key = "e";
    parm.east->key_desc = "value";
    parm.east->required = NO;
    parm.east->multiple = NO;
    parm.east->type = TYPE_STRING;
    parm.east->description = _("Value for the eastern edge");
    parm.east->guisection = _("Bounds");

    parm.west = G_define_option();
    parm.west->key = "w";
    parm.west->key_desc = "value";
    parm.west->required = NO;
    parm.west->multiple = NO;
    parm.west->type = TYPE_STRING;
    parm.west->description = _("Value for the western edge");
    parm.west->guisection = _("Bounds");

    parm.top = G_define_option();
    parm.top->key = "t";
    parm.top->key_desc = "value";
    parm.top->required = NO;
    parm.top->multiple = NO;
    parm.top->type = TYPE_STRING;
    parm.top->description = _("Value for the top edge");
    parm.top->guisection = _("Bounds");

    parm.bottom = G_define_option();
    parm.bottom->key = "b";
    parm.bottom->key_desc = "value";
    parm.bottom->required = NO;
    parm.bottom->multiple = NO;
    parm.bottom->type = TYPE_STRING;
    parm.bottom->description = _("Value for the bottom edge");
    parm.bottom->guisection = _("Bounds");

    parm.rows = G_define_option();
    parm.rows->key = "rows";
    parm.rows->key_desc = "value";
    parm.rows->required = NO;
    parm.rows->multiple = NO;
    parm.rows->type = TYPE_INTEGER;
    parm.rows->description = _("Number of rows in the new region");
    parm.rows->guisection = _("Resolution");

    parm.cols = G_define_option();
    parm.cols->key = "cols";
    parm.cols->key_desc = "value";
    parm.cols->required = NO;
    parm.cols->multiple = NO;
    parm.cols->type = TYPE_INTEGER;
    parm.cols->description = _("Number of columns in the new region");
    parm.cols->guisection = _("Resolution");

    parm.res = G_define_option();
    parm.res->key = "res";
    parm.res->key_desc = "value";
    parm.res->required = NO;
    parm.res->multiple = NO;
    parm.res->type = TYPE_STRING;
    parm.res->description =
	_("2D grid resolution (north-south and east-west)");
    parm.res->guisection = _("Resolution");

    parm.res3 = G_define_option();
    parm.res3->key = "res3";
    parm.res3->key_desc = "value";
    parm.res3->required = NO;
    parm.res3->multiple = NO;
    parm.res3->type = TYPE_STRING;
    parm.res3->description =
	_("3D grid resolution (north-south, east-west and top-bottom)");
    parm.res3->guisection = _("Resolution");

    parm.nsres = G_define_option();
    parm.nsres->key = "nsres";
    parm.nsres->key_desc = "value";
    parm.nsres->required = NO;
    parm.nsres->multiple = NO;
    parm.nsres->type = TYPE_STRING;
    parm.nsres->description = _("North-south 2D grid resolution");
    parm.nsres->guisection = _("Resolution");

    parm.ewres = G_define_option();
    parm.ewres->key = "ewres";
    parm.ewres->key_desc = "value";
    parm.ewres->required = NO;
    parm.ewres->multiple = NO;
    parm.ewres->type = TYPE_STRING;
    parm.ewres->description = _("East-west 2D grid resolution");
    parm.ewres->guisection = _("Resolution");

    parm.tbres = G_define_option();
    parm.tbres->key = "tbres";
    parm.tbres->key_desc = "value";
    parm.tbres->required = NO;
    parm.tbres->multiple = NO;
    parm.tbres->type = TYPE_STRING;
    parm.tbres->description = _("Top-bottom 3D grid resolution");
    parm.tbres->guisection = _("Resolution");

    parm.zoom = G_define_option();
    parm.zoom->key = "zoom";
    parm.zoom->key_desc = "name";
    parm.zoom->required = NO;
    parm.zoom->multiple = NO;
    parm.zoom->type = TYPE_STRING;
    parm.zoom->description =
	_("Shrink region until it meets non-NULL data from this raster map");
    parm.zoom->gisprompt = "old,cell,raster";
    parm.zoom->guisection = _("Bounds");

    parm.align = G_define_option();
    parm.align->key = "align";
    parm.align->key_desc = "name";
    parm.align->required = NO;
    parm.align->multiple = NO;
    parm.align->type = TYPE_STRING;
    parm.align->description =
	_("Adjust region cells to cleanly align with this raster map");
    parm.align->gisprompt = "old,cell,raster";
    parm.align->guisection = _("Bounds");

    parm.save = G_define_option();
    parm.save->key = "save";
    parm.save->key_desc = "name";
    parm.save->required = NO;
    parm.save->multiple = NO;
    parm.save->type = TYPE_STRING;
    parm.save->description =
	_("Save current region settings in named region file");
    parm.save->gisprompt = "new,windows,region";
    parm.save->guisection = _("Effects");

    G_option_required(flag.dflt, flag.savedefault, flag.print, flag.lprint,
                      flag.eprint, flag.center, flag.gmt_style, flag.wms_style,
                      flag.dist_res, flag.nangle, flag. z, flag.bbox, flag.gprint,
                      flag.res_set, flag.update, parm.region, parm.raster,
                      parm.raster3d, parm.vect, parm.north, parm.south, parm.east,
                      parm.west, parm.top, parm.bottom, parm.rows, parm.cols,
                      parm.res, parm.res3, parm.nsres, parm.ewres, parm.tbres,
                      parm.zoom, parm.align, parm.save, NULL);

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

    G_get_default_window(&window);

    set_flag = !flag.update->answer;
    flat_flag = flag.flprint->answer;

    if (flag.print->answer)
	print_flag |= PRINT_REG;

    if (flag.gprint->answer)
	print_flag |= PRINT_SH;

    if (flag.lprint->answer)
	print_flag |= PRINT_LL;

    if (flag.eprint->answer)
	print_flag |= PRINT_EXTENT;

    if (flag.center->answer)
	print_flag |= PRINT_CENTER;

    if (flag.gmt_style->answer)
	print_flag |= PRINT_GMT;

    if (flag.wms_style->answer)
	print_flag |= PRINT_WMS;

    if (flag.nangle->answer)
	print_flag |= PRINT_NANGLE;

    if (flag.dist_res->answer)
	print_flag |= PRINT_METERS;

    if (flag.z->answer)
	print_flag |= PRINT_3D;

    if (flag.bbox->answer)
	print_flag |= PRINT_MBBOX;

    if (print_flag == PRINT_METERS)
	print_flag |= PRINT_SH;

    if (print_flag == PRINT_SH ||
	print_flag & PRINT_3D || print_flag == PRINT_METERS + PRINT_SH) {
	print_flag |= PRINT_REG;
    }

    if (!flag.dflt->answer)
	G_get_window(&window);

    /* region= */
    if ((name = parm.region->answer)) {
	mapset = G_find_file2("windows", name, "");
	if (!mapset)
	    G_fatal_error(_("Region <%s> not found"), name);
	G_get_element_window(&window, "windows", name, mapset);
    }

    /* raster= */
    if (parm.raster->answer) {
	int first = 0;

	rast_ptr = parm.raster->answers;
	for (; *rast_ptr != NULL; rast_ptr++) {
	    char rast_name[GNAME_MAX];

	    strcpy(rast_name, *rast_ptr);
	    mapset = G_find_raster2(rast_name, "");
	    if (!mapset)
		G_fatal_error(_("Raster map <%s> not found"), rast_name);
	    Rast_get_cellhd(rast_name, mapset, &temp_window);
	    if (!first) {
		window = temp_window;
		first = 1;
	    }
	    else {
		window.north = (window.north > temp_window.north) ?
		    window.north : temp_window.north;
		window.south = (window.south < temp_window.south) ?
		    window.south : temp_window.south;
		window.east = (window.east > temp_window.east) ?
		    window.east : temp_window.east;
		window.west = (window.west < temp_window.west) ?
		    window.west : temp_window.west;
	    }
	}
	G_adjust_Cell_head3(&window, 0, 0, 0);
    }


    /* raster3d= */
    if ((name = parm.raster3d->answer)) {
	RASTER3D_Region win;

	if ((mapset = G_find_raster3d(name, "")) == NULL)
	    G_fatal_error(_("3D raster map <%s> not found"), name);

	if (Rast3d_read_region_map(name, mapset, &win) < 0)
	    G_fatal_error(_("Unable to read header of 3D raster map <%s@%s>"),
			  name, mapset);

	Rast3d_region_to_cell_head(&win, &window);
    }

    /* vector= */
    if (parm.vect->answer) {
	int first = 0;

	vect_ptr = parm.vect->answers;
	for (; *vect_ptr != NULL; vect_ptr++) {
	    struct Map_info Map;
	    struct bound_box box;
	    char vect_name[GNAME_MAX];
	    struct Cell_head map_window;

	    strcpy(vect_name, *vect_ptr);
	    mapset = G_find_vector2(vect_name, "");
	    if (!mapset)
		G_fatal_error(_("Vector map <%s> not found"), vect_name);

	    temp_window = window;

	    Vect_set_open_level(2);
	    if (2 > Vect_open_old_head(&Map, vect_name, mapset))
		G_fatal_error(_("Unable to open vector map <%s> on topological level"),
			      vect_name);
            
	    Vect_get_map_box(&Map, &box);
	    map_window = window;
	    map_window.north = box.N;
	    map_window.south = box.S;
	    map_window.west = box.W;
	    map_window.east = box.E;
	    map_window.top = box.T;
	    map_window.bottom = box.B;

	    if (!first) {
		window = map_window;
		first = 1;
	    }
	    else {
		window.north = (window.north > map_window.north) ?
		    window.north : map_window.north;
		window.south = (window.south < map_window.south) ?
		    window.south : map_window.south;
		window.east = (window.east > map_window.east) ?
		    window.east : map_window.east;
		window.west = (window.west < map_window.west) ?
		    window.west : map_window.west;
		if (map_window.top > window.top)
		    window.top = map_window.top;
		if (map_window.bottom < window.bottom)
		    window.bottom = map_window.bottom;
	    }

	    if (window.north == window.south) {
		window.north = window.north + 0.5 * temp_window.ns_res;
		window.south = window.south - 0.5 * temp_window.ns_res;
	    }
	    if (window.east == window.west) {
		window.west = window.west - 0.5 * temp_window.ew_res;
		window.east = window.east + 0.5 * temp_window.ew_res;
	    }
	    if (window.top == window.bottom) {
		window.bottom = (window.bottom - 0.5 * temp_window.tb_res);
		window.top = (window.top + 0.5 * temp_window.tb_res);
	    }

	    if (flag.res_set->answer)
		Rast_align_window(&window, &temp_window);

	    Vect_close(&Map);
	}
    }

    /* n= */
    if ((value = parm.north->answer)) {
	if ((i = nsew(value, "n+", "n-", "s+"))) {
	    if (!G_scan_resolution(value + 2, &x, window.proj))
		die(parm.north);
	    switch (i) {
	    case 1:
		window.north += x;
		break;
	    case 2:
		window.north -= x;
		break;
	    case 3:
		window.north = window.south + x;
		break;
	    }
	}
	else if (G_scan_northing(value, &x, window.proj))
	    window.north = x;
	else
	    die(parm.north);
    }

    /* s= */
    if ((value = parm.south->answer)) {
	if ((i = nsew(value, "s+", "s-", "n-"))) {
	    if (!G_scan_resolution(value + 2, &x, window.proj))
		die(parm.south);
	    switch (i) {
	    case 1:
		window.south += x;
		break;
	    case 2:
		window.south -= x;
		break;
	    case 3:
		window.south = window.north - x;
		break;
	    }
	}
	else if (G_scan_northing(value, &x, window.proj))
	    window.south = x;
	else
	    die(parm.south);
    }

    /* e= */
    if ((value = parm.east->answer)) {
	if ((i = nsew(value, "e+", "e-", "w+"))) {
	    if (!G_scan_resolution(value + 2, &x, window.proj))
		die(parm.east);
	    switch (i) {
	    case 1:
		window.east += x;
		break;
	    case 2:
		window.east -= x;
		break;
	    case 3:
		window.east = window.west + x;
		break;
	    }
	}
	else if (G_scan_easting(value, &x, window.proj))
	    window.east = x;
	else
	    die(parm.east);
    }

    /* w= */
    if ((value = parm.west->answer)) {
	if ((i = nsew(value, "w+", "w-", "e-"))) {
	    if (!G_scan_resolution(value + 2, &x, window.proj))
		die(parm.west);
	    switch (i) {
	    case 1:
		window.west += x;
		break;
	    case 2:
		window.west -= x;
		break;
	    case 3:
		window.west = window.east - x;
		break;
	    }
	}
	else if (G_scan_easting(value, &x, window.proj))
	    window.west = x;
	else
	    die(parm.west);
    }

    /* t= */
    if ((value = parm.top->answer)) {
	if ((i = nsew(value, "t+", "t-", "b+"))) {
	    if (sscanf(value + 2, "%lf", &x) != 1)
		die(parm.top);
	    switch (i) {
	    case 1:
		window.top += x;
		break;
	    case 2:
		window.top -= x;
		break;
	    case 3:
		window.top = window.bottom + x;
		break;
	    }
	}
	else if (sscanf(value, "%lf", &x) == 1)
	    window.top = x;
	else
	    die(parm.top);
    }

    /* b= */
    if ((value = parm.bottom->answer)) {
	if ((i = nsew(value, "b+", "b-", "t-"))) {
	    if (sscanf(value + 2, "%lf", &x) != 1)
		die(parm.bottom);
	    switch (i) {
	    case 1:
		window.bottom += x;
		break;
	    case 2:
		window.bottom -= x;
		break;
	    case 3:
		window.bottom = window.top - x;
		break;
	    }
	}
	else if (sscanf(value, "%lf", &x) == 1)
	    window.bottom = x;
	else
	    die(parm.bottom);
    }

    /* res= */
    if ((value = parm.res->answer)) {
	if (!G_scan_resolution(value, &x, window.proj))
	    die(parm.res);
	window.ns_res = x;
	window.ew_res = x;

	if (flag.res_set->answer) {
	    window.north = ceil(window.north / x) * x;
	    window.south = floor(window.south / x) * x;
	    window.east = ceil(window.east / x) * x;
	    window.west = floor(window.west / x) * x;
	}
    }

    /* res3= */
    if ((value = parm.res3->answer)) {
	if (!G_scan_resolution(value, &x, window.proj))
	    die(parm.res);
	window.ns_res3 = x;
	window.ew_res3 = x;
	window.tb_res = x;
    }

    /* nsres= */
    if ((value = parm.nsres->answer)) {
	if (!G_scan_resolution(value, &x, window.proj))
	    die(parm.nsres);
	window.ns_res = x;

	if (flag.res_set->answer) {
	    window.north = ceil(window.north / x) * x;
	    window.south = floor(window.south / x) * x;
	}
    }

    /* ewres= */
    if ((value = parm.ewres->answer)) {
	if (!G_scan_resolution(value, &x, window.proj))
	    die(parm.ewres);
	window.ew_res = x;

	if (flag.res_set->answer) {
	    window.east = ceil(window.east / x) * x;
	    window.west = floor(window.west / x) * x;
	}
    }

    /* tbres= */
    if ((value = parm.tbres->answer)) {
	if (sscanf(value, "%lf", &x) != 1)
	    die(parm.tbres);
	window.tb_res = x;

	if (flag.res_set->answer) {
	    window.top = ceil(window.top / x) * x;
	    window.bottom = floor(window.bottom / x) * x;
	}
    }

    /* rows= */
    if ((value = parm.rows->answer)) {
	if (sscanf(value, "%i", &ival) != 1)
	    die(parm.rows);
	window.rows = ival;
	row_flag = 1;
    }

    /* cols= */
    if ((value = parm.cols->answer)) {
	if (sscanf(value, "%i", &ival) != 1)
	    die(parm.cols);
	window.cols = ival;
	col_flag = 1;
    }

    /* zoom= */
    if ((name = parm.zoom->answer)) {
	mapset = G_find_raster2(name, "");
	if (!mapset)
	    G_fatal_error(_("Raster map <%s> not found"), name);
	zoom(&window, name, mapset);
    }

    /* align= */
    if ((name = parm.align->answer)) {
	mapset = G_find_raster2(name, "");
	if (!mapset)
	    G_fatal_error(_("Raster map <%s> not found"), name);
	Rast_get_cellhd(name, mapset, &temp_window);
	Rast_align_window(&window, &temp_window);
    }

    /* save= */
    if ((name = parm.save->answer)) {
	temp_window = window;
	G_adjust_Cell_head3(&temp_window, 0, 0, 0);
	if (G_put_element_window(&temp_window, "windows", name) < 0)
	    G_fatal_error(_("Unable to set region <%s>"), name);
    }

    G_adjust_Cell_head3(&window, row_flag, col_flag, 0);
    if (set_flag) {
	if (G_put_window(&window) < 0)
	    G_fatal_error(_("Unable to update current region"));
    }

    if (flag.savedefault->answer) {
	if (strcmp(G_mapset(), "PERMANENT") == 0) {
	    G_put_element_window(&window, "", "DEFAULT_WIND");
	}
	else {
	    G_fatal_error(_("Unable to change default region. "
			    "The current mapset is not <PERMANENT>."));
	}
    }				/* / flag.savedefault->answer */


    if (print_flag)
	print_window(&window, print_flag, flat_flag);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 2
0
int main(int argc, char *argv[])
{
    int m1;
    struct FPRange range;
    DCELL cellmin, cellmax;
    FCELL *cellrow, fcellmin;

    struct GModule *module;
    struct
    {
	struct Option *input, *elev, *slope, *aspect, *pcurv, *tcurv, *mcurv,
	    *smooth, *maskmap, *zmult, *fi, *segmax, *npmin, *res_ew, *res_ns,
	    *overlap, *theta, *scalex;
    } parm;
    struct
    {
	struct Flag *deriv, *cprght;
    } flag;


    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("resample"));
    module->description =
	_("Reinterpolates and optionally computes topographic analysis from "
	  "input raster map to a new raster map (possibly with "
	  "different resolution) using regularized spline with "
	  "tension and smoothing.");

    parm.input = G_define_standard_option(G_OPT_R_INPUT);

    parm.res_ew = G_define_option();
    parm.res_ew->key = "ew_res";
    parm.res_ew->type = TYPE_DOUBLE;
    parm.res_ew->required = YES;
    parm.res_ew->description = _("Desired east-west resolution");

    parm.res_ns = G_define_option();
    parm.res_ns->key = "ns_res";
    parm.res_ns->type = TYPE_DOUBLE;
    parm.res_ns->required = YES;
    parm.res_ns->description = _("Desired north-south resolution");

    parm.elev = G_define_option();
    parm.elev->key = "elev";
    parm.elev->type = TYPE_STRING;
    parm.elev->required = NO;
    parm.elev->gisprompt = "new,cell,raster";
    parm.elev->description = _("Output z-file (elevation) map");
    parm.elev->guisection = _("Output");

    parm.slope = G_define_option();
    parm.slope->key = "slope";
    parm.slope->type = TYPE_STRING;
    parm.slope->required = NO;
    parm.slope->gisprompt = "new,cell,raster";
    parm.slope->description = _("Output slope map (or fx)");
    parm.slope->guisection = _("Output");

    parm.aspect = G_define_option();
    parm.aspect->key = "aspect";
    parm.aspect->type = TYPE_STRING;
    parm.aspect->required = NO;
    parm.aspect->gisprompt = "new,cell,raster";
    parm.aspect->description = _("Output aspect map (or fy)");
    parm.aspect->guisection = _("Output");

    parm.pcurv = G_define_option();
    parm.pcurv->key = "pcurv";
    parm.pcurv->type = TYPE_STRING;
    parm.pcurv->required = NO;
    parm.pcurv->gisprompt = "new,cell,raster";
    parm.pcurv->description = _("Output profile curvature map (or fxx)");
    parm.pcurv->guisection = _("Output");

    parm.tcurv = G_define_option();
    parm.tcurv->key = "tcurv";
    parm.tcurv->type = TYPE_STRING;
    parm.tcurv->required = NO;
    parm.tcurv->gisprompt = "new,cell,raster";
    parm.tcurv->description = _("Output tangential curvature map (or fyy)");
    parm.tcurv->guisection = _("Output");

    parm.mcurv = G_define_option();
    parm.mcurv->key = "mcurv";
    parm.mcurv->type = TYPE_STRING;
    parm.mcurv->required = NO;
    parm.mcurv->gisprompt = "new,cell,raster";
    parm.mcurv->description = _("Output mean curvature map (or fxy)");
    parm.mcurv->guisection = _("Output");

    parm.smooth = G_define_option();
    parm.smooth->key = "smooth";
    parm.smooth->type = TYPE_STRING;
    parm.smooth->required = NO;
    parm.smooth->gisprompt = "old,cell,raster";
    parm.smooth->description = _("Name of raster map containing smoothing");
    parm.smooth->guisection = _("Settings");

    parm.maskmap = G_define_option();
    parm.maskmap->key = "maskmap";
    parm.maskmap->type = TYPE_STRING;
    parm.maskmap->required = NO;
    parm.maskmap->gisprompt = "old,cell,raster";
    parm.maskmap->description = _("Name of raster map to be used as mask");
    parm.maskmap->guisection = _("Settings");

    parm.overlap = G_define_option();
    parm.overlap->key = "overlap";
    parm.overlap->type = TYPE_INTEGER;
    parm.overlap->required = NO;
    parm.overlap->answer = OVERLAP;
    parm.overlap->description = _("Rows/columns overlap for segmentation");
    parm.overlap->guisection = _("Settings");

    parm.zmult = G_define_option();
    parm.zmult->key = "zmult";
    parm.zmult->type = TYPE_DOUBLE;
    parm.zmult->answer = ZMULT;
    parm.zmult->required = NO;
    parm.zmult->description = _("Multiplier for z-values");
    parm.zmult->guisection = _("Settings");

    parm.fi = G_define_option();
    parm.fi->key = "tension";
    parm.fi->type = TYPE_DOUBLE;
    parm.fi->answer = TENSION;
    parm.fi->required = NO;
    parm.fi->description = _("Spline tension value");
    parm.fi->guisection = _("Settings");

    parm.theta = G_define_option();
    parm.theta->key = "theta";
    parm.theta->type = TYPE_DOUBLE;
    parm.theta->required = NO;
    parm.theta->description = _("Anisotropy angle (in degrees)");
    parm.theta->guisection = _("Anisotropy");

    parm.scalex = G_define_option();
    parm.scalex->key = "scalex";
    parm.scalex->type = TYPE_DOUBLE;
    parm.scalex->required = NO;
    parm.scalex->description = _("Anisotropy scaling factor");
    parm.scalex->guisection = _("Anisotropy");

    flag.cprght = G_define_flag();
    flag.cprght->key = 't';
    flag.cprght->description = _("Use dnorm independent tension");

    flag.deriv = G_define_flag();
    flag.deriv->key = 'd';
    flag.deriv->description =
	_("Output partial derivatives instead of topographic parameters");
    flag.deriv->guisection = _("Output");

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

    G_get_set_window(&winhd);

    inp_ew_res = winhd.ew_res;
    inp_ns_res = winhd.ns_res;
    inp_cols = winhd.cols;
    inp_rows = winhd.rows;
    inp_x_orig = winhd.west;
    inp_y_orig = winhd.south;

    input = parm.input->answer;
    smooth = parm.smooth->answer;
    maskmap = parm.maskmap->answer;

    elev = parm.elev->answer;
    slope = parm.slope->answer;
    aspect = parm.aspect->answer;
    pcurv = parm.pcurv->answer;
    tcurv = parm.tcurv->answer;
    mcurv = parm.mcurv->answer;

    cond2 = ((pcurv != NULL) || (tcurv != NULL) || (mcurv != NULL));
    cond1 = ((slope != NULL) || (aspect != NULL) || cond2);
    deriv = flag.deriv->answer;
    dtens = flag.cprght->answer;

    ertre = 0.1;

    if (!G_scan_resolution(parm.res_ew->answer, &ew_res, winhd.proj))
	G_fatal_error(_("Unable to read ew_res value"));

    if (!G_scan_resolution(parm.res_ns->answer, &ns_res, winhd.proj))
	G_fatal_error(_("Unable to read ns_res value"));

    if (sscanf(parm.fi->answer, "%lf", &fi) != 1)
	G_fatal_error(_("Invalid value for tension"));

    if (sscanf(parm.zmult->answer, "%lf", &zmult) != 1)
	G_fatal_error(_("Invalid value for zmult"));

    if (sscanf(parm.overlap->answer, "%d", &overlap) != 1)
	G_fatal_error(_("Invalid value for overlap"));

    if (parm.theta->answer) {
	if (sscanf(parm.theta->answer, "%lf", &theta) != 1)
	    G_fatal_error(_("Invalid value for theta"));
    }
    if (parm.scalex->answer) {
	if (sscanf(parm.scalex->answer, "%lf", &scalex) != 1)
	    G_fatal_error(_("Invalid value for scalex"));
	if (!parm.theta->answer)
	    G_fatal_error(_("When using anisotropy both theta and scalex must be specified"));
    }

    /*
     * G_set_embedded_null_value_mode(1);
     */
    outhd.ew_res = ew_res;
    outhd.ns_res = ns_res;
    outhd.east = winhd.east;
    outhd.west = winhd.west;
    outhd.north = winhd.north;
    outhd.south = winhd.south;
    outhd.proj = winhd.proj;
    outhd.zone = winhd.zone;
    G_adjust_Cell_head(&outhd, 0, 0);
    ew_res = outhd.ew_res;
    ns_res = outhd.ns_res;
    nsizc = outhd.cols;
    nsizr = outhd.rows;
    disk = nsizc * nsizr * sizeof(int);

    az = G_alloc_vector(nsizc + 1);

    if (cond1) {
	adx = G_alloc_vector(nsizc + 1);
	ady = G_alloc_vector(nsizc + 1);
	if (cond2) {
	    adxx = G_alloc_vector(nsizc + 1);
	    adyy = G_alloc_vector(nsizc + 1);
	    adxy = G_alloc_vector(nsizc + 1);
	}
    }

    if (smooth != NULL) {

	fdsmooth = Rast_open_old(smooth, "");

	Rast_get_cellhd(smooth, "", &smhd);

	if ((winhd.ew_res != smhd.ew_res) || (winhd.ns_res != smhd.ns_res))
	    G_fatal_error(_("Map <%s> is the wrong resolution"), smooth);

	if (Rast_read_fp_range(smooth, "", &range) >= 0)
	    Rast_get_fp_range_min_max(&range, &cellmin, &cellmax);

	fcellmin = (float)cellmin;

	if (Rast_is_f_null_value(&fcellmin) || fcellmin < 0.0)
	    G_fatal_error(_("Smoothing values can not be negative or NULL"));
    }

    Rast_get_cellhd(input, "", &inphd);

    if ((winhd.ew_res != inphd.ew_res) || (winhd.ns_res != inphd.ns_res))
	G_fatal_error(_("Input map resolution differs from current region resolution!"));

    fdinp = Rast_open_old(input, "");

    sdisk = 0;
    if (elev != NULL)
	sdisk += disk;
    if (slope != NULL)
	sdisk += disk;
    if (aspect != NULL)
	sdisk += disk;
    if (pcurv != NULL)
	sdisk += disk;
    if (tcurv != NULL)
	sdisk += disk;
    if (mcurv != NULL)
	sdisk += disk;

    G_message(_("Processing all selected output files will require"));
    if (sdisk > 1024) {
	if (sdisk > 1024 * 1024) {
	    if (sdisk > 1024 * 1024 * 1024) {
		G_message(_("%.2f GB of disk space for temp files."), sdisk / (1024. * 1024. * 1024.));
	    }
	    else
		G_message(_("%.2f MB of disk space for temp files."), sdisk / (1024. * 1024.));
	}
	else
	    G_message(_("%.2f KB of disk space for temp files."), sdisk / 1024.);
    }
    else
	G_message(_("%d bytes of disk space for temp files."), sdisk);


    fstar2 = fi * fi / 4.;
    tfsta2 = fstar2 + fstar2;
    deltx = winhd.east - winhd.west;
    delty = winhd.north - winhd.south;
    xmin = winhd.west;
    xmax = winhd.east;
    ymin = winhd.south;
    ymax = winhd.north;
    if (smooth != NULL)
	smc = -9999;
    else
	smc = 0.01;


    if (Rast_read_fp_range(input, "", &range) >= 0) {
	Rast_get_fp_range_min_max(&range, &cellmin, &cellmax);
    }
    else {
	cellrow = Rast_allocate_f_buf();
	for (m1 = 0; m1 < inp_rows; m1++) {
	    Rast_get_f_row(fdinp, cellrow, m1);
	    Rast_row_update_fp_range(cellrow, m1, &range, FCELL_TYPE);
	}
	Rast_get_fp_range_min_max(&range, &cellmin, &cellmax);
    }

    fcellmin = (float)cellmin;
    if (Rast_is_f_null_value(&fcellmin))
	G_fatal_error(_("Maximum value of a raster map is NULL."));

    zmin = (double)cellmin *zmult;
    zmax = (double)cellmax *zmult;

    G_debug(1, "zmin=%f, zmax=%f", zmin, zmax);

    if (fd4 != NULL)
	fprintf(fd4, "deltx,delty %f %f \n", deltx, delty);
    create_temp_files();

    IL_init_params_2d(&params, NULL, 1, 1, zmult, KMIN, KMAX, maskmap,
		      outhd.rows, outhd.cols, az, adx, ady, adxx, adyy, adxy,
		      fi, MAXPOINTS, SCIK1, SCIK2, SCIK3, smc, elev, slope,
		      aspect, pcurv, tcurv, mcurv, dmin, inp_x_orig,
		      inp_y_orig, deriv, theta, scalex, Tmp_fd_z, Tmp_fd_dx,
		      Tmp_fd_dy, Tmp_fd_xx, Tmp_fd_yy, Tmp_fd_xy, NULL, NULL,
		      0, NULL);

    /*  In the above line, the penultimate argument is supposed to be a 
     * deviations file pointer.  None is obvious, so I used NULL. */
    /*  The 3rd and 4th argument are int-s, elatt and smatt (from the function
     * definition.  The value 1 seemed like a good placeholder...  or not. */

    IL_init_func_2d(&params, IL_grid_calc_2d, IL_matrix_create,
		    IL_check_at_points_2d,
		    IL_secpar_loop_2d, IL_crst, IL_crstg, IL_write_temp_2d);

    G_message(_("Temporarily changing the region to desired resolution ..."));
    Rast_set_window(&outhd);

    bitmask = IL_create_bitmask(&params);
    /* change region to initial region */
    G_message(_("Changing back to the original region ..."));
    Rast_set_window(&winhd);

    ertot = 0.;
    cursegm = 0;
    G_message(_("Percent complete: "));


    NPOINT =
	IL_resample_interp_segments_2d(&params, bitmask, zmin, zmax, &zminac,
				       &zmaxac, &gmin, &gmax, &c1min, &c1max,
				       &c2min, &c2max, &ertot, nsizc, &dnorm,
				       overlap, inp_rows, inp_cols, fdsmooth,
				       fdinp, ns_res, ew_res, inp_ns_res,
				       inp_ew_res, dtens);


    G_message(_("dnorm in mainc after grid before out1= %f"), dnorm);

    if (NPOINT < 0) {
	clean();
	G_fatal_error(_("split_and_interpolate() failed"));
    }

    if (fd4 != NULL)
	fprintf(fd4, "max. error found = %f \n", ertot);
    G_free_vector(az);
    if (cond1) {
	G_free_vector(adx);
	G_free_vector(ady);
	if (cond2) {
	    G_free_vector(adxx);
	    G_free_vector(adyy);
	    G_free_vector(adxy);
	}
    }
    G_message(_("dnorm in mainc after grid before out2= %f"), dnorm);

    if (IL_resample_output_2d(&params, zmin, zmax, zminac, zmaxac, c1min,
			      c1max, c2min, c2max, gmin, gmax, ertot, input,
			      &dnorm, &outhd, &winhd, smooth, NPOINT) < 0) {
	clean();
	G_fatal_error(_("Unable to write raster maps -- try increasing cell size"));
    }

    G_free(zero_array_cell);
    clean();
    if (fd4)
	fclose(fd4);
    Rast_close(fdinp);
    if (smooth != NULL)
	Rast_close(fdsmooth);

    G_done_msg(" ");
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 3
0
int main(int argc, char *argv[])
{
    int out_fd, base_raster;
    char *infile, *outmap;
    int percent;
    double zrange_min, zrange_max, d_tmp;
    double irange_min, irange_max;
    unsigned long estimated_lines;

    RASTER_MAP_TYPE rtype, base_raster_data_type;
    struct History history;
    char title[64];
    SEGMENT base_segment;
    struct PointBinning point_binning;
    void *base_array;
    void *raster_row;
    struct Cell_head region;
    struct Cell_head input_region;
    int rows, last_rows, row0, cols;		/* scan box size */
    int row;		/* counters */

    int pass, npasses;
    unsigned long line, line_total;
    unsigned int counter;
    unsigned long n_invalid;
    char buff[BUFFSIZE];
    double x, y, z;
    double intensity;
    int arr_row, arr_col;
    unsigned long count, count_total;
    int point_class;

    double zscale = 1.0;
    double iscale = 1.0;
    double res = 0.0;

    struct BinIndex bin_index_nodes;
    bin_index_nodes.num_nodes = 0;
    bin_index_nodes.max_nodes = 0;
    bin_index_nodes.nodes = 0;

    struct GModule *module;
    struct Option *input_opt, *output_opt, *percent_opt, *type_opt, *filter_opt, *class_opt;
    struct Option *method_opt, *base_raster_opt;
    struct Option *zrange_opt, *zscale_opt;
    struct Option *irange_opt, *iscale_opt;
    struct Option *trim_opt, *pth_opt, *res_opt;
    struct Option *file_list_opt;
    struct Flag *print_flag, *scan_flag, *shell_style, *over_flag, *extents_flag;
    struct Flag *intens_flag, *intens_import_flag;
    struct Flag *set_region_flag;
    struct Flag *base_rast_res_flag;
    struct Flag *only_valid_flag;

    /* LAS */
    LASReaderH LAS_reader;
    LASHeaderH LAS_header;
    LASSRSH LAS_srs;
    LASPointH LAS_point;
    int return_filter;

    const char *projstr;
    struct Cell_head cellhd, loc_wind;

    unsigned int n_filtered;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("import"));
    G_add_keyword(_("LIDAR"));
    G_add_keyword(_("statistics"));
    G_add_keyword(_("conversion"));
    G_add_keyword(_("aggregation"));
    G_add_keyword(_("binning"));
    module->description =
	_("Creates a raster map from LAS LiDAR points using univariate statistics.");

    input_opt = G_define_standard_option(G_OPT_F_BIN_INPUT);
    input_opt->required = NO;
    input_opt->label = _("LAS input file");
    input_opt->description = _("LiDAR input files in LAS format (*.las or *.laz)");
    input_opt->guisection = _("Input");

    output_opt = G_define_standard_option(G_OPT_R_OUTPUT);
    output_opt->required = NO;
    output_opt->guisection = _("Output");

    file_list_opt = G_define_standard_option(G_OPT_F_INPUT);
    file_list_opt->key = "file";
    file_list_opt->label = _("File containing names of LAS input files");
    file_list_opt->description = _("LiDAR input files in LAS format (*.las or *.laz)");
    file_list_opt->required = NO;
    file_list_opt->guisection = _("Input");

    method_opt = G_define_option();
    method_opt->key = "method";
    method_opt->type = TYPE_STRING;
    method_opt->required = NO;
    method_opt->description = _("Statistic to use for raster values");
    method_opt->options =
	"n,min,max,range,sum,mean,stddev,variance,coeff_var,median,percentile,skewness,trimmean";
    method_opt->answer = "mean";
    method_opt->guisection = _("Statistic");
    G_asprintf((char **)&(method_opt->descriptions),
               "n;%s;"
               "min;%s;"
               "max;%s;"
               "range;%s;"
               "sum;%s;"
               "mean;%s;"
               "stddev;%s;"
               "variance;%s;"
               "coeff_var;%s;"
               "median;%s;"
               "percentile;%s;"
               "skewness;%s;"
               "trimmean;%s",
               _("Number of points in cell"),
               _("Minimum value of point values in cell"),
               _("Maximum value of point values in cell"),
               _("Range of point values in cell"),
               _("Sum of point values in cell"),
               _("Mean (average) value of point values in cell"),
               _("Standard deviation of point values in cell"),
               _("Variance of point values in cell"),
               _("Coefficient of variance of point values in cell"),
               _("Median value of point values in cell"),
               _("pth (nth) percentile of point values in cell"),
               _("Skewness of point values in cell"),
               _("Trimmed mean of point values in cell"));

    type_opt = G_define_standard_option(G_OPT_R_TYPE);
    type_opt->required = NO;
    type_opt->answer = "FCELL";

    base_raster_opt = G_define_standard_option(G_OPT_R_INPUT);
    base_raster_opt->key = "base_raster";
    base_raster_opt->required = NO;
    base_raster_opt->label =
        _("Subtract raster values from the Z coordinates");
    base_raster_opt->description =
        _("The scale for Z is applied beforehand, the range filter for"
          " Z afterwards");
    base_raster_opt->guisection = _("Transform");

    zrange_opt = G_define_option();
    zrange_opt->key = "zrange";
    zrange_opt->type = TYPE_DOUBLE;
    zrange_opt->required = NO;
    zrange_opt->key_desc = "min,max";
    zrange_opt->description = _("Filter range for Z data (min,max)");
    zrange_opt->guisection = _("Selection");

    zscale_opt = G_define_option();
    zscale_opt->key = "zscale";
    zscale_opt->type = TYPE_DOUBLE;
    zscale_opt->required = NO;
    zscale_opt->answer = "1.0";
    zscale_opt->description = _("Scale to apply to Z data");
    zscale_opt->guisection = _("Transform");

    irange_opt = G_define_option();
    irange_opt->key = "intensity_range";
    irange_opt->type = TYPE_DOUBLE;
    irange_opt->required = NO;
    irange_opt->key_desc = "min,max";
    irange_opt->description = _("Filter range for intensity values (min,max)");
    irange_opt->guisection = _("Selection");

    iscale_opt = G_define_option();
    iscale_opt->key = "intensity_scale";
    iscale_opt->type = TYPE_DOUBLE;
    iscale_opt->required = NO;
    iscale_opt->answer = "1.0";
    iscale_opt->description = _("Scale to apply to intensity values");
    iscale_opt->guisection = _("Transform");

    percent_opt = G_define_option();
    percent_opt->key = "percent";
    percent_opt->type = TYPE_INTEGER;
    percent_opt->required = NO;
    percent_opt->answer = "100";
    percent_opt->options = "1-100";
    percent_opt->description = _("Percent of map to keep in memory");

    /* I would prefer to call the following "percentile", but that has too
     * much namespace overlap with the "percent" option above */
    pth_opt = G_define_option();
    pth_opt->key = "pth";
    pth_opt->type = TYPE_INTEGER;
    pth_opt->required = NO;
    pth_opt->options = "1-100";
    pth_opt->description = _("pth percentile of the values");
    pth_opt->guisection = _("Statistic");

    trim_opt = G_define_option();
    trim_opt->key = "trim";
    trim_opt->type = TYPE_DOUBLE;
    trim_opt->required = NO;
    trim_opt->options = "0-50";
    trim_opt->label = _("Discard given percentage of the smallest and largest values");
    trim_opt->description =
	_("Discard <trim> percent of the smallest and <trim> percent of the largest observations");
    trim_opt->guisection = _("Statistic");

    res_opt = G_define_option();
    res_opt->key = "resolution";
    res_opt->type = TYPE_DOUBLE;
    res_opt->required = NO;
    res_opt->description =
	_("Output raster resolution");
    res_opt->guisection = _("Output");

    filter_opt = G_define_option();
    filter_opt->key = "return_filter";
    filter_opt->type = TYPE_STRING;
    filter_opt->required = NO;
    filter_opt->label = _("Only import points of selected return type");
    filter_opt->description = _("If not specified, all points are imported");
    filter_opt->options = "first,last,mid";
    filter_opt->guisection = _("Selection");

    class_opt = G_define_option();
    class_opt->key = "class_filter";
    class_opt->type = TYPE_INTEGER;
    class_opt->multiple = YES;
    class_opt->required = NO;
    class_opt->label = _("Only import points of selected class(es)");
    class_opt->description = _("Input is comma separated integers. "
                               "If not specified, all points are imported.");
    class_opt->guisection = _("Selection");

    print_flag = G_define_flag();
    print_flag->key = 'p';
    print_flag->description =
	_("Print LAS file info and exit");

    extents_flag = G_define_flag();
    extents_flag->key = 'e';
    extents_flag->label =
        _("Use the extent of the input for the raster extent");
    extents_flag->description =
        _("Set internally computational region extents based on the"
          " point cloud");
    extents_flag->guisection = _("Output");

    set_region_flag = G_define_flag();
    set_region_flag->key = 'n';
    set_region_flag->label =
        _("Set computation region to match the new raster map");
    set_region_flag->description =
        _("Set computation region to match the 2D extent and resolution"
          " of the newly created new raster map");
    set_region_flag->guisection = _("Output");

    over_flag = G_define_flag();
    over_flag->key = 'o';
    over_flag->label =
	_("Override projection check (use current location's projection)");
    over_flag->description =
	_("Assume that the dataset has same projection as the current location");

    scan_flag = G_define_flag();
    scan_flag->key = 's';
    scan_flag->description = _("Scan data file for extent then exit");

    shell_style = G_define_flag();
    shell_style->key = 'g';
    shell_style->description =
	_("In scan mode, print using shell script style");

    intens_flag = G_define_flag();
    intens_flag->key = 'i';
    intens_flag->label =
        _("Use intensity values rather than Z values");
    intens_flag->description =
        _("Uses intensity values everywhere as if they would be Z"
          " coordinates");

    intens_import_flag = G_define_flag();
    intens_import_flag->key = 'j';
    intens_import_flag->description =
        _("Use Z values for filtering, but intensity values for statistics");

    base_rast_res_flag = G_define_flag();
    base_rast_res_flag->key = 'd';
    base_rast_res_flag->label =
        _("Use base raster resolution instead of computational region");
    base_rast_res_flag->description =
        _("For getting values from base raster, use its actual"
          " resolution instead of computational region resolution");

    only_valid_flag = G_define_flag();
    only_valid_flag->key = 'v';
    only_valid_flag->label = _("Use only valid points");
    only_valid_flag->description =
        _("Points invalid according to APSRS LAS specification will be"
          " filtered out");
    only_valid_flag->guisection = _("Selection");

    G_option_required(input_opt, file_list_opt, NULL);
    G_option_exclusive(input_opt, file_list_opt, NULL);
    G_option_required(output_opt, print_flag, scan_flag, shell_style, NULL);
    G_option_exclusive(intens_flag, intens_import_flag, NULL);
    G_option_requires(base_rast_res_flag, base_raster_opt, NULL);

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

    int only_valid = FALSE;
    n_invalid = 0;
    if (only_valid_flag->answer)
        only_valid = TRUE;

    /* we could use rules but this gives more info and allows continuing */
    if (set_region_flag->answer && !(extents_flag->answer || res_opt->answer)) {
        G_warning(_("Flag %c makes sense only with %s option or -%c flag"),
                  set_region_flag->key, res_opt->key, extents_flag->key);
        /* avoid the call later on */
        set_region_flag->answer = '\0';
    }

    struct StringList infiles;

    if (file_list_opt->answer) {
        if (access(file_list_opt->answer, F_OK) != 0)
            G_fatal_error(_("File <%s> does not exist"), file_list_opt->answer);
        string_list_from_file(&infiles, file_list_opt->answer);
    }
    else {
        string_list_from_one_item(&infiles, input_opt->answer);
    }

    /* parse input values */
    outmap = output_opt->answer;

    if (shell_style->answer && !scan_flag->answer) {
	scan_flag->answer = 1; /* pointer not int, so set = shell_style->answer ? */
    }

    /* check zrange and extent relation */
    if (scan_flag->answer || extents_flag->answer) {
        if (zrange_opt->answer)
            G_warning(_("zrange will not be taken into account during scan"));
    }

    Rast_get_window(&region);
    /* G_get_window seems to be unreliable if the location has been changed */
    G_get_set_window(&loc_wind);        /* TODO: v.in.lidar uses G_get_default_window() */

    estimated_lines = 0;
    int i;
    for (i = 0; i < infiles.num_items; i++) {
        infile = infiles.items[i];
        /* don't if file not found */
        if (access(infile, F_OK) != 0)
            G_fatal_error(_("Input file <%s> does not exist"), infile);
        /* Open LAS file*/
        LAS_reader = LASReader_Create(infile);
        if (LAS_reader == NULL)
            G_fatal_error(_("Unable to open file <%s> as a LiDAR point cloud"),
                          infile);
        LAS_header = LASReader_GetHeader(LAS_reader);
        if  (LAS_header == NULL) {
            G_fatal_error(_("Unable to read LAS header of <%s>"), infile);
        }

        LAS_srs = LASHeader_GetSRS(LAS_header);

        /* print info or check projection if we are actually importing */
        if (print_flag->answer) {
            /* print filename when there is more than one file */
            if (infiles.num_items > 1)
                fprintf(stdout, "File: %s\n", infile);
            /* Print LAS header */
            print_lasinfo(LAS_header, LAS_srs);
        }
        else {
            /* report that we are checking more files */
            if (i == 1)
                G_message(_("First file's projection checked,"
                            " checking projection of the other files..."));
            /* Fetch input map projection in GRASS form. */
            projstr = LASSRS_GetWKT_CompoundOK(LAS_srs);
            /* we are printing the non-warning messages only for first file */
            projection_check_wkt(cellhd, loc_wind, projstr, over_flag->answer,
                                 shell_style->answer || i);
            /* if there is a problem in some other file, first OK message
             * is printed but than a warning, this is not ideal but hopefully
             * not so confusing when importing multiple files */
        }
        if (scan_flag->answer || extents_flag->answer) {
            /* we assign to the first one (i==0) but update for the rest */
            scan_bounds(LAS_reader, shell_style->answer, extents_flag->answer, i,
                        zscale, &region);
        }
        /* number of estimated point across all files */
        /* TODO: this should be ull which won't work with percent report */
        estimated_lines += LASHeader_GetPointRecordsCount(LAS_header);
        /* We are closing all again and we will be opening them later,
         * so we don't have to worry about limit for open files. */
        LASSRS_Destroy(LAS_srs);
        LASHeader_Destroy(LAS_header);
        LASReader_Destroy(LAS_reader);
    }
    /* if we are not importing, end */
    if (print_flag->answer || scan_flag->answer)
        exit(EXIT_SUCCESS);

    return_filter = LAS_ALL;
    if (filter_opt->answer) {
	if (strcmp(filter_opt->answer, "first") == 0)
	    return_filter = LAS_FIRST;
	else if (strcmp(filter_opt->answer, "last") == 0)
	    return_filter = LAS_LAST;
	else if (strcmp(filter_opt->answer, "mid") == 0)
	    return_filter = LAS_MID;
	else
	    G_fatal_error(_("Unknown filter option <%s>"), filter_opt->answer);
    }
    struct ReturnFilter return_filter_struct;
    return_filter_struct.filter = return_filter;
    struct ClassFilter class_filter;
    class_filter_create_from_strings(&class_filter, class_opt->answers);

    percent = atoi(percent_opt->answer);
    /* TODO: we already used zscale */
    /* TODO: we don't report intensity range */
    if (zscale_opt->answer)
        zscale = atof(zscale_opt->answer);
    if (iscale_opt->answer)
        iscale = atof(iscale_opt->answer);

    /* parse zrange */
    if (zrange_opt->answer != NULL) {
	if (zrange_opt->answers[0] == NULL)
	    G_fatal_error(_("Invalid zrange"));

	sscanf(zrange_opt->answers[0], "%lf", &zrange_min);
	sscanf(zrange_opt->answers[1], "%lf", &zrange_max);

	if (zrange_min > zrange_max) {
	    d_tmp = zrange_max;
	    zrange_max = zrange_min;
	    zrange_min = d_tmp;
	}
    }
    /* parse irange */
    if (irange_opt->answer != NULL) {
        if (irange_opt->answers[0] == NULL)
            G_fatal_error(_("Invalid %s"), irange_opt->key);

        sscanf(irange_opt->answers[0], "%lf", &irange_min);
        sscanf(irange_opt->answers[1], "%lf", &irange_max);

        if (irange_min > irange_max) {
            d_tmp = irange_max;
            irange_max = irange_min;
            irange_min = d_tmp;
        }
    }

    point_binning_set(&point_binning, method_opt->answer, pth_opt->answer,
                      trim_opt->answer, FALSE);

    base_array = NULL;

    if (strcmp("CELL", type_opt->answer) == 0)
	rtype = CELL_TYPE;
    else if (strcmp("DCELL", type_opt->answer) == 0)
	rtype = DCELL_TYPE;
    else
	rtype = FCELL_TYPE;

    if (point_binning.method == METHOD_N)
	rtype = CELL_TYPE;

    if (res_opt->answer) {
	/* align to resolution */
	res = atof(res_opt->answer);

	if (!G_scan_resolution(res_opt->answer, &res, region.proj))
	    G_fatal_error(_("Invalid input <%s=%s>"), res_opt->key, res_opt->answer);

	if (res <= 0)
	    G_fatal_error(_("Option '%s' must be > 0.0"), res_opt->key);
	
	region.ns_res = region.ew_res = res;

	region.north = ceil(region.north / res) * res;
	region.south = floor(region.south / res) * res;
	region.east = ceil(region.east / res) * res;
	region.west = floor(region.west / res) * res;

	G_adjust_Cell_head(&region, 0, 0);
    }
    else if (extents_flag->answer) {
	/* align to current region */
	Rast_align_window(&region, &loc_wind);
    }
    Rast_set_output_window(&region);

    rows = last_rows = region.rows;
    npasses = 1;
    if (percent < 100) {
	rows = (int)(region.rows * (percent / 100.0));
	npasses = region.rows / rows;
	last_rows = region.rows - npasses * rows;
	if (last_rows)
	    npasses++;
	else
	    last_rows = rows;

    }
    cols = region.cols;

    G_debug(2, "region.n=%f  region.s=%f  region.ns_res=%f", region.north,
	    region.south, region.ns_res);
    G_debug(2, "region.rows=%d  [box_rows=%d]  region.cols=%d", region.rows,
	    rows, region.cols);

    /* using row-based chunks (used for output) when input and output
     * region matches and using segment library when they don't */
    int use_segment = 0;
    int use_base_raster_res = 0;
    /* TODO: see if the input region extent is smaller than the raster
     * if yes, the we need to load the whole base raster if the -e
     * flag was defined (alternatively clip the regions) */
    if (base_rast_res_flag->answer)
        use_base_raster_res = 1;
    if (base_raster_opt->answer && (res_opt->answer || use_base_raster_res
                                    || extents_flag->answer))
        use_segment = 1;
    if (base_raster_opt->answer && !use_segment) {
        /* TODO: do we need to test existence first? mapset? */
        base_raster = Rast_open_old(base_raster_opt->answer, "");
        base_raster_data_type = Rast_get_map_type(base_raster);
        base_array = G_calloc((size_t)rows * (cols + 1), Rast_cell_size(base_raster_data_type));
    }
    if (base_raster_opt->answer && use_segment) {
        if (use_base_raster_res) {
            /* read raster actual extent and resolution */
            Rast_get_cellhd(base_raster_opt->answer, "", &input_region);
            /* TODO: make it only as small as the output is or points are */
            Rast_set_input_window(&input_region);  /* we have split window */
        } else {
            Rast_get_input_window(&input_region);
        }
        rast_segment_open(&base_segment, base_raster_opt->answer, &base_raster_data_type);
    }

    if (!scan_flag->answer) {
        if (!check_rows_cols_fit_to_size_t(rows, cols))
		G_fatal_error(_("Unable to process the hole map at once. "
                        "Please set the '%s' option to some value lower than 100."),
				percent_opt->key);
        point_binning_memory_test(&point_binning, rows, cols, rtype);
	}

    /* open output map */
    out_fd = Rast_open_new(outmap, rtype);

    /* allocate memory for a single row of output data */
    raster_row = Rast_allocate_output_buf(rtype);

    G_message(_("Reading data ..."));

    count_total = line_total = 0;

    /* main binning loop(s) */
    for (pass = 1; pass <= npasses; pass++) {

	if (npasses > 1)
	    G_message(_("Pass #%d (of %d) ..."), pass, npasses);

	/* figure out segmentation */
	row0 = (pass - 1) * rows;
	if (pass == npasses) {
	    rows = last_rows;
	}

        if (base_array) {
            G_debug(2, "filling base raster array");
            for (row = 0; row < rows; row++) {
                Rast_get_row(base_raster, base_array + ((size_t) row * cols * Rast_cell_size(base_raster_data_type)), row, base_raster_data_type);
            }
        }

	G_debug(2, "pass=%d/%d  rows=%d", pass, npasses, rows);

    point_binning_allocate(&point_binning, rows, cols, rtype);

	line = 0;
	count = 0;
	counter = 0;
	G_percent_reset();

        /* loop of input files */
        for (i = 0; i < infiles.num_items; i++) {
            infile = infiles.items[i];
            /* we already know file is there, so just do basic checks */
            LAS_reader = LASReader_Create(infile);
            if (LAS_reader == NULL)
                G_fatal_error(_("Unable to open file <%s>"), infile);

            while ((LAS_point = LASReader_GetNextPoint(LAS_reader)) != NULL) {
                line++;
                counter++;

                if (counter == 100000) {        /* speed */
                    if (line < estimated_lines)
                        G_percent(line, estimated_lines, 3);
                    counter = 0;
                }

                /* We always count them and report because behavior
                 * changed in between 7.0 and 7.2 from undefined (but skipping
                 * invalid points) to filtering them out only when requested. */
                if (!LASPoint_IsValid(LAS_point)) {
                    n_invalid++;
                    if (only_valid)
                        continue;
                }

                x = LASPoint_GetX(LAS_point);
                y = LASPoint_GetY(LAS_point);
                if (intens_flag->answer)
                    /* use intensity as z here to allow all filters (and
                     * modifications) below to be applied for intensity */
                    z = LASPoint_GetIntensity(LAS_point);
                else
                    z = LASPoint_GetZ(LAS_point);

                int return_n = LASPoint_GetReturnNumber(LAS_point);
                int n_returns = LASPoint_GetNumberOfReturns(LAS_point);
                if (return_filter_is_out(&return_filter_struct, return_n, n_returns)) {
                    n_filtered++;
                    continue;
                }
                point_class = (int) LASPoint_GetClassification(LAS_point);
                if (class_filter_is_out(&class_filter, point_class))
                    continue;

                if (y <= region.south || y > region.north) {
                    continue;
                }
                if (x < region.west || x >= region.east) {
                    continue;
                }

                /* find the bin in the current array box */
		arr_row = (int)((region.north - y) / region.ns_res) - row0;
		if (arr_row < 0 || arr_row >= rows)
		    continue;
                arr_col = (int)((x - region.west) / region.ew_res);

                z = z * zscale;

                if (base_array) {
                    double base_z;
                    if (row_array_get_value_row_col(base_array, arr_row, arr_col,
                                                    cols, base_raster_data_type,
                                                    &base_z))
                        z -= base_z;
                    else
                        continue;
                }
                else if (use_segment) {
                    double base_z;
                    if (rast_segment_get_value_xy(&base_segment, &input_region,
                                                  base_raster_data_type, x, y,
                                                  &base_z))
                        z -= base_z;
                    else
                        continue;
                }

                if (zrange_opt->answer) {
                    if (z < zrange_min || z > zrange_max) {
                        continue;
                    }
                }

                if (intens_import_flag->answer || irange_opt->answer) {
                    intensity = LASPoint_GetIntensity(LAS_point);
                    intensity *= iscale;
                    if (irange_opt->answer) {
                        if (intensity < irange_min || intensity > irange_max) {
                            continue;
                        }
                    }
                    /* use intensity for statistics */
                    if (intens_import_flag->answer)
                        z = intensity;
                }

                count++;
                /*          G_debug(5, "x: %f, y: %f, z: %f", x, y, z); */

                update_value(&point_binning, &bin_index_nodes, cols,
                             arr_row, arr_col, rtype, x, y, z);
            }                        /* while !EOF of one input file */
            /* close input LAS file */
            LASReader_Destroy(LAS_reader);
        }           /* end of loop for all input files files */

	G_percent(1, 1, 1);	/* flush */
	G_debug(2, "pass %d finished, %lu coordinates in box", pass, count);
	count_total += count;
	line_total += line;

	/* calc stats and output */
	G_message(_("Writing to map ..."));
	for (row = 0; row < rows; row++) {
        /* potentially vector writing can be independent on the binning */
        write_values(&point_binning, &bin_index_nodes, raster_row, row,
            cols, rtype, NULL);
	    /* write out line of raster data */
        Rast_put_row(out_fd, raster_row, rtype);
	}

	/* free memory */
	point_binning_free(&point_binning, &bin_index_nodes);
    }				/* passes loop */
    if (base_array)
        Rast_close(base_raster);
    if (use_segment)
        Segment_close(&base_segment);

    G_percent(1, 1, 1);		/* flush */
    G_free(raster_row);

    /* close raster file & write history */
    Rast_close(out_fd);

    sprintf(title, "Raw X,Y,Z data binned into a raster grid by cell %s",
            method_opt->answer);
    Rast_put_cell_title(outmap, title);

    Rast_short_history(outmap, "raster", &history);
    Rast_command_history(&history);
    Rast_set_history(&history, HIST_DATSRC_1, infile);
    Rast_write_history(outmap, &history);

    /* set computation region to the new raster map */
    /* TODO: should be in the done message */
    if (set_region_flag->answer)
        G_put_window(&region);

    if (n_invalid && only_valid)
        G_message(_("%lu input points were invalid and filtered out"),
                  n_invalid);
    if (n_invalid && !only_valid)
        G_message(_("%lu input points were invalid, use -%c flag to filter"
                    " them out"), n_invalid, only_valid_flag->key);
    if (infiles.num_items > 1) {
        sprintf(buff, _("Raster map <%s> created."
                        " %lu points from %d files found in region."),
                outmap, count_total, infiles.num_items);
    }
    else {
        sprintf(buff, _("Raster map <%s> created."
                        " %lu points found in region."),
                outmap, count_total);
    }

    G_done_msg("%s", buff);
    G_debug(1, "Processed %lu points.", line_total);

    string_list_free(&infiles);

    exit(EXIT_SUCCESS);

}
Ejemplo n.º 4
0
int main(int argc, char **argv)
{
    int colorg = 0;
    int colorb = 0;
    int colort = 0;
    int colorbg = 0;
    double size = 0., gsize = 0.;       /* initialize to zero */
    double east, north;
    int do_text, fontsize, mark_type, line_width, dirn;
    struct GModule *module;
    struct Option *opt1, *opt2, *opt3, *opt4, *fsize, *tcolor, *lwidth,
        *direction, *bgcolor;
    struct Flag *noborder, *notext, *geogrid, *nogrid, *wgs84, *cross,
        *fiducial, *dot, *align;
    struct pj_info info_in;     /* Proj structures */
    struct pj_info info_out;    /* Proj structures */
    struct Cell_head wind;

    /* Initialize the GIS calls */
    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("display"));
    G_add_keyword(_("cartography"));
    G_add_keyword(_("graticule"));
    module->description =
        _("Overlays a user-specified grid "
          "in the active display frame on the graphics monitor.");

    opt2 = G_define_option();
    opt2->key = "size";
    opt2->key_desc = "value";
    opt2->type = TYPE_STRING;
    opt2->required = YES;
    opt2->label = _("Size of grid to be drawn (in map units)");
    opt2->description =
        _("0 for north-south resolution of the current region. "
          "In map units or DDD:MM:SS format. "
          "Example: \"1000\" or \"0:10\"");

    opt3 = G_define_standard_option(G_OPT_M_COORDS);
    opt3->key = "origin";
    opt3->answer = "0,0";
    opt3->multiple = NO;
    opt3->description = _("Lines of the grid pass through this coordinate");

    direction = G_define_option();
    direction->key = "direction";
    direction->type = TYPE_STRING;
    direction->required = NO;
    direction->answer = "both";
    direction->options = "both,east-west,north-south";
    direction->description =
        _("Draw only east-west lines, north-south lines, or both ");
    direction->guisection = _("Disable");

    lwidth = G_define_option();
    lwidth->key = "width";
    lwidth->type = TYPE_DOUBLE;
    lwidth->required = NO;
    lwidth->description = _("Grid line width");

    opt1 = G_define_standard_option(G_OPT_C);
    opt1->answer = "gray";
    opt1->label = _("Grid color");
    opt1->guisection = _("Color");

    opt4 = G_define_standard_option(G_OPT_C);
    opt4->key = "border_color";
    opt4->label = _("Border color");
    opt4->guisection = _("Color");

    tcolor = G_define_standard_option(G_OPT_C);
    tcolor->key = "text_color";
    tcolor->answer = "gray";
    tcolor->label = _("Text color");
    tcolor->guisection = _("Color");

    bgcolor = G_define_standard_option(G_OPT_CN);
    bgcolor->key = "bgcolor";
    bgcolor->answer = "none";
    bgcolor->label = _("Background color");
    bgcolor->guisection = _("Color");

    fsize = G_define_option();
    fsize->key = "fontsize";
    fsize->type = TYPE_INTEGER;
    fsize->required = NO;
    fsize->answer = "9";
    fsize->options = "1-72";
    fsize->description = _("Font size for gridline coordinate labels");

    align = G_define_flag();
    align->key = 'a';
    align->description =
        _("Align the origin to the east-north corner of the current region");

    geogrid = G_define_flag();
    geogrid->key = 'g';
    geogrid->description =
        _("Draw geographic grid (referenced to current ellipsoid)");
    geogrid->guisection = _("Draw");

    wgs84 = G_define_flag();
    wgs84->key = 'w';
    wgs84->description =
        _("Draw geographic grid (referenced to WGS84 ellipsoid)");
    wgs84->guisection = _("Draw");

    cross = G_define_flag();
    cross->key = 'c';
    cross->description = _("Draw '+' marks instead of grid lines");
    cross->guisection = _("Draw");

    dot = G_define_flag();
    dot->key = 'd';
    dot->description = _("Draw '.' marks instead of grid lines");
    dot->guisection = _("Draw");

    fiducial = G_define_flag();
    fiducial->key = 'f';
    fiducial->description = _("Draw fiducial marks instead of grid lines");
    fiducial->guisection = _("Draw");

    nogrid = G_define_flag();
    nogrid->key = 'n';
    nogrid->description = _("Disable grid drawing");
    nogrid->guisection = _("Disable");

    noborder = G_define_flag();
    noborder->key = 'b';
    noborder->description = _("Disable border drawing");
    noborder->guisection = _("Disable");

    notext = G_define_flag();
    notext->key = 't';
    notext->description = _("Disable text drawing");
    notext->guisection = _("Disable");

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


    /* do some checking */
    if (nogrid->answer && noborder->answer)
        G_fatal_error(_("Both grid and border drawing are disabled"));
    if (wgs84->answer)
        geogrid->answer = 1;    /* -w implies -g */
    if (geogrid->answer && G_projection() == PROJECTION_LL)
        G_fatal_error(_("Geo-grid option not available for LL projection, use without -g/-w"));
    if (geogrid->answer && G_projection() == PROJECTION_XY)
        G_fatal_error(_("Geo-grid option not available for XY projection, use without -g/-w"));

    if (notext->answer)
        do_text = FALSE;
    else
        do_text = TRUE;

    if (lwidth->answer) {
        line_width = atoi(lwidth->answer);
        if (line_width < 0 || line_width > 1e3)
            G_fatal_error("Invalid line width");
    }
    else
        line_width = 0;

    fontsize = atoi(fsize->answer);

    mark_type = MARK_GRID;
    if (cross->answer + fiducial->answer + dot->answer > 1)
        G_fatal_error(_("Choose a single mark style"));
    if (cross->answer)
        mark_type = MARK_CROSS;
    if (fiducial->answer)
        mark_type = MARK_FIDUCIAL;
    if (dot->answer)
        mark_type = MARK_DOT;

    if (G_strcasecmp(direction->answer, "both") == 0)
        dirn = DIRN_BOTH;
    else if (G_strcasecmp(direction->answer, "east-west") == 0)
        dirn = DIRN_LAT;
    else if (G_strcasecmp(direction->answer, "north-south") == 0)
        dirn = DIRN_LON;
    else
        G_fatal_error("Invalid direction: %s", direction->answer);

    if (align->answer || strcmp(opt2->answer, "0") == 0)
        G_get_element_window(&wind, "", "WIND", G_mapset());

    if (strcmp(opt2->answer, "0") == 0) {
        if (geogrid->answer)
            gsize = wind.ns_res;
        else
            size = wind.ns_res;
    }
    else {
        /* get grid size */
        if (geogrid->answer) {
            if (!G_scan_resolution(opt2->answer, &gsize, PROJECTION_LL) ||
                gsize <= 0.0)
                G_fatal_error(_("Invalid geo-grid size <%s>"), opt2->answer);
        }
        else {
            if (!G_scan_resolution(opt2->answer, &size, G_projection()) ||
                size <= 0.0)
                G_fatal_error(_("Invalid grid size <%s>"), opt2->answer);
        }
    }

    if (align->answer) {
        /* reduce accumulated errors when ew_res is not the same as ns_res. */
        struct Cell_head w;

        G_get_set_window(&w);
        east =
            wind.west +
            (int)((w.west - wind.west) / wind.ew_res) * wind.ew_res;
        north =
            wind.south +
            (int)((w.south - wind.south) / wind.ns_res) * wind.ns_res;
    }
    else {
        /* get grid easting start */
        if (!G_scan_easting(opt3->answers[0], &east, G_projection())) {
            G_usage();
            G_fatal_error(_("Illegal east coordinate <%s>"),
                          opt3->answers[0]);
        }

        /* get grid northing start */
        if (!G_scan_northing(opt3->answers[1], &north, G_projection())) {
            G_usage();
            G_fatal_error(_("Illegal north coordinate <%s>"),
                          opt3->answers[1]);
        }
    }

    /* Setup driver and check important information */
    D_open_driver();

    /* Parse and select grid color */
    colorg = D_parse_color(opt1->answer, FALSE);
    /* Parse and select border color */
    colorb = D_parse_color(opt4->answer, FALSE);
    /* Parse and select text color */
    colort = D_parse_color(tcolor->answer, FALSE);
    /* Parse and select background color */
    colorbg = D_parse_color(bgcolor->answer, TRUE);


    D_setup(0);

    /* draw grid */
    if (!nogrid->answer) {
        if (geogrid->answer) {
            /* initialzie proj stuff */
            init_proj(&info_in, &info_out, wgs84->answer);
            plot_geogrid(gsize, info_in, info_out, do_text, colorg, colort,
                         colorbg, fontsize, mark_type, line_width, dirn);
        }
        else {
            /* Do the grid plotting */
            plot_grid(size, east, north, do_text, colorg, colort, colorbg,
                      fontsize, mark_type, line_width, dirn);
        }
    }

    /* Draw border */
    if (!noborder->answer) {
        /* Set border color */
        D_use_color(colorb);

        /* Do the border plotting */
        plot_border(size, east, north, dirn);
    }

    D_save_command(G_recreate_command());
    D_close_driver();

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 5
0
Archivo: main.c Proyecto: caomw/grass
int main(int argc, char *argv[])
{

    /* loop */
    int i, j;

    /* store filename and path  */
    char *dig_file;
    
    char buf[2000];

    /* Other local variables */
    int attCount, nbreaks;

    struct grid_description grid_info;
    struct Cell_head window;
    struct Map_info Map;
    struct Option *vectname, *grid, *coord, *box, *angle, *position_opt, *breaks;
    struct GModule *module;
    struct Flag *points_fl, *line_fl;
    int points_p, line_p, output_type;
    char *desc;

    struct line_pnts *Points;
    struct line_cats *Cats;

    /* Attributes */
    struct field_info *Fi;
    dbDriver *Driver;
    dbString sql;

    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("geometry"));
    module->description = _("Creates a vector map of a user-defined grid.");

    vectname = G_define_standard_option(G_OPT_V_OUTPUT);
    vectname->key = "map";

    grid = G_define_option();
    grid->key = "grid";
    grid->key_desc = _("rows,columns");
    grid->type = TYPE_INTEGER;
    grid->required = YES;
    grid->multiple = NO;
    grid->description = _("Number of rows and columns in grid");

    position_opt = G_define_option();
    position_opt->key = "position";
    position_opt->type = TYPE_STRING;
    position_opt->required = NO;
    position_opt->multiple = NO;
    position_opt->options = "region,coor";
    position_opt->answer = "region";
    position_opt->description = _("Where to place the grid");
    desc = NULL;
    G_asprintf(&desc,
            "region;%s;coor;%s",
            _("current region"),
            _("use 'coor' and 'box' options"));
    position_opt->descriptions = desc;

    coord = G_define_option();
    coord->key = "coor";
    coord->key_desc = "x,y";
    coord->type = TYPE_DOUBLE;
    coord->required = NO;
    coord->multiple = NO;
    coord->description =
	_("Lower left easting and northing coordinates of map");

    box = G_define_option();
    box->key = "box";
    box->key_desc = _("width,height");
    box->type = TYPE_DOUBLE;
    box->required = NO;
    box->multiple = NO;
    box->description = _("Width and height of boxes in grid");

    angle = G_define_option();
    angle->key = "angle";
    angle->type = TYPE_DOUBLE;
    angle->required = NO;
    angle->description =
	_("Angle of rotation (in degrees counter-clockwise)");
    angle->answer = "0";

    breaks = G_define_option();
    breaks->key = "breaks";
    breaks->type = TYPE_INTEGER;
    breaks->required = NO;
    breaks->description =
	_("Number of vertex points per grid cell");
    breaks->options = "0-60";
    breaks->answer = "3";

    points_fl = G_define_flag();
    points_fl->key = 'p';
    points_fl->description =
	_("Create grid of points instead of areas and centroids");

    line_fl = G_define_flag();
    line_fl->key = 'l';
    line_fl->description =
	_("Create grid as lines, instead of areas");

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

    line_p = line_fl->answer;
    if (line_p) {
	output_type = GV_LINE;
    } else {
	output_type = GV_BOUNDARY;
    }

    points_p = points_fl->answer;

    /* get the current window  */
    G_get_window(&window);

    /*
     * information we need to collect from user: origin point x and y (lower
     * left), shift in x, shift in y,  number of rows, number of cols
     */
    dig_file = G_store(vectname->answer);

    /* Number of row and cols */
    grid_info.num_rows = atoi(grid->answers[0]);
    grid_info.num_cols = atoi(grid->answers[1]);

    grid_info.angle = M_PI / 180 * atof(angle->answer);

    nbreaks = atoi(breaks->answer);

    /* Position */
    if (position_opt->answer[0] == 'r') {	/* region */
	if (coord->answer)
	    G_fatal_error(_("'coor' and 'position=region' are exclusive options"));

	if (box->answer)
	    G_fatal_error(_("'box' and 'position=region' are exclusive options"));

	if (grid_info.angle != 0.0)
	    G_fatal_error(_("'angle' and 'position=region' are exclusive options"));

	grid_info.origin_x = window.west;
	grid_info.origin_y = window.south;

	grid_info.length = (window.east - window.west) / grid_info.num_cols;
	grid_info.width = (window.north - window.south) / grid_info.num_rows;

	G_debug(2, "x = %e y = %e l = %e w = %e", grid_info.origin_x,
		grid_info.origin_y, grid_info.length, grid_info.width);
    }
    else {
	if (!coord->answer)
	    G_fatal_error(_("'coor' option missing"));

	if (!box->answer)
	    G_fatal_error(_("'box' option missing"));

	if (!G_scan_easting
	    (coord->answers[0], &(grid_info.origin_x), window.proj))
	    G_fatal_error(_("Invalid easting"));;
	if (!G_scan_northing
	    (coord->answers[1], &(grid_info.origin_y), window.proj))
	    G_fatal_error(_("Invalid northing"));;

	if (!G_scan_resolution
	    (box->answers[0], &(grid_info.length), window.proj))
	    G_fatal_error(_("Invalid distance"));;
	if (!G_scan_resolution
	    (box->answers[1], &(grid_info.width), window.proj))
	    G_fatal_error(_("Invalid distance"));;

    }

    /*
     * vector rows are the actual number of rows of vectors to make up the
     * entire grid.   ditto for cols.
     */
    grid_info.num_vect_rows = grid_info.num_rows + 1;
    grid_info.num_vect_cols = grid_info.num_cols + 1;

    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();
    db_init_string(&sql);

    /* Open output map */
    if (0 > Vect_open_new(&Map, dig_file, 0)) {
	G_fatal_error(_("Unable to create vector map <%s>"), dig_file);
    }

    Vect_hist_command(&Map);

    /* Open database, create table */
    Fi = Vect_default_field_info(&Map, 1, NULL, GV_1TABLE);
    Vect_map_add_dblink(&Map, Fi->number, Fi->name, Fi->table, Fi->key,
			Fi->database, Fi->driver);

    Driver =
	db_start_driver_open_database(Fi->driver,
				      Vect_subst_var(Fi->database, &Map));
    if (Driver == NULL)
	G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
		      Fi->database, Fi->driver);
    db_set_error_handler_driver(Driver);

    if (grid_info.num_rows < 27 && grid_info.num_cols < 27) {
	sprintf(buf,
		"create table %s ( cat integer, row integer, col integer, "
		"rown varchar(1), coln varchar(1))", Fi->table);
    }
    else {
	sprintf(buf,
		"create table %s ( cat integer, row integer, col integer)",
		Fi->table);
    }
    db_set_string(&sql, buf);

    G_debug(1, "SQL: %s", db_get_string(&sql));

    if (db_execute_immediate(Driver, &sql) != DB_OK) {
	G_fatal_error(_("Unable to create table: %s"), db_get_string(&sql));
    }

    if (db_create_index2(Driver, Fi->table, Fi->key) != DB_OK)
	G_warning(_("Unable to create index"));

    if (db_grant_on_table
	(Driver, Fi->table, DB_PRIV_SELECT, DB_GROUP | DB_PUBLIC) != DB_OK)
	G_fatal_error(_("Unable to grant privileges on table <%s>"),
		      Fi->table);

    if (!points_p) {
	/* create areas */
	write_grid(&grid_info, &Map, nbreaks, output_type);
    }

    /* Create a grid of label points at the centres of the grid cells */
    G_verbose_message(_("Creating centroids..."));

    /* Write out centroids and attributes */
    /* If the output id is lines it skips to add centroids and attributes
       TODO decide what to write in the attribute table
     */
    if (!line_p) {
      db_begin_transaction(Driver);
      attCount = 0;
      for (i = 0; i < grid_info.num_rows; ++i) {
	  for (j = 0; j < grid_info.num_cols; ++j) {
	      double x, y;
	      const int point_type = points_p ? GV_POINT : GV_CENTROID;

	      x = grid_info.origin_x + (0.5 + j) * grid_info.length;
	      y = grid_info.origin_y + (0.5 + i) * grid_info.width;

	      rotate(&x, &y, grid_info.origin_x, grid_info.origin_y,
		    grid_info.angle);

	      Vect_reset_line(Points);
	      Vect_reset_cats(Cats);

	      Vect_append_point(Points, x, y, 0.0);
	      Vect_cat_set(Cats, 1, attCount + 1);
	      Vect_write_line(&Map, point_type, Points, Cats);

	      sprintf(buf, "insert into %s values ", Fi->table);
	      if (db_set_string(&sql, buf) != DB_OK)
		  G_fatal_error(_("Unable to fill attribute table"));

	      if (grid_info.num_rows < 27 && grid_info.num_cols < 27) {
		  sprintf(buf,
			  "( %d, %d, %d, '%c', '%c' )",
			  attCount + 1, grid_info.num_rows - i,
			  j + 1, 'A' + grid_info.num_rows - i - 1, 'A' + j);
	      }
	      else {
		  sprintf(buf, "( %d, %d, %d )",
			  attCount + 1, i + 1, j + 1);
	      }
	      if (db_append_string(&sql, buf) != DB_OK)
		      G_fatal_error(_("Unable to fill attribute table"));

	      G_debug(3, "SQL: %s", db_get_string(&sql));

	      if (db_execute_immediate(Driver, &sql) != DB_OK) {
		  G_fatal_error(_("Unable to insert new record: %s"),
			      db_get_string(&sql));
	      }
	      attCount++;
	  }
      }
    }
    db_commit_transaction(Driver);

    db_close_database_shutdown_driver(Driver);

    Vect_build(&Map);
    Vect_close(&Map);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 6
0
int E_edit_cellhd(struct Cell_head *cellhd, int type)
{
    char ll_north[20];
    char ll_south[20];
    char ll_east[20];
    char ll_west[20];
    char ll_nsres[20];
    char ll_ewres[20];
    char ll_def_north[20];
    char ll_def_south[20];
    char ll_def_east[20];
    char ll_def_west[20];
    char ll_def_ewres[20];
    char ll_def_nsres[20];
    char projection[80];
    char **screen;

    struct Cell_head def_wind;
    double north, south, east, west;
    double nsres, ewres;
    char buf[64], buf2[30], *p;
    short ok;
    int line;
    char *prj;
    char *err;

    if (type == AS_CELLHD && (cellhd->rows <= 0 || cellhd->cols <= 0)) {
	G_message("E_edit_cellhd() - programmer error");
	G_message("  ** rows and cols must be positive **");
	return -1;
    }
    if (type != AS_DEF_WINDOW) {
	if (G_get_default_window(&def_wind) != 1)
	    return -1;

	if (cellhd->proj < 0) {
	    cellhd->proj = def_wind.proj;
	    cellhd->zone = def_wind.zone;
	}
	else if (cellhd->zone < 0)
	    cellhd->zone = def_wind.zone;
    }

    prj = G__projection_name(cellhd->proj);
    if (!prj)
	prj = "** unknown **";
    sprintf(projection, "%d (%s)", cellhd->proj, prj);

    if (type != AS_DEF_WINDOW) {
	if (cellhd->west >= cellhd->east || cellhd->south >= cellhd->north) {
	    cellhd->north = def_wind.north;
	    cellhd->south = def_wind.south;
	    cellhd->west = def_wind.west;
	    cellhd->east = def_wind.east;

	    if (type != AS_CELLHD) {
		cellhd->ew_res = def_wind.ew_res;
		cellhd->ns_res = def_wind.ns_res;
		cellhd->rows = def_wind.rows;
		cellhd->cols = def_wind.cols;
	    }
	}

	if (cellhd->proj != def_wind.proj) {
	    if (type == AS_CELLHD)
		G_message
		    ("header projection %d differs from default projection %d",
		     cellhd->proj, def_wind.proj);
	    else
		G_message
		    ("region projection %d differs from default projection %d",
		     cellhd->proj, def_wind.proj);

	    if (!G_yes("do you want to make them match? ", 1))
		return -1;

	    cellhd->proj = def_wind.proj;
	    cellhd->zone = def_wind.zone;
	}

	if (cellhd->zone != def_wind.zone) {
	    if (type == AS_CELLHD)
		G_message("header zone %d differs from default zone %d",
			  cellhd->zone, def_wind.zone);
	    else
		G_message("region zone %d differs from default zone %d",
			  cellhd->zone, def_wind.zone);

	    if (!G_yes("do you want to make them match? ", 1))
		return -1;

	    cellhd->zone = def_wind.zone;
	}

	*ll_def_north = 0;
	*ll_def_south = 0;
	*ll_def_east = 0;
	*ll_def_west = 0;
	*ll_def_ewres = 0;
	*ll_def_nsres = 0;
	format_northing(def_wind.north, ll_def_north, def_wind.proj);
	format_northing(def_wind.south, ll_def_south, def_wind.proj);
	format_easting(def_wind.east, ll_def_east, def_wind.proj);
	format_easting(def_wind.west, ll_def_west, def_wind.proj);
	format_resolution(def_wind.ew_res, ll_def_ewres, def_wind.proj);
	format_resolution(def_wind.ns_res, ll_def_nsres, def_wind.proj);
    }

    *ll_north = 0;
    *ll_south = 0;
    *ll_east = 0;
    *ll_west = 0;
    *ll_ewres = 0;
    *ll_nsres = 0;
    format_northing(cellhd->north, ll_north, cellhd->proj);
    format_northing(cellhd->south, ll_south, cellhd->proj);
    format_easting(cellhd->east, ll_east, cellhd->proj);
    format_easting(cellhd->west, ll_west, cellhd->proj);
    format_resolution(cellhd->ew_res, ll_ewres, cellhd->proj);
    format_resolution(cellhd->ns_res, ll_nsres, cellhd->proj);

    while (1) {
	ok = 1;

	/* List window options on the screen for the user to answer */
	switch (type) {
	case AS_CELLHD:
	    screen = cellhd_screen;
	    break;
	case AS_DEF_WINDOW:
	    screen = def_window_screen;
	    break;
	default:
	    screen = window_screen;
	    break;
	}

	V_clear();
	line = 0;
	while (*screen)
	    V_line(line++, *screen++);

	/* V_ques ( variable, type, row, col, length) ; */
	V_ques(ll_north, 's', 6, 36, 10);
	V_ques(ll_south, 's', 10, 36, 10);
	V_ques(ll_west, 's', 9, 12, 10);
	V_ques(ll_east, 's', 9, 52, 10);

	if (type != AS_CELLHD) {
	    V_ques(ll_ewres, 's', 18, 48, 10);
	    V_ques(ll_nsres, 's', 19, 48, 10);
	}

	if (type != AS_DEF_WINDOW) {
	    V_const(ll_def_north, 's', 3, 36, 10);
	    V_const(ll_def_south, 's', 13, 36, 10);
	    V_const(ll_def_west, 's', 9, 1, 10);
	    V_const(ll_def_east, 's', 9, 65, 10);

	    if (type != AS_CELLHD) {
		V_const(ll_def_ewres, 's', 18, 21, 10);
		V_const(ll_def_nsres, 's', 19, 21, 10);
	    }
	}

	V_const(projection, 's', 15, 23, (int)strlen(projection));
	V_const(&cellhd->zone, 'i', 15, 60, 3);

	V_intrpt_ok();
	if (!V_call())
	    return -1;

	G_squeeze(ll_north);
	G_squeeze(ll_south);
	G_squeeze(ll_east);
	G_squeeze(ll_west);

	if (type != AS_CELLHD) {
	    G_squeeze(ll_ewres);
	    G_squeeze(ll_nsres);
	}

	if (!G_scan_northing(ll_north, &cellhd->north, cellhd->proj)) {
	    G_warning("Illegal value for north: %s", ll_north);
	    ok = 0;
	}

	if (!G_scan_northing(ll_south, &cellhd->south, cellhd->proj)) {
	    G_warning("Illegal value for south: %s", ll_south);
	    ok = 0;
	}

	if (!G_scan_easting(ll_east, &cellhd->east, cellhd->proj)) {
	    G_warning("Illegal value for east: %s", ll_east);
	    ok = 0;
	}

	if (!G_scan_easting(ll_west, &cellhd->west, cellhd->proj)) {
	    G_warning("Illegal value for west: %s", ll_west);
	    ok = 0;
	}

	if (type != AS_CELLHD) {
	    if (!G_scan_resolution(ll_ewres, &cellhd->ew_res, cellhd->proj)) {
		G_warning("Illegal east-west resolution: %s", ll_ewres);
		ok = 0;
	    }

	    if (!G_scan_resolution(ll_nsres, &cellhd->ns_res, cellhd->proj)) {
		G_warning("Illegal north-south resolution: %s", ll_nsres);
		ok = 0;
	    }
	}

	if (!ok) {
	    hitreturn();
	    continue;
	}

	/* Adjust and complete the cell header */
	north = cellhd->north;
	south = cellhd->south;
	east = cellhd->east;
	west = cellhd->west;
	nsres = cellhd->ns_res;
	ewres = cellhd->ew_res;

	if ((err =
	     G_adjust_Cell_head(cellhd, type == AS_CELLHD,
				type == AS_CELLHD))) {
	    G_message("%s", err);
	    hitreturn();
	    continue;
	}

	if (type == AS_CELLHD) {
	    nsres = cellhd->ns_res;
	    ewres = cellhd->ew_res;
	}

      SHOW:
	fprintf(stderr, "\n\n");
	G_message("  projection:   %s", projection);
	G_message("  zone:         %d", cellhd->zone);

	G_format_northing(cellhd->north, buf, cellhd->proj);
	G_format_northing(north, buf2, cellhd->proj);
	fprintf(stderr, "  north:       %s", buf);

	if (strcmp(buf, buf2) != 0) {
	    ok = 0;
	    fprintf(stderr, "  (Changed to match resolution)");
	}
	fprintf(stderr, "\n");

	G_format_northing(cellhd->south, buf, cellhd->proj);
	G_format_northing(south, buf2, cellhd->proj);
	fprintf(stderr, "  south:       %s", buf);
	if (strcmp(buf, buf2) != 0) {
	    ok = 0;
	    fprintf(stderr, "  (Changed to match resolution)");
	}
	fprintf(stderr, "\n");

	G_format_easting(cellhd->east, buf, cellhd->proj);
	G_format_easting(east, buf2, cellhd->proj);
	fprintf(stderr, "  east:        %s", buf);
	if (strcmp(buf, buf2) != 0) {
	    ok = 0;
	    fprintf(stderr, "  (Changed to match resolution)");
	}
	fprintf(stderr, "\n");

	G_format_easting(cellhd->west, buf, cellhd->proj);
	G_format_easting(west, buf2, cellhd->proj);
	fprintf(stderr, "  west:        %s", buf);
	if (strcmp(buf, buf2) != 0) {
	    ok = 0;
	    fprintf(stderr, "  (Changed to match resolution)");
	}
	fprintf(stderr, "\n\n");

	G_format_resolution(cellhd->ew_res, buf, cellhd->proj);
	G_format_resolution(ewres, buf2, cellhd->proj);
	fprintf(stderr, "  e-w res:     %s", buf);
	if (strcmp(buf, buf2) != 0) {
	    ok = 0;
	    fprintf(stderr, "  (Changed to conform to grid)");
	}
	fprintf(stderr, "\n");

	G_format_resolution(cellhd->ns_res, buf, cellhd->proj);
	G_format_resolution(nsres, buf2, cellhd->proj);
	fprintf(stderr, "  n-s res:     %s", buf);
	if (strcmp(buf, buf2) != 0) {
	    ok = 0;
	    fprintf(stderr, "  (Changed to conform to grid)");
	}
	fprintf(stderr, "\n\n");

	G_message("  total rows:  %15d", cellhd->rows);
	G_message("  total cols:  %15d", cellhd->cols);

	sprintf(buf, "%lf", (double)cellhd->rows * cellhd->cols);
	*(p = strchr(buf, '.')) = 0;
	G_insert_commas(buf);
	G_message("  total cells: %15s", buf);
	fprintf(stderr, "\n");

	if (type != AS_DEF_WINDOW) {
	    if (cellhd->north > def_wind.north) {
		G_warning("north falls outside the default region");
		ok = 0;
	    }

	    if (cellhd->south < def_wind.south) {
		G_warning("south falls outside the default region");
		ok = 0;
	    }

	    if (cellhd->proj != PROJECTION_LL) {
		if (cellhd->east > def_wind.east) {
		    G_warning("east falls outside the default region");
		    ok = 0;
		}

		if (cellhd->west < def_wind.west) {
		    G_warning("west falls outside the default region");
		    ok = 0;
		}
	    }
	}

      ASK:
	fflush(stdin);
	if (type == AS_CELLHD)
	    fprintf(stderr, "\nDo you accept this header? (y/n) [%s] > ",
		    ok ? "y" : "n");
	else
	    fprintf(stderr, "\nDo you accept this region? (y/n) [%s] > ",
		    ok ? "y" : "n");

	if (!G_gets(buf))
	    goto SHOW;

	G_strip(buf);
	switch (*buf) {
	case 0:
	    break;
	case 'y':
	case 'Y':
	    ok = 1;
	    break;
	case 'n':
	case 'N':
	    ok = 0;
	    break;
	default:
	    goto ASK;
	}

	if (ok)
	    return 0;
    }
}
Ejemplo n.º 7
0
Archivo: main.c Proyecto: caomw/grass
int main(int argc, char *argv[])
{
    int i;
    double x;
    struct Cell_head cellhd, window;
    const char *value;
    const char *name;

    struct GModule *module;
    struct
    {
	struct Flag *dflt, *cur;
    } flag;
    struct
    {
	struct Option
	    *map,
	    *north, *south, *east, *west,
	    *raster, *vect, *region, *align;
    } parm;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("metadata"));
    module->description =
	_("Sets the boundary definitions for a raster map.");

    /* flags */

    flag.cur = G_define_flag();
    flag.cur->key = 'c';
    flag.cur->description = _("Set from current region");
    flag.cur->guisection = _("Existing");

    flag.dflt = G_define_flag();
    flag.dflt->key = 'd';
    flag.dflt->description = _("Set from default region");
    flag.dflt->guisection = _("Existing");

    /* parameters */

    parm.map = G_define_standard_option(G_OPT_R_MAP);
    parm.map->description = _("Name of raster map to change");

    parm.region = G_define_option();
    parm.region->key = "region";
    parm.region->key_desc = "name";
    parm.region->required = NO;
    parm.region->multiple = NO;
    parm.region->type = TYPE_STRING;
    parm.region->description = _("Set region from named region");
    parm.region->gisprompt = "old,windows,region";
    parm.region->guisection = _("Existing");
    
    parm.raster = G_define_standard_option(G_OPT_R_MAP);
    parm.raster->key = "raster";
    parm.raster->required = NO;
    parm.raster->multiple = NO;
    parm.raster->description = _("Set region to match this raster map");
    parm.raster->guisection = _("Existing");

    parm.vect = G_define_standard_option(G_OPT_V_MAP);
    parm.vect->key = "vector";
    parm.vect->required = NO;
    parm.vect->multiple = NO;
    parm.vect->description = _("Set region to match this vector map");
    parm.vect->guisection = _("Existing");

    parm.north = G_define_option();
    parm.north->key = "n";
    parm.north->key_desc = "value";
    parm.north->required = NO;
    parm.north->multiple = NO;
    parm.north->type = TYPE_STRING;
    parm.north->description = _("Value for the northern edge");
    parm.north->guisection = _("Bounds");

    parm.south = G_define_option();
    parm.south->key = "s";
    parm.south->key_desc = "value";
    parm.south->required = NO;
    parm.south->multiple = NO;
    parm.south->type = TYPE_STRING;
    parm.south->description = _("Value for the southern edge");
    parm.south->guisection = _("Bounds");

    parm.east = G_define_option();
    parm.east->key = "e";
    parm.east->key_desc = "value";
    parm.east->required = NO;
    parm.east->multiple = NO;
    parm.east->type = TYPE_STRING;
    parm.east->description = _("Value for the eastern edge");
    parm.east->guisection = _("Bounds");

    parm.west = G_define_option();
    parm.west->key = "w";
    parm.west->key_desc = "value";
    parm.west->required = NO;
    parm.west->multiple = NO;
    parm.west->type = TYPE_STRING;
    parm.west->description = _("Value for the western edge");
    parm.west->guisection = _("Bounds");
    
    parm.align = G_define_standard_option(G_OPT_R_MAP);
    parm.align->key = "align";
    parm.align->required = NO;
    parm.align->multiple = NO;
    parm.align->description = _("Raster map to align to");
    parm.align->guisection = _("Existing");

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

    G_get_window(&window);

    name = parm.map->answer;

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

    window = cellhd;

    if (flag.dflt->answer)
	G_get_default_window(&window);

    if (flag.cur->answer)
	G_get_window(&window);

    if ((name = parm.region->answer))	/* region= */
	G__get_window(&window, "windows", name, "");

    if ((name = parm.raster->answer)) {	/* raster= */
	Rast_get_cellhd(name, "", &window);
    }

    if ((name = parm.vect->answer)) {	/* vect= */
	struct Map_info Map;
	struct bound_box box;

	Vect_set_open_level(1);
	if (Vect_open_old(&Map, name, "") != 1)
	    G_fatal_error(_("Unable to open vector map <%s>"), name);

	Vect_get_map_box(&Map, &box);
	window.north = box.N;
	window.south = box.S;
	window.west = box.W;
	window.east = box.E;

	Rast_align_window(&window, &cellhd);

	Vect_close(&Map);
    }

    if ((value = parm.north->answer)) {	/* n= */
	if ((i = nsew(value, "n+", "n-", "s+"))) {
	    if (!G_scan_resolution(value + 2, &x, window.proj))
		die(parm.north);
	    switch (i) {
	    case 1:
		window.north += x;
		break;
	    case 2:
		window.north -= x;
		break;
	    case 3:
		window.north = window.south + x;
		break;
	    }
	}
	else if (G_scan_northing(value, &x, window.proj))
	    window.north = x;
	else
	    die(parm.north);
    }

    if ((value = parm.south->answer)) {	/* s= */
	if ((i = nsew(value, "s+", "s-", "n-"))) {
	    if (!G_scan_resolution(value + 2, &x, window.proj))
		die(parm.south);
	    switch (i) {
	    case 1:
		window.south += x;
		break;
	    case 2:
		window.south -= x;
		break;
	    case 3:
		window.south = window.north - x;
		break;
	    }
	}
	else if (G_scan_northing(value, &x, window.proj))
	    window.south = x;
	else
	    die(parm.south);
    }

    if ((value = parm.east->answer)) {	/* e= */
	if ((i = nsew(value, "e+", "e-", "w+"))) {
	    if (!G_scan_resolution(value + 2, &x, window.proj))
		die(parm.east);
	    switch (i) {
	    case 1:
		window.east += x;
		break;
	    case 2:
		window.east -= x;
		break;
	    case 3:
		window.east = window.west + x;
		break;
	    }
	}
	else if (G_scan_easting(value, &x, window.proj))
	    window.east = x;
	else
	    die(parm.east);
    }

    if ((value = parm.west->answer)) {	/* w= */
	if ((i = nsew(value, "w+", "w-", "e-"))) {
	    if (!G_scan_resolution(value + 2, &x, window.proj))
		die(parm.west);
	    switch (i) {
	    case 1:
		window.west += x;
		break;
	    case 2:
		window.west -= x;
		break;
	    case 3:
		window.west = window.east - x;
		break;
	    }
	}
	else if (G_scan_easting(value, &x, window.proj))
	    window.west = x;
	else
	    die(parm.west);
    }

    if ((name = parm.align->answer)) {	/* align= */
	struct Cell_head temp_window;

	Rast_get_cellhd(name, "", &temp_window);

	Rast_align_window(&window, &temp_window);
    }

    window.rows = cellhd.rows;
    window.cols = cellhd.cols;

    G_adjust_Cell_head(&window, 1, 1);

    cellhd.north = window.north;
    cellhd.south = window.south;
    cellhd.east = window.east;
    cellhd.west = window.west;

    Rast_put_cellhd(parm.map->answer, &cellhd);

    G_done_msg(" ");

    return 0;
}
Ejemplo n.º 8
0
int main(int argc, char **argv)
{
    int colorg = 0;
    int colorb = 0;
    int colort = 0;
    double size = 0., gsize = 0.;	/* initialize to zero */
    double east, north;
    int do_text, fontsize, mark_type, line_width;
    struct GModule *module;
    struct Option *opt1, *opt2, *opt3, *opt4, *fsize, *tcolor, *lwidth;
    struct Flag *noborder, *notext, *geogrid, *nogrid, *wgs84, *cross,
	*fiducial, *dot;
    struct pj_info info_in;	/* Proj structures */
    struct pj_info info_out;	/* Proj structures */

    /* Initialize the GIS calls */
    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("display, cartography");
    module->description =
	_("Overlays a user-specified grid "
	  "in the active display frame on the graphics monitor.");

    opt2 = G_define_option();
    opt2->key = "size";
    opt2->key_desc = "value";
    opt2->type = TYPE_STRING;
    opt2->required = YES;
    opt2->label = _("Size of grid to be drawn");
    opt2->description = _("In map units or DDD:MM:SS format. "
			  "Example: \"1000\" or \"0:10\"");

    opt3 = G_define_option();
    opt3->key = "origin";
    opt3->type = TYPE_STRING;
    opt3->key_desc = "easting,northing";
    opt3->answer = "0,0";
    opt3->multiple = NO;
    opt3->description = _("Lines of the grid pass through this coordinate");

    lwidth = G_define_option();
    lwidth->key = "width";
    lwidth->type = TYPE_DOUBLE;
    lwidth->required = NO;
    lwidth->description = _("Grid line width");

    opt1 = G_define_standard_option(G_OPT_C_FG);
    opt1->answer = "gray";
    opt1->label = _("Grid color");
    opt1->guisection = _("Color");

    opt4 = G_define_standard_option(G_OPT_C_FG);
    opt4->key = "bordercolor";
    opt4->label = _("Border color");
    opt4->guisection = _("Color");

    tcolor = G_define_standard_option(G_OPT_C_FG);
    tcolor->key = "textcolor";
    tcolor->answer = "gray";
    tcolor->label = _("Text color");
    tcolor->guisection = _("Color");

    fsize = G_define_option();
    fsize->key = "fontsize";
    fsize->type = TYPE_INTEGER;
    fsize->required = NO;
    fsize->answer = "9";
    fsize->options = "1-72";
    fsize->description = _("Font size for gridline coordinate labels");

    geogrid = G_define_flag();
    geogrid->key = 'g';
    geogrid->description =
	_("Draw geographic grid (referenced to current ellipsoid)");

    wgs84 = G_define_flag();
    wgs84->key = 'w';
    wgs84->description =
	_("Draw geographic grid (referenced to WGS84 ellipsoid)");

    cross = G_define_flag();
    cross->key = 'c';
    cross->description = _("Draw '+' marks instead of grid lines");

    dot = G_define_flag();
    dot->key = 'd';
    dot->description = _("Draw '.' marks instead of grid lines");

    fiducial = G_define_flag();
    fiducial->key = 'f';
    fiducial->description = _("Draw fiducial marks instead of grid lines");

    nogrid = G_define_flag();
    nogrid->key = 'n';
    nogrid->description = _("Disable grid drawing");
    nogrid->guisection = _("Disable");

    noborder = G_define_flag();
    noborder->key = 'b';
    noborder->description = _("Disable border drawing");
    noborder->guisection = _("Disable");

    notext = G_define_flag();
    notext->key = 't';
    notext->description = _("Disable text drawing");
    notext->guisection = _("Disable");

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


    /* do some checking */
    if (nogrid->answer && noborder->answer)
	G_fatal_error(_("Both grid and border drawing are disabled"));
    if (wgs84->answer)
	geogrid->answer = 1;	/* -w implies -g */
    if (geogrid->answer && G_projection() == PROJECTION_LL)
	G_fatal_error(_("Geo-Grid option is not available for LL projection"));
    if (geogrid->answer && G_projection() == PROJECTION_XY)
	G_fatal_error(_("Geo-Grid option is not available for XY projection"));

    if (notext->answer)
	do_text = FALSE;
    else
	do_text = TRUE;

    if (lwidth->answer) {
	line_width = atoi(lwidth->answer);
	if(line_width < 0 || line_width > 1e3)
	    G_fatal_error("Invalid line width.");
    }
    else
	line_width = 0;

    fontsize = atoi(fsize->answer);

    mark_type = MARK_GRID;
    if (cross->answer + fiducial->answer + dot->answer > 1)
	G_fatal_error(_("Choose a single mark style"));
    if (cross->answer)
	mark_type = MARK_CROSS;
    if (fiducial->answer)
	mark_type = MARK_FIDUCIAL;
    if (dot->answer)
	mark_type = MARK_DOT;

    /* get grid size */
    if (geogrid->answer) {
	if (!G_scan_resolution(opt2->answer, &gsize, PROJECTION_LL) ||
	    gsize <= 0.0)
	    G_fatal_error(_("Invalid geo-grid size <%s>"), opt2->answer);
    }
    else {
	if (!G_scan_resolution(opt2->answer, &size, G_projection()) ||
	    size <= 0.0)
	    G_fatal_error(_("Invalid grid size <%s>"), opt2->answer);
    }

    /* get grid easting start */
    if (!G_scan_easting(opt3->answers[0], &east, G_projection())) {
	G_usage();
	G_fatal_error(_("Illegal east coordinate <%s>"), opt3->answers[0]);
    }

    /* get grid northing start */
    if (!G_scan_northing(opt3->answers[1], &north, G_projection())) {
	G_usage();
	G_fatal_error(_("Illegal north coordinate <%s>"), opt3->answers[1]);
    }

    /* Setup driver and check important information */
    if (R_open_driver() != 0)
	G_fatal_error(_("No graphics device selected"));


    /* Parse and select grid color */
    colorg = D_parse_color(opt1->answer, FALSE);
    /* Parse and select border color */
    colorb = D_parse_color(opt4->answer, FALSE);
    /* Parse and select text color */
    colort = D_parse_color(tcolor->answer, FALSE);


    D_setup(0);

    /* draw grid */
    if (!nogrid->answer) {
	if (geogrid->answer) {
	    /* initialzie proj stuff */
	    init_proj(&info_in, &info_out, wgs84->answer);
	    plot_geogrid(gsize, info_in, info_out, do_text, colorg, colort,
			 fontsize, mark_type, line_width);
	}
	else {
	    /* Do the grid plotting */
	    plot_grid(size, east, north, do_text, colorg, colort, fontsize,
		      mark_type, line_width);
	}
    }

    /* Draw border */
    if (!noborder->answer) {
	/* Set border color */
	D_raster_use_color(colorb);

	/* Do the border plotting */
	plot_border(size, east, north);
    }

    D_add_to_list(G_recreate_command());

    R_close_driver();

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 9
0
int scan_resolution(char *buf, double *f)
{
    return G_scan_resolution(buf, f, PS.w.proj);
}