main.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. /****************************************************************
  2. *
  3. * MODULE: v.buffer
  4. *
  5. * AUTHOR(S): Radim Blazek
  6. * Upgraded by Rosen Matev (Google Summer of Code 2008)
  7. *
  8. * PURPOSE: Vector buffer
  9. *
  10. * COPYRIGHT: (C) 2001-2008 by the GRASS Development Team
  11. *
  12. * This program is free software under the
  13. * GNU General Public License (>=v2).
  14. * Read the file COPYING that comes with GRASS
  15. * for details.
  16. *
  17. **************************************************************/
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <grass/gis.h>
  21. #include <grass/Vect.h>
  22. #include <grass/dbmi.h>
  23. #include <grass/glocale.h>
  24. #include "local_proto.h"
  25. #define PI M_PI
  26. #ifndef MIN
  27. #define MIN(X,Y) ((X<Y)?X:Y)
  28. #endif
  29. #ifndef MAX
  30. #define MAX(X,Y) ((X>Y)?X:Y)
  31. #endif
  32. void stop(struct Map_info *In, struct Map_info *Out)
  33. {
  34. Vect_close(In);
  35. Vect_build_partial(Out, GV_BUILD_NONE);
  36. Vect_build(Out);
  37. Vect_close(Out);
  38. }
  39. /* returns 1 if unit_tolerance is adjusted, 0 otherwise */
  40. int adjust_tolerance(double *tolerance)
  41. {
  42. double t = 0.999 * (1 - cos(2 * PI / 8 / 2));
  43. G_debug(2, "Maximum tolerance = %f", t);
  44. if (*tolerance > t) {
  45. *tolerance = t;
  46. return 1;
  47. }
  48. return 0;
  49. }
  50. int db_CatValArray_get_value_di(dbCatValArray * cvarr, int cat, double *value)
  51. {
  52. int t;
  53. int ctype = cvarr->ctype;
  54. int ret;
  55. if (ctype == DB_C_TYPE_INT) {
  56. ret = db_CatValArray_get_value_int(cvarr, cat, &t);
  57. if (ret != DB_OK)
  58. return ret;
  59. *value = (double)t;
  60. return DB_OK;
  61. }
  62. if (ctype == DB_C_TYPE_DOUBLE) {
  63. ret = db_CatValArray_get_value_double(cvarr, cat, value);
  64. return ret;
  65. }
  66. return DB_FAILED;
  67. }
  68. struct buf_contours
  69. {
  70. int inner_count;
  71. struct line_pnts *oPoints;
  72. struct line_pnts **iPoints;
  73. };
  74. int point_in_buffer(struct buf_contours *arr_bc, int buffers_count,
  75. double x, double y)
  76. {
  77. int i, j, ret, flag;
  78. for (i = 0; i < buffers_count; i++) {
  79. ret = Vect_point_in_poly(x, y, arr_bc[i].oPoints);
  80. if (ret == 0)
  81. continue;
  82. flag = 1;
  83. for (j = 0; j < arr_bc[i].inner_count; j++) {
  84. ret = Vect_point_in_poly(x, y, arr_bc[i].iPoints[j]);
  85. if (ret != 0) { /* inside inner contour */
  86. flag = 0;
  87. break;
  88. }
  89. }
  90. if (flag) {
  91. /* (x,y) is inside outer contour and outside inner contours of arr_bc[i] */
  92. return 1;
  93. }
  94. }
  95. return 0;
  96. }
  97. int main(int argc, char *argv[])
  98. {
  99. struct Map_info In, Out;
  100. struct line_pnts *Points;
  101. struct line_cats *Cats, *BCats;
  102. const char *mapset;
  103. struct GModule *module;
  104. struct Option *in_opt, *out_opt, *type_opt, *dista_opt, *distb_opt,
  105. *angle_opt;
  106. struct Flag *straight_flag, *nocaps_flag;
  107. struct Option *tol_opt, *bufcol_opt, *scale_opt, *field_opt;
  108. double da, db, dalpha, tolerance, unit_tolerance;
  109. int type;
  110. int i, j, ret, nareas, area, nlines, line;
  111. char *Areas, *Lines;
  112. int field;
  113. struct buf_contours *arr_bc;
  114. int buffers_count;
  115. /* Attributes if sizecol is used */
  116. int nrec, ctype;
  117. struct field_info *Fi;
  118. dbDriver *Driver;
  119. dbCatValArray cvarr;
  120. double size_val, scale;
  121. module = G_define_module();
  122. module->keywords = _("vector, buffer");
  123. module->description =
  124. _("Creates a buffer around features of given type (areas must contain centroid).");
  125. in_opt = G_define_standard_option(G_OPT_V_INPUT);
  126. out_opt = G_define_standard_option(G_OPT_V_OUTPUT);
  127. type_opt = G_define_standard_option(G_OPT_V_TYPE);
  128. type_opt->options = "point,line,boundary,centroid,area";
  129. type_opt->answer = "point,line,area";
  130. field_opt = G_define_standard_option(G_OPT_V_FIELD);
  131. dista_opt = G_define_option();
  132. dista_opt->key = "distance";
  133. dista_opt->type = TYPE_DOUBLE;
  134. dista_opt->required = NO;
  135. dista_opt->description =
  136. _("Buffer distance along major axis in map units");
  137. distb_opt = G_define_option();
  138. distb_opt->key = "minordistance";
  139. distb_opt->type = TYPE_DOUBLE;
  140. distb_opt->required = NO;
  141. distb_opt->description =
  142. _("Buffer distance along minor axis in map units");
  143. distb_opt->guisection = _("Advanced");
  144. angle_opt = G_define_option();
  145. angle_opt->key = "angle";
  146. angle_opt->type = TYPE_DOUBLE;
  147. angle_opt->required = NO;
  148. angle_opt->answer = "0";
  149. angle_opt->description = _("Angle of major axis in degrees");
  150. angle_opt->guisection = _("Advanced");
  151. bufcol_opt = G_define_option();
  152. bufcol_opt->key = "bufcol";
  153. bufcol_opt->type = TYPE_STRING;
  154. bufcol_opt->required = NO;
  155. bufcol_opt->description =
  156. _("Attribute column to use for buffer distances");
  157. bufcol_opt->guisection = _("Advanced");
  158. scale_opt = G_define_option();
  159. scale_opt->key = "scale";
  160. scale_opt->type = TYPE_DOUBLE;
  161. scale_opt->required = NO;
  162. scale_opt->answer = "1.0";
  163. scale_opt->description = _("Scaling factor for attribute column values");
  164. scale_opt->guisection = _("Advanced");
  165. tol_opt = G_define_option();
  166. tol_opt->key = "tolerance";
  167. tol_opt->type = TYPE_DOUBLE;
  168. tol_opt->required = NO;
  169. tol_opt->answer = "0.01";
  170. tol_opt->guisection = _("Advanced");
  171. tol_opt->description =
  172. _("Maximum distance between theoretical arc and polygon segments as multiple of buffer");
  173. straight_flag = G_define_flag();
  174. straight_flag->key = 's';
  175. straight_flag->description = _("Make outside corners straight");
  176. nocaps_flag = G_define_flag();
  177. nocaps_flag->key = 'c';
  178. nocaps_flag->description = _("Don't make caps at the ends of polylines");
  179. G_gisinit(argv[0]);
  180. if (G_parser(argc, argv))
  181. exit(EXIT_FAILURE);
  182. type = Vect_option_to_types(type_opt);
  183. field = atoi(field_opt->answer);
  184. if ((dista_opt->answer && bufcol_opt->answer) ||
  185. (!(dista_opt->answer || bufcol_opt->answer)))
  186. G_fatal_error(_("Select a buffer distance/minordistance/angle "
  187. "or column, but not both."));
  188. if (bufcol_opt->answer)
  189. G_warning(_("The bufcol option may contain bugs during the cleaning "
  190. "step. If you encounter problems, use the debug "
  191. "option or clean manually with v.clean tool=break; "
  192. "v.category step=0; v.extract -d type=area"));
  193. tolerance = atof(tol_opt->answer);
  194. if (adjust_tolerance(&tolerance))
  195. G_warning(_("The tolerance was reset to %g"), tolerance);
  196. scale = atof(scale_opt->answer);
  197. if (scale <= 0.0)
  198. G_fatal_error("Illegal scale value");
  199. if (dista_opt->answer) {
  200. da = atof(dista_opt->answer);
  201. if (distb_opt->answer)
  202. db = atof(distb_opt->answer);
  203. else
  204. db = da;
  205. if (angle_opt->answer)
  206. dalpha = atof(angle_opt->answer);
  207. else
  208. dalpha = 0;
  209. unit_tolerance = tolerance * MIN(da, db);
  210. G_verbose_message(_("The tolerance in map units = %g"), unit_tolerance);
  211. }
  212. Vect_check_input_output_name(in_opt->answer, out_opt->answer,
  213. GV_FATAL_EXIT);
  214. Points = Vect_new_line_struct();
  215. Cats = Vect_new_cats_struct();
  216. BCats = Vect_new_cats_struct();
  217. /* open input vector */
  218. if ((mapset = G_find_vector2(in_opt->answer, "")) == NULL)
  219. G_fatal_error(_("Vector map <%s> not found"), in_opt->answer);
  220. Vect_set_open_level(2);
  221. if (1 > Vect_open_old(&In, in_opt->answer, mapset))
  222. G_fatal_error(_("Unable to open vector map <%s>"), in_opt->answer);
  223. if (0 > Vect_open_new(&Out, out_opt->answer, WITHOUT_Z)) {
  224. Vect_close(&In);
  225. G_fatal_error(_("Unable to create vector map <%s>"), out_opt->answer);
  226. }
  227. /* check and load attribute column data */
  228. if (bufcol_opt->answer) {
  229. db_CatValArray_init(&cvarr);
  230. Fi = Vect_get_field(&In, field);
  231. if (Fi == NULL)
  232. G_fatal_error(_("Database connection not defined for layer %d"),
  233. field);
  234. Driver = db_start_driver_open_database(Fi->driver, Fi->database);
  235. if (Driver == NULL)
  236. G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
  237. Fi->database, Fi->driver);
  238. /* Note do not check if the column exists in the table because it may be expression */
  239. /* TODO: only select values we need instead of all in column */
  240. nrec =
  241. db_select_CatValArray(Driver, Fi->table, Fi->key,
  242. bufcol_opt->answer, NULL, &cvarr);
  243. if (nrec < 0)
  244. G_fatal_error(_("Unable to select data from table <%s>"),
  245. Fi->table);
  246. G_debug(2, "%d records selected from table", nrec);
  247. ctype = cvarr.ctype;
  248. if (ctype != DB_C_TYPE_INT && ctype != DB_C_TYPE_DOUBLE)
  249. G_fatal_error(_("Column type not supported"));
  250. db_close_database_shutdown_driver(Driver);
  251. /* Output cats/values list */
  252. for (i = 0; i < cvarr.n_values; i++) {
  253. if (ctype == DB_C_TYPE_INT) {
  254. G_debug(4, "cat = %d val = %d", cvarr.value[i].cat,
  255. cvarr.value[i].val.i);
  256. }
  257. else if (ctype == DB_C_TYPE_DOUBLE) {
  258. G_debug(4, "cat = %d val = %f", cvarr.value[i].cat,
  259. cvarr.value[i].val.d);
  260. }
  261. }
  262. }
  263. Vect_copy_head_data(&In, &Out);
  264. Vect_hist_copy(&In, &Out);
  265. Vect_hist_command(&Out);
  266. /* Create buffers' boundaries */
  267. nlines = Vect_get_num_lines(&In);
  268. nareas = Vect_get_num_areas(&In);
  269. /* TODO: don't allocate so much space */
  270. buffers_count = 0;
  271. arr_bc = G_malloc((nlines + nareas) * sizeof(struct buf_contours));
  272. /* Lines (and Points) */
  273. if ((type & GV_POINTS) || (type & GV_LINES)) {
  274. int ltype;
  275. if (nlines > 0)
  276. G_message(_("Buffering lines..."));
  277. for (line = 1; line <= nlines; line++) {
  278. int cat;
  279. G_debug(2, "line = %d", line);
  280. G_percent(line, nlines, 2);
  281. ltype = Vect_read_line(&In, Points, Cats, line);
  282. if (!(ltype & type))
  283. continue;
  284. if (!Vect_cat_get(Cats, field, &cat))
  285. continue;
  286. if (bufcol_opt->answer) {
  287. ret = db_CatValArray_get_value_di(&cvarr, cat, &size_val);
  288. if (ret != DB_OK) {
  289. G_warning(_("No record for category %d in table <%s>"),
  290. cat, Fi->table);
  291. continue;
  292. }
  293. if (size_val < 0.0) {
  294. G_warning(_("Attribute is of invalid size (%.3f) for category %d"),
  295. size_val, cat);
  296. continue;
  297. }
  298. if (size_val == 0.0)
  299. continue;
  300. da = size_val * scale;
  301. db = da;
  302. dalpha = 0;
  303. unit_tolerance = tolerance * MIN(da, db);
  304. G_debug(2, " dynamic buffer size = %.2f", da);
  305. G_debug(2, _("The tolerance in map units: %g"),
  306. unit_tolerance);
  307. }
  308. if (ltype & GV_POINTS) {
  309. Vect_point_buffer2(Points->x[0], Points->y[0], da, db, dalpha,
  310. !(straight_flag->answer), unit_tolerance,
  311. &(arr_bc[buffers_count].oPoints));
  312. arr_bc[buffers_count].iPoints = NULL;
  313. arr_bc[buffers_count].inner_count = 0;
  314. buffers_count++;
  315. }
  316. else {
  317. Vect_line_buffer2(Points, da, db, dalpha,
  318. !(straight_flag->answer),
  319. !(nocaps_flag->answer), unit_tolerance,
  320. &(arr_bc[buffers_count].oPoints),
  321. &(arr_bc[buffers_count].iPoints),
  322. &(arr_bc[buffers_count].inner_count));
  323. buffers_count++;
  324. }
  325. }
  326. }
  327. /* Areas */
  328. if (type & GV_AREA) {
  329. int centroid;
  330. if (nareas > 0)
  331. G_message(_("Buffering areas..."));
  332. for (area = 1; area <= nareas; area++) {
  333. int cat;
  334. G_percent(area, nareas, 2);
  335. centroid = Vect_get_area_centroid(&In, area);
  336. if (centroid == 0)
  337. continue;
  338. Vect_read_line(&In, NULL, Cats, centroid);
  339. if (!Vect_cat_get(Cats, field, &cat))
  340. continue;
  341. if (bufcol_opt->answer) {
  342. ret = db_CatValArray_get_value_di(&cvarr, cat, &size_val);
  343. if (ret != DB_OK) {
  344. G_warning(_("No record for category %d in table <%s>"),
  345. cat, Fi->table);
  346. continue;
  347. }
  348. if (size_val < 0.0) {
  349. G_warning(_("Attribute is of invalid size (%.3f) for category %d"),
  350. size_val, cat);
  351. continue;
  352. }
  353. if (size_val == 0.0)
  354. continue;
  355. da = size_val * scale;
  356. db = da;
  357. dalpha = 0;
  358. unit_tolerance = tolerance * MIN(da, db);
  359. G_debug(2, " dynamic buffer size = %.2f", da);
  360. G_debug(2, _("The tolerance in map units: %g"),
  361. unit_tolerance);
  362. }
  363. Vect_area_buffer2(&In, area, da, db, dalpha,
  364. !(straight_flag->answer),
  365. !(nocaps_flag->answer), unit_tolerance,
  366. &(arr_bc[buffers_count].oPoints),
  367. &(arr_bc[buffers_count].iPoints),
  368. &(arr_bc[buffers_count].inner_count));
  369. buffers_count++;
  370. }
  371. }
  372. /* write all buffer contours */
  373. for (i = 0; i < buffers_count; i++) {
  374. Vect_write_line(&Out, GV_BOUNDARY, arr_bc[i].oPoints, BCats);
  375. for (j = 0; j < arr_bc[i].inner_count; j++)
  376. Vect_write_line(&Out, GV_BOUNDARY, arr_bc[i].iPoints[j], BCats);
  377. }
  378. /* Create areas */
  379. /* Break lines */
  380. G_verbose_message(_("Building parts of topology..."));
  381. Vect_build_partial(&Out, GV_BUILD_BASE);
  382. G_message(_("Snapping boundaries..."));
  383. Vect_snap_lines(&Out, GV_BOUNDARY, 1e-7, NULL);
  384. G_message(_("Breaking boundaries..."));
  385. Vect_break_lines(&Out, GV_BOUNDARY, NULL);
  386. G_message(_("Removing duplicates..."));
  387. Vect_remove_duplicates(&Out, GV_BOUNDARY, NULL);
  388. /* Dangles and bridges don't seem to be necessary if snapping is small enough. */
  389. /*
  390. G_message ( "Removing dangles..." );
  391. Vect_remove_dangles ( &Out, GV_BOUNDARY, -1, NULL, stderr );
  392. G_message ( "Removing bridges..." );
  393. Vect_remove_bridges ( &Out, NULL, stderr );
  394. */
  395. G_message(_("Attaching islands..."));
  396. Vect_build_partial(&Out, GV_BUILD_ATTACH_ISLES);
  397. /* Calculate new centroids for all areas */
  398. nareas = Vect_get_num_areas(&Out);
  399. Areas = (char *)G_calloc(nareas + 1, sizeof(char));
  400. for (area = 1; area <= nareas; area++) {
  401. double x, y;
  402. G_debug(3, "area = %d", area);
  403. if (!Vect_area_alive(&Out, area))
  404. continue;
  405. ret = Vect_get_point_in_area(&Out, area, &x, &y);
  406. if (ret < 0) {
  407. G_warning(_("Cannot calculate area centroid"));
  408. continue;
  409. }
  410. ret = point_in_buffer(arr_bc, buffers_count, x, y);
  411. if (ret) {
  412. G_debug(3, " -> in buffer");
  413. Areas[area] = 1;
  414. }
  415. }
  416. /* Make a list of boundaries to be deleted (both sides inside) */
  417. nlines = Vect_get_num_lines(&Out);
  418. G_debug(3, "nlines = %d", nlines);
  419. Lines = (char *)G_calloc(nlines + 1, sizeof(char));
  420. for (line = 1; line <= nlines; line++) {
  421. int j, side[2], areas[2];
  422. G_debug(3, "line = %d", line);
  423. if (!Vect_line_alive(&Out, line))
  424. continue;
  425. Vect_get_line_areas(&Out, line, &side[0], &side[1]);
  426. for (j = 0; j < 2; j++) {
  427. if (side[j] == 0) { /* area/isle not build */
  428. areas[j] = 0;
  429. }
  430. else if (side[j] > 0) { /* area */
  431. areas[j] = side[j];
  432. }
  433. else { /* < 0 -> island */
  434. areas[j] = Vect_get_isle_area(&Out, abs(side[j]));
  435. }
  436. }
  437. G_debug(3, " areas = %d , %d -> Areas = %d, %d", areas[0], areas[1],
  438. Areas[areas[0]], Areas[areas[1]]);
  439. if (Areas[areas[0]] && Areas[areas[1]])
  440. Lines[line] = 1;
  441. }
  442. G_free(Areas);
  443. /* Delete boundaries */
  444. for (line = 1; line <= nlines; line++) {
  445. if (Lines[line]) {
  446. G_debug(3, " delete line %d", line);
  447. Vect_delete_line(&Out, line);
  448. }
  449. }
  450. G_free(Lines);
  451. /* Create new centroids */
  452. Vect_reset_cats(Cats);
  453. Vect_cat_set(Cats, 1, 1);
  454. nareas = Vect_get_num_areas(&Out);
  455. for (area = 1; area <= nareas; area++) {
  456. double x, y;
  457. G_debug(3, "area = %d", area);
  458. if (!Vect_area_alive(&Out, area))
  459. continue;
  460. ret = Vect_get_point_in_area(&Out, area, &x, &y);
  461. if (ret < 0) {
  462. G_warning(_("Cannot calculate area centroid"));
  463. continue;
  464. }
  465. ret = point_in_buffer(arr_bc, buffers_count, x, y);
  466. if (ret) {
  467. Vect_reset_line(Points);
  468. Vect_append_point(Points, x, y, 0.);
  469. Vect_write_line(&Out, GV_CENTROID, Points, Cats);
  470. }
  471. }
  472. /* free arr_bc[] */
  473. /* will only slow down the module
  474. for (i = 0; i < buffers_count; i++) {
  475. Vect_destroy_line_struct(arr_bc[i].oPoints);
  476. for (j = 0; j < arr_bc[i].inner_count; j++)
  477. Vect_destroy_line_struct(arr_bc[i].iPoints[j]);
  478. G_free(arr_bc[i].iPoints);
  479. } */
  480. G_message(_("Attaching centroids..."));
  481. Vect_build_partial(&Out, GV_BUILD_CENTROIDS);
  482. stop(&In, &Out);
  483. exit(EXIT_SUCCESS);
  484. }