tile4ms.c 9 KB
Newer Older
1
/******************************************************************************
2
 * $Id$
3 4
 *
 * Project:  MapServer
5
 * Purpose:  Create shapefile of rectangles from extents of several shapefiles
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 *           (=tiles)
 *           Create DBF with file names for shape tiles, in column LOCATION as
 *           required by mapserv.
 *           For use with Mapserv tiling capability.
 * Author:   Herbie Freytag hfreytag@dlwc.nsw.gov.au
 *
 * Note:
 * Resulting shape files do not display in ArcView.
 *
 ******************************************************************************
 * Copyright (c) 1996-2005 Regents of the University of Minnesota.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
25
 * The above copyright notice and this permission notice shall be included in
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
 * all copies of this Software or works derived from this Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *****************************************************************************/

/*
* This is a modified version of Herbie's program that works with MapServer's
* shapelib and should be using the MapServer makefile.
*
*/

#include "mapserver.h"
#include <string.h>

46

47 48

/***********************************************************************/
49 50
int process_shapefiles(char *metaFileNameP, char *tileFileNameP,
                       int tile_path_only)
51
{
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
  SHPHandle   hSHP, tileSHP;
  rectObj     extentRect;
  lineObj     line;
  shapeObj    shapeRect;
  DBFHandle   tileDBF;
  DBFHandle   shpDBF;

  typedef struct DBFFieldDef_struct {
    DBFFieldType  type;
    char          name[12];
    int           width;
    int           decimals;
  } DBFFieldDef;

  DBFFieldDef     *theFields = NULL;
  char            fldname[256];
  int             width;
  int             decimals;
  int             fieldCnt;
  int             i;

  FILE        *metaFP = NULL;
  char        *p;
  char        tileshapeName[256];
  char        tiledbfName[256];
  char        shapeFileName[256];
  int     entityNum;

  int     tilesFound = 0;
  int     tilesProcessed = 0;
82 83

  msInitShape(&shapeRect);
84
  line.point = (pointObj *)msSmallMalloc(sizeof(pointObj)*5);
85
  line.numpoints = 5;
86

87 88 89 90 91
  /* open metafile */
  /* ------------- */
  if (NULL==(metaFP=fopen(metaFileNameP, "r"))) {
    printf( "Unable to open:%s\n", metaFileNameP);
    return(1);
92
  }
93 94 95 96


  /* create new tileindex shapefiles and create a header */
  /* -------------------------------------------------- */
97
  snprintf(tileshapeName, sizeof(tileshapeName), "%s.shp", tileFileNameP);
98 99 100 101 102

  if(NULL==(tileSHP=msSHPCreate(tileFileNameP, SHP_POLYGON))) {
    fclose(metaFP);
    printf("Unable to create %s.shp (.shx)\n", tileFileNameP);
    return(1);
103 104
  }

105 106 107

  /* create new tileindex dbf-file */
  /* ----------------------------- */
108
  snprintf(tiledbfName, sizeof(tiledbfName), "%s.dbf", tileFileNameP);
109 110 111 112 113
  if (NULL==(tileDBF=msDBFCreate(tiledbfName))) {
    fclose(metaFP);
    msSHPClose(tileSHP);
    printf("DBFCreate(%s) failed.\n", tiledbfName);
    return(1);
114
  }
115 116 117 118 119 120 121

  if(msDBFAddField(tileDBF, "LOCATION", FTString, 255, 0 )== -1 ) {
    fclose(metaFP);
    msSHPClose(tileSHP);
    msDBFClose(tileDBF);
    printf("DBFAddField(fieldname='LOCATION') failed.\n");
    return(1);
122
  }
123 124 125 126 127 128



  /* loop through files listed in metafile */
  /* ===================================== */
  while (fgets(shapeFileName, 255, metaFP)) {
129

130 131 132 133

    if ((p=strchr(shapeFileName, '\n')) != NULL) *p='\0';

    if (!strlen(shapeFileName))
134
      break;
135 136 137 138 139

    tilesFound++;

    /* read the DBFFields for this shapefile */
    /* and save them if the first, otherwise compare them */
140

141 142 143
    shpDBF = msDBFOpen(shapeFileName, "rb");

    if( shpDBF == NULL ) {
144 145 146
      printf( "Aborted. Unable to open DBF:%s\n", shapeFileName);
      break;
    }
147 148

    if( theFields == NULL ) {
149 150 151 152 153 154 155 156 157 158
      fieldCnt = msDBFGetFieldCount(shpDBF);
      theFields = (DBFFieldDef *) msSmallCalloc(fieldCnt, sizeof(DBFFieldDef));
      for (i=0; i<fieldCnt; i++) {
        theFields[i].type = msDBFGetFieldInfo(shpDBF, i,
                                              theFields[i].name,
                                              &theFields[i].width, &theFields[i].decimals);
        if( theFields[i].type == FTInvalid ) {
          printf( "Aborted. DBF Invalid field (%d of %d) file:%s\n",
                  i, fieldCnt, shapeFileName);
          break;
159
        }
160
      }
161
    } else {
162 163 164 165 166 167 168
      fieldCnt = msDBFGetFieldCount(shpDBF);
      for (i=0; i<fieldCnt; i++) {
        if( theFields[i].type != msDBFGetFieldInfo(shpDBF, i, fldname, &width, &decimals) ||
            strcmp(theFields[i].name, fldname) ||
            theFields[i].width != width || theFields[i].decimals != decimals ) {
          printf( "Aborted. DBF fields do not match for file:%s\n", shapeFileName);
          break;
169
        }
170
      }
171 172 173
    }
    msDBFClose(shpDBF);

174 175 176 177 178
    /* Get rid of .shp extension if it was included. */
    if (strlen(shapeFileName) > 4 &&
        (p=shapeFileName+strlen(shapeFileName)-4) &&
        strcasecmp(p, ".shp") == 0)
      *p = '\0';
179 180

    if (!strlen(shapeFileName))
181
      break;
182 183 184 185 186 187

    /* read extent from shapefile */
    /* -------------------------- */
    hSHP = msSHPOpen(shapeFileName, "rb");

    if( hSHP == NULL )  {
188 189 190
      printf( "Aborted. Unable to open SHP:%s\n", shapeFileName);
      break;
    }
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215

    msSHPReadBounds(hSHP, -1, &extentRect);
    /* SHPGetInfo(hSHP, &nEntities, &nShapeType, adfBndsMin, adfBndsMax); */

    /* printf("File:  %s Bounds 0/1: (%15.10lg,%15.10lg)\n\t(%15.10lg,%15.10lg)\n", shapeFileName, adfBndsMin[0], adfBndsMin[1], adfBndsMax[0], adfBndsMax[1] ); */

    msSHPClose(hSHP);


    /* create rectangle describing current shapefile extent */
    /* ---------------------------------------------------- */

    line.point[0].x = line.point[4].x = extentRect.minx; /* bottom left */
    line.point[0].y = line.point[4].y  = extentRect.miny;
    line.point[1].x = extentRect.minx; /* top left */
    line.point[1].y = extentRect.maxy;
    line.point[2].x = extentRect.maxx; /* top left */
    line.point[2].y = extentRect.maxy;
    line.point[3].x = extentRect.maxx; /* bottom right */
    line.point[3].y = extentRect.miny;


    /* create and add shape object.  Returns link to entry in DBF file */
    /* --------------------------------------------------------------- */

216
    shapeRect.type = MS_SHAPE_POLYGON;
217 218
    msAddLine(&shapeRect, &line);
    entityNum = msSHPWriteShape( tileSHP, &shapeRect );
219

220 221 222 223 224 225
    msFreeShape(&shapeRect);

    /* store filepath of current shapefile as attribute of rectangle */
    /* ------------------------------------------------------------- */

    /* Strip off filename if requested */
226 227 228 229 230 231
    if (tile_path_only) {
      char *pszTmp;
      if ((pszTmp = strrchr(shapeFileName, '/')) != NULL ||
          (pszTmp = strrchr(shapeFileName, '\\')) != NULL ) {
        *(pszTmp+1) = '\0';  /* Keep the trailing '/' only. */
      }
232 233 234 235 236 237 238 239 240 241 242 243 244 245
    }

    msDBFWriteStringAttribute(tileDBF, entityNum, 0, shapeFileName);

    tilesProcessed++;

  }

  msSHPClose(tileSHP);
  msDBFClose(tileDBF);

  fclose(metaFP);

  free(line.point);
246
  free(theFields);
247

248

249 250
  printf("Processed %i of %i files\n", tilesProcessed, tilesFound);

251

252 253 254 255 256
  return (0);

}

/***********************************************************************/
257 258
void print_usage_and_exit(void)
{
259

260 261 262 263 264
  printf("\nusage: tile4ms <meta-file> <tile-file> [-tile-path-only]\n");
  printf("<meta-file>\tINPUT  file containing list of shapefile names\n\t\t(complete paths 255 chars max, no extension)\n");
  printf("<tile-file>\tOUTPUT shape file of extent rectangles and names\n\t\tof tiles in <tile-file>.dbf\n");
  printf("-tile-path-only\tOptional flag.  If specified then only the path to the \n\t\tshape files will be stored in the LOCATION field\n\t\tinstead of storing the full filename.\n\n");
  exit(1);
265 266 267 268 269 270 271 272 273 274 275
}



/***********************************************************************/
int main( int argc, char **argv )
{
  int tile_path_only = 0;

  /* stun user with existence of help  */
  /* -------------------------------- */
276 277
  if ((argc == 2)&&(strstr(argv[1], "-h"))) {
    print_usage_and_exit();
278 279 280 281 282
  }


  /* check arguments */
  /* --------------- */
283 284
  if( argc < 3 ) {
    print_usage_and_exit();
285 286
  }

287 288
  if ( argc == 4 && strcmp(argv[3],"-tile-path-only") == 0) {
    tile_path_only = 1;
289 290 291 292 293 294 295 296
  }

  process_shapefiles(argv[1], argv[2], tile_path_only);


  exit(0);
}