mapdraw.c 129 KB
Newer Older
1
/******************************************************************************
2
 * $Id$
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * Project:  MapServer
 * Purpose:  High level msDrawMap() implementation and related functions.
 * Author:   Steve Lime and the MapServer team.
 *
 ******************************************************************************
 * 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:
 *
18
 * The above copyright notice and this permission notice shall be included in
19 20 21 22 23 24 25 26 27 28 29 30
 * 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.
 *****************************************************************************/

#include <assert.h>
31
#include <math.h>
32 33 34
#include "mapserver.h"
#include "maptime.h"
#include "mapcopy.h"
35
#include "mapfile.h"
36
#include "mapows.h"
37 38 39 40 41 42 43 44 45 46


/* msPrepareImage()
 *
 * Returns a new imageObj ready for rendering the current map.
 *
 * If allow_nonsquare is set to MS_TRUE then the caller should call
 * msMapRestoreRealExtent() once they are done with the image.
 * This should be set to MS_TRUE only when called from msDrawMap(), see bug 945.
 */
47
imageObj *msPrepareImage(mapObj *map, int allow_nonsquare)
48
{
49 50 51
  int i, status;
  imageObj *image=NULL;
  double geo_cellsize;
52

53 54 55 56 57 58 59 60 61 62 63 64
  if(map->width == -1 || map->height == -1) {
    msSetError(MS_MISCERR, "Image dimensions not specified.", "msPrepareImage()");
    return(NULL);
  }

  msInitLabelCache(&(map->labelcache)); /* this clears any previously allocated cache */

  /* clear any previously created mask layer images */
  for(i=0; i<map->numlayers; i++) {
    if(GET_LAYER(map, i)->maskimage) {
      msFreeImage(GET_LAYER(map, i)->maskimage);
      GET_LAYER(map, i)->maskimage = NULL;
65
    }
66
  }
67

68 69
  status = msValidateContexts(map); /* make sure there are no recursive REQUIRES or LABELREQUIRES expressions */
  if(status != MS_SUCCESS) return NULL;
70

71
  if(!map->outputformat) {
72
    msSetError(MS_IMGERR, "Map outputformat not set!", "msPrepareImage()");
73 74 75 76 77 78 79 80 81
    return(NULL);
  } else if (MS_RENDERER_PLUGIN(map->outputformat)) {
    rendererVTableObj *renderer = map->outputformat->vtable;
    colorObj *bg = &map->imagecolor;
    map->imagecolor.alpha=255;
    if(map->transparent == MS_TRUE) {
      /* don't set the image color */
      bg = NULL;
    }
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

  image = renderer->createImage(map->width, map->height, map->outputformat,bg);
  if (image == NULL)
    return(NULL);
  image->format = map->outputformat;
  image->format->refcount++;
  image->width = map->width;
  image->height = map->height;

  image->resolution = map->resolution;
  image->resolutionfactor = map->resolution/map->defresolution;
  if (map->web.imagepath)
    image->imagepath = msStrdup(map->web.imagepath);
  if (map->web.imageurl)
    image->imageurl = msStrdup(map->web.imageurl);
97 98 99 100 101 102 103 104 105 106

  } else if( MS_RENDERER_IMAGEMAP(map->outputformat) ) {
    image = msImageCreateIM(map->width, map->height, map->outputformat,
                            map->web.imagepath, map->web.imageurl, map->resolution, map->defresolution);
  } else if( MS_RENDERER_RAWDATA(map->outputformat) ) {
    image = msImageCreate(map->width, map->height, map->outputformat,
                          map->web.imagepath, map->web.imageurl, map->resolution, map->defresolution, &map->imagecolor);
  } else {
    image = NULL;
  }
107
  
108
  if(!image) {
109
    msSetError(MS_IMGERR, "Unable to initialize image.", "msPrepareImage()");
110 111
    return(NULL);
  }
112 113
  
  image->map = map;
114

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
  /*
   * If we want to support nonsquare pixels, note that now, otherwise
   * adjust the extent size to have square pixels.
   *
   * If allow_nonsquare is set to MS_TRUE then the caller should call
   * msMapRestoreRealExtent() once they are done with the image.
   * This should be set to MS_TRUE only when called from msDrawMap(), see bug 945.
   */
  if( allow_nonsquare && msTestConfigOption( map, "MS_NONSQUARE", MS_FALSE ) ) {
    double cellsize_x = (map->extent.maxx - map->extent.minx)/map->width;
    double cellsize_y = (map->extent.maxy - map->extent.miny)/map->height;

    if( cellsize_y != 0.0
        && (fabs(cellsize_x/cellsize_y) > 1.00001
            || fabs(cellsize_x/cellsize_y) < 0.99999) ) {
      map->gt.need_geotransform = MS_TRUE;
      if (map->debug)
        msDebug( "msDrawMap(): kicking into non-square pixel preserving mode.\n" );
    }
    map->cellsize = (cellsize_x*0.5 + cellsize_y*0.5);
  } else
    map->cellsize = msAdjustExtent(&(map->extent),map->width,map->height);

  status = msCalculateScale(map->extent,map->units,map->width,map->height, map->resolution, &map->scaledenom);
  if(status != MS_SUCCESS) {
    msFreeImage(image);
    return(NULL);
  }
143

144 145
  /* update geotransform based on adjusted extent. */
  msMapComputeGeotransform( map );
146

147 148 149
  /* Do we need to fake out stuff for rotated support? */
  if( map->gt.need_geotransform )
    msMapSetFakedExtent( map );
150

151 152
  /* We will need a cellsize that represents a real georeferenced */
  /* coordinate cellsize here, so compute it from saved extents.   */
153

154 155 156 157 158 159
  geo_cellsize = map->cellsize;
  if( map->gt.need_geotransform == MS_TRUE ) {
    double cellsize_x = (map->saved_extent.maxx - map->saved_extent.minx)
                        / map->width;
    double cellsize_y = (map->saved_extent.maxy - map->saved_extent.miny)
                        / map->height;
160

161 162 163
    geo_cellsize = sqrt(cellsize_x*cellsize_x + cellsize_y*cellsize_y)
                   / sqrt(2.0);
  }
164

165 166 167 168 169 170 171 172 173
  /* compute layer scale factors now */
  for(i=0; i<map->numlayers; i++) {
    if(GET_LAYER(map, i)->sizeunits != MS_PIXELS)
      GET_LAYER(map, i)->scalefactor = (msInchesPerUnit(GET_LAYER(map, i)->sizeunits,0)/msInchesPerUnit(map->units,0)) / geo_cellsize;
    else if(GET_LAYER(map, i)->symbolscaledenom > 0 && map->scaledenom > 0)
      GET_LAYER(map, i)->scalefactor = GET_LAYER(map, i)->symbolscaledenom/map->scaledenom*map->resolution/map->defresolution;
    else
      GET_LAYER(map, i)->scalefactor = map->resolution/map->defresolution;
  }
174

175 176
  image->refpt.x = MS_MAP2IMAGE_X_IC_DBL(0, map->extent.minx, 1.0/map->cellsize);
  image->refpt.y = MS_MAP2IMAGE_Y_IC_DBL(0, map->extent.maxy, 1.0/map->cellsize);
177

178
  return image;
179
  
180 181
}

182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
static int msCompositeRasterBuffer(imageObj *img, rasterBufferObj *rb, LayerCompositer *comp) {
  int ret = MS_SUCCESS;
  if(MS_IMAGE_RENDERER(img)->compositeRasterBuffer) {
    while(comp && ret == MS_SUCCESS) {
      rasterBufferObj *rb_ptr = rb;
      if(comp->filter) {
        rb_ptr = msApplyFilterToRasterBuffer(rb,comp->filter);
      }
      ret = MS_IMAGE_RENDERER(img)->compositeRasterBuffer(img,rb_ptr,comp->comp_op, comp->opacity);
      if(rb_ptr != rb) {
        msFreeRasterBuffer(rb_ptr);
        msFree(rb_ptr);
      }
      comp = comp->next;
    }
  } else {
    ret = MS_FAILURE;
  }
  return ret;
}
202 203 204 205 206 207

/*
 * Generic function to render the map file.
 * The type of the image created is based on the imagetype parameter in the map file.
 *
 * mapObj *map - map object loaded in MapScript or via a mapfile to use
208
 * int querymap - is this map the result of a query operation, MS_TRUE|MS_FALSE
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
*/
imageObj *msDrawMap(mapObj *map, int querymap)
{
  int i;
  layerObj *lp=NULL;
  int status = MS_FAILURE;
  imageObj *image = NULL;
  struct mstimeval mapstarttime, mapendtime;
  struct mstimeval starttime, endtime;

#if defined(USE_WMS_LYR) || defined(USE_WFS_LYR)
  enum MS_CONNECTION_TYPE lastconnectiontype;
  httpRequestObj *pasOWSReqInfo=NULL;
  int numOWSLayers=0, numOWSRequests=0;
  wmsParamsObj sLastWMSParams;
#endif

  if(map->debug >= MS_DEBUGLEVEL_TUNING) msGettimeofday(&mapstarttime, NULL);

  if(querymap) { /* use queryMapObj image dimensions */
    if(map->querymap.width != -1) map->width = map->querymap.width;
    if(map->querymap.height != -1) map->height = map->querymap.height;
  }

  msApplyMapConfigOptions(map);
  image = msPrepareImage(map, MS_TRUE);

  if(!image) {
    msSetError(MS_IMGERR, "Unable to initialize image.", "msDrawMap()");
    return(NULL);
  }

241
  if( map->debug >= MS_DEBUGLEVEL_DEBUG )
242 243 244
    msDebug( "msDrawMap(): rendering using outputformat named %s (%s).\n",
             map->outputformat->name,
             map->outputformat->driver );
245

246
#if defined(USE_WMS_LYR) || defined(USE_WFS_LYR)
247 248 249 250

  /* Time the OWS query phase */
  if(map->debug >= MS_DEBUGLEVEL_TUNING ) msGettimeofday(&starttime, NULL);

251 252
  /* How many OWS (WMS/WFS) layers do we have to draw?
   * Note: numOWSLayers is the number of actual layers and numOWSRequests is
253
   * the number of HTTP requests which could be lower if multiple layers
254 255 256 257
   * are merged into the same request.
   */
  numOWSLayers=0;
  for(i=0; i<map->numlayers; i++) {
258 259 260
    if(map->layerorder[i] != -1 &&
        msLayerIsVisible(map, GET_LAYER(map,map->layerorder[i])))
      numOWSLayers++;
261 262
  }

263

264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
  if (numOWSLayers > 0) {
    /* Alloc and init pasOWSReqInfo...
     */
    pasOWSReqInfo = (httpRequestObj *)malloc((numOWSLayers+1)*sizeof(httpRequestObj));
    if (pasOWSReqInfo == NULL) {
      msSetError(MS_MEMERR, "Allocation of httpRequestObj failed.", "msDrawMap()");
      return NULL;
    }
    msHTTPInitRequestObj(pasOWSReqInfo, numOWSLayers+1);
    msInitWmsParamsObj(&sLastWMSParams);

    /* Pre-download all WMS/WFS layers in parallel before starting to draw map */
    lastconnectiontype = MS_SHAPEFILE;
    for(i=0; numOWSLayers && i<map->numlayers; i++) {
      if(map->layerorder[i] == -1 || !msLayerIsVisible(map, GET_LAYER(map,map->layerorder[i])))
        continue;

      lp = GET_LAYER(map,map->layerorder[i]);

#ifdef USE_WMS_LYR
      if(lp->connectiontype == MS_WMS) {
285
        if(msPrepareWMSLayerRequest(map->layerorder[i], map, lp, 1, lastconnectiontype, &sLastWMSParams, 0, 0, 0, NULL, pasOWSReqInfo, &numOWSRequests) == MS_FAILURE) {
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
          msFreeWmsParamsObj(&sLastWMSParams);
          msFreeImage(image);
          msFree(pasOWSReqInfo);
          return NULL;
        }
      }
#endif

#ifdef USE_WFS_LYR
      if(lp->connectiontype == MS_WFS) {
        if(msPrepareWFSLayerRequest(map->layerorder[i], map, lp, pasOWSReqInfo, &numOWSRequests) == MS_FAILURE) {
          msFreeWmsParamsObj(&sLastWMSParams);
          msFreeImage(image);
          msFree(pasOWSReqInfo);
          return NULL;
        }
      }
#endif

      lastconnectiontype = lp->connectiontype;
    }

#ifdef USE_WMS_LYR
309
    msFreeWmsParamsObj(&sLastWMSParams);
310 311 312 313 314 315 316 317
#endif
  } /* if numOWSLayers > 0 */

  if(numOWSRequests && msOWSExecuteRequests(pasOWSReqInfo, numOWSRequests, map, MS_TRUE) == MS_FAILURE) {
    msFreeImage(image);
    msFree(pasOWSReqInfo);
    return NULL;
  }
318 319 320

  if(map->debug >= MS_DEBUGLEVEL_TUNING) {
    msGettimeofday(&endtime, NULL);
321
    msDebug("msDrawMap(): WMS/WFS set-up and query, %.3fs\n",
322 323 324 325
            (endtime.tv_sec+endtime.tv_usec/1.0e6)-
            (starttime.tv_sec+starttime.tv_usec/1.0e6) );
  }

326 327 328 329 330 331
#endif /* USE_WMS_LYR || USE_WFS_LYR */

  /* OK, now we can start drawing */
  for(i=0; i<map->numlayers; i++) {

    if(map->layerorder[i] != -1) {
332 333
      char *force_draw_label_cache = NULL;

334 335 336 337 338 339 340 341 342 343
      lp = (GET_LAYER(map,  map->layerorder[i]));

      if(lp->postlabelcache) /* wait to draw */
        continue;

      if(map->debug >= MS_DEBUGLEVEL_TUNING || lp->debug >= MS_DEBUGLEVEL_TUNING ) msGettimeofday(&starttime, NULL);

      if(!msLayerIsVisible(map, lp)) continue;

      if(lp->connectiontype == MS_WMS) {
344
#ifdef USE_WMS_LYR
345
        if(MS_RENDERER_PLUGIN(image->format) || MS_RENDERER_RAWDATA(image->format))
346 347 348 349 350
          status = msDrawWMSLayerLow(map->layerorder[i], pasOWSReqInfo, numOWSRequests,  map, lp, image);
        else {
          msSetError(MS_WMSCONNERR, "Output format '%s' doesn't support WMS layers.", "msDrawMap()", image->format->name);
          status = MS_FAILURE;
        }
351

352
        if(status == MS_FAILURE) {
353
          msSetError(MS_WMSCONNERR,
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
                     "Failed to draw WMS layer named '%s'. This most likely happened because "
                     "the remote WMS server returned an invalid image, and XML exception "
                     "or another unexpected result in response to the GetMap request. Also check "
                     "and make sure that the layer's connection URL is valid.",
                     "msDrawMap()", lp->name);
          msFreeImage(image);
          msHTTPFreeRequestObj(pasOWSReqInfo, numOWSRequests);
          msFree(pasOWSReqInfo);
          return(NULL);
        }


#else /* ndef USE_WMS_LYR */
        msSetError(MS_WMSCONNERR, "MapServer not built with WMS Client support, unable to render layer '%s'.", "msDrawMap()", lp->name);
        msFreeImage(image);
        return(NULL);
#endif
      } else { /* Default case: anything but WMS layers */
        if(querymap)
          status = msDrawQueryLayer(map, lp, image);
        else
          status = msDrawLayer(map, lp, image);
        if(status == MS_FAILURE) {
          msSetError(MS_IMGERR, "Failed to draw layer named '%s'.", "msDrawMap()", lp->name);
          msFreeImage(image);
#if defined(USE_WMS_LYR) || defined(USE_WFS_LYR)
          if (pasOWSReqInfo) {
            msHTTPFreeRequestObj(pasOWSReqInfo, numOWSRequests);
            msFree(pasOWSReqInfo);
          }
#endif /* USE_WMS_LYR || USE_WFS_LYR */
          return(NULL);
        }
      }
388 389 390 391 392 393 394
      if(map->debug >= MS_DEBUGLEVEL_TUNING || lp->debug >= MS_DEBUGLEVEL_TUNING) {
        msGettimeofday(&endtime, NULL);
        msDebug("msDrawMap(): Layer %d (%s), %.3fs\n",
                map->layerorder[i], lp->name?lp->name:"(null)",
                (endtime.tv_sec+endtime.tv_usec/1.0e6)-
                (starttime.tv_sec+starttime.tv_usec/1.0e6) );
      }
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415

      /* Flush layer cache in-between layers if requested by PROCESSING directive*/
      force_draw_label_cache = msLayerGetProcessingKey(lp, "FORCE_DRAW_LABEL_CACHE");
      if (force_draw_label_cache &&
	  strncasecmp(force_draw_label_cache,"FLUSH",5)==0) {
	if(map->debug >= MS_DEBUGLEVEL_V)
	  msDebug("msDrawMap(): PROCESSING FORCE_DRAW_LABEL_CACHE=FLUSH found.\n");
	if(msDrawLabelCache(map, image) != MS_SUCCESS) {
	  msFreeImage(image);
#if defined(USE_WMS_LYR) || defined(USE_WFS_LYR)
	  if (pasOWSReqInfo) {
	    msHTTPFreeRequestObj(pasOWSReqInfo, numOWSRequests);
	    msFree(pasOWSReqInfo);
	  }
#endif /* USE_WMS_LYR || USE_WFS_LYR */
	  return(NULL);
	}
	msFreeLabelCache(&(map->labelcache));
	msInitLabelCache(&(map->labelcache));
      } /* PROCESSING FORCE_DRAW_LABEL_CACHE */

416 417 418 419 420 421 422 423 424 425 426
    }
  }

  if(map->scalebar.status == MS_EMBED && !map->scalebar.postlabelcache) {

    /* We need to temporarily restore the original extent for drawing */
    /* the scalebar as it uses the extent to recompute cellsize. */
    if(map->gt.need_geotransform)
      msMapRestoreRealExtent(map);


427
    if(MS_SUCCESS != msEmbedScalebar(map, image)) {
428
      msFreeImage( image );
429 430 431 432 433 434 435
#if defined(USE_WMS_LYR) || defined(USE_WFS_LYR)
      /* Cleanup WMS/WFS Request stuff */
      if (pasOWSReqInfo) {
         msHTTPFreeRequestObj(pasOWSReqInfo, numOWSRequests);
         msFree(pasOWSReqInfo);
      }
#endif
436
      return NULL;
437
    }
438 439 440 441 442 443


    if(map->gt.need_geotransform)
      msMapSetFakedExtent(map);
  }

444 445 446
  if(map->legend.status == MS_EMBED && !map->legend.postlabelcache) {
    if( msEmbedLegend(map, image) != MS_SUCCESS ) {
      msFreeImage( image );
447 448 449 450 451 452 453
#if defined(USE_WMS_LYR) || defined(USE_WFS_LYR)
      /* Cleanup WMS/WFS Request stuff */
      if (pasOWSReqInfo) {
         msHTTPFreeRequestObj(pasOWSReqInfo, numOWSRequests);
         msFree(pasOWSReqInfo);
      }
#endif
454 455
      return NULL;
    }
456
  }
457

458
  if(msDrawLabelCache(map, image) != MS_SUCCESS) {
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
    msFreeImage(image);
#if defined(USE_WMS_LYR) || defined(USE_WFS_LYR)
    if (pasOWSReqInfo) {
      msHTTPFreeRequestObj(pasOWSReqInfo, numOWSRequests);
      msFree(pasOWSReqInfo);
    }
#endif /* USE_WMS_LYR || USE_WFS_LYR */
    return(NULL);
  }


  for(i=0; i<map->numlayers; i++) { /* for each layer, check for postlabelcache layers */

    lp = (GET_LAYER(map, map->layerorder[i]));

    if(!lp->postlabelcache) continue;
    if(!msLayerIsVisible(map, lp)) continue;

    if(map->debug >= MS_DEBUGLEVEL_TUNING || lp->debug >= MS_DEBUGLEVEL_TUNING) msGettimeofday(&starttime, NULL);

    if(lp->connectiontype == MS_WMS) {
480
#ifdef USE_WMS_LYR
481
      if(MS_RENDERER_PLUGIN(image->format) || MS_RENDERER_RAWDATA(image->format))
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
        status = msDrawWMSLayerLow(map->layerorder[i], pasOWSReqInfo, numOWSRequests, map, lp, image);

#else
      status = MS_FAILURE;
#endif
    } else {
      if(querymap)
        status = msDrawQueryLayer(map, lp, image);
      else
        status = msDrawLayer(map, lp, image);
    }

    if(status == MS_FAILURE) {
      msFreeImage(image);
#if defined(USE_WMS_LYR) || defined(USE_WFS_LYR)
      if (pasOWSReqInfo) {
        msHTTPFreeRequestObj(pasOWSReqInfo, numOWSRequests);
        msFree(pasOWSReqInfo);
      }
#endif /* USE_WMS_LYR || USE_WFS_LYR */
      return(NULL);
    }

    if(map->debug >= MS_DEBUGLEVEL_TUNING || lp->debug >= MS_DEBUGLEVEL_TUNING) {
      msGettimeofday(&endtime, NULL);
507
      msDebug("msDrawMap(): Layer %d (%s), %.3fs\n",
508 509 510 511 512 513
              map->layerorder[i], lp->name?lp->name:"(null)",
              (endtime.tv_sec+endtime.tv_usec/1.0e6)-
              (starttime.tv_sec+starttime.tv_usec/1.0e6) );
    }

  }
514

515 516 517 518 519 520
  /* Do we need to fake out stuff for rotated support? */
  /* This really needs to be done on every preceeding exit point too... */
  if(map->gt.need_geotransform)
    msMapRestoreRealExtent(map);

  if(map->legend.status == MS_EMBED && map->legend.postlabelcache)
521 522 523 524
    if(UNLIKELY(MS_FAILURE == msEmbedLegend(map, image))) {
      msFreeImage( image );
      return NULL;
    }
525

526
  if(map->scalebar.status == MS_EMBED && map->scalebar.postlabelcache) {
527 528 529 530 531 532 533 534 535

    /* We need to temporarily restore the original extent for drawing */
    /* the scalebar as it uses the extent to recompute cellsize. */
    if(map->gt.need_geotransform)
      msMapRestoreRealExtent(map);


    if(MS_SUCCESS != msEmbedScalebar(map, image)) {
      msFreeImage( image );
536 537 538 539 540 541 542
#if defined(USE_WMS_LYR) || defined(USE_WFS_LYR)
      /* Cleanup WMS/WFS Request stuff */
      if (pasOWSReqInfo) {
         msHTTPFreeRequestObj(pasOWSReqInfo, numOWSRequests);
         msFree(pasOWSReqInfo);
      }
#endif
543 544 545 546 547 548 549
      return NULL;
    }


    if(map->gt.need_geotransform)
      msMapSetFakedExtent(map);
  }
550 551 552 553 554 555 556 557 558 559 560

#if defined(USE_WMS_LYR) || defined(USE_WFS_LYR)
  /* Cleanup WMS/WFS Request stuff */
  if (pasOWSReqInfo) {
    msHTTPFreeRequestObj(pasOWSReqInfo, numOWSRequests);
    msFree(pasOWSReqInfo);
  }
#endif

  if(map->debug >= MS_DEBUGLEVEL_TUNING) {
    msGettimeofday(&mapendtime, NULL);
561
    msDebug("msDrawMap() total time: %.3fs\n",
562 563 564 565 566 567 568 569 570
            (mapendtime.tv_sec+mapendtime.tv_usec/1.0e6)-
            (mapstarttime.tv_sec+mapstarttime.tv_usec/1.0e6) );
  }

  return(image);
}

/*
 * Test whether a layer should be drawn or not in the current map view and
571
 * at the current scale.
572 573 574 575 576 577
 * Returns TRUE if layer is visible, FALSE if not.
*/
int msLayerIsVisible(mapObj *map, layerObj *layer)
{
  int i;

578
  if(!layer->data && !layer->tileindex && !layer->connection && !layer->features && !layer->grid)
579 580 581 582 583
    return(MS_FALSE); /* no data associated with this layer, not an error since layer may be used as a template from MapScript */

  if(layer->type == MS_LAYER_QUERY || layer->type == MS_LAYER_TILEINDEX) return(MS_FALSE);
  if((layer->status != MS_ON) && (layer->status != MS_DEFAULT)) return(MS_FALSE);

584
  /* Only return MS_FALSE if it is definitely false. Sometimes it will return MS_UNKNOWN, which we
585 586 587 588 589
  ** consider true, for this use case (it might be visible, try and draw it, see what happens). */
  if ( msExtentsOverlap(map, layer) == MS_FALSE ) {
    if( layer->debug >= MS_DEBUGLEVEL_V ) {
      msDebug("msLayerIsVisible(): Skipping layer (%s) because LAYER.EXTENT does not intersect MAP.EXTENT\n", layer->name);
    }
590
    return(MS_FALSE);
591
  }
592

593 594 595
  if(msEvalContext(map, layer, layer->requires) == MS_FALSE) return(MS_FALSE);

  if(map->scaledenom > 0) {
596

597 598 599 600 601 602 603 604 605 606 607 608 609
    /* layer scale boundaries should be checked first */
    if((layer->maxscaledenom > 0) && (map->scaledenom > layer->maxscaledenom)) {
      if( layer->debug >= MS_DEBUGLEVEL_V ) {
        msDebug("msLayerIsVisible(): Skipping layer (%s) because LAYER.MAXSCALE is too small for this MAP scale\n", layer->name);
      }
      return(MS_FALSE);
    }
    if((layer->minscaledenom > 0) && (map->scaledenom <= layer->minscaledenom)) {
      if( layer->debug >= MS_DEBUGLEVEL_V ) {
        msDebug("msLayerIsVisible(): Skipping layer (%s) because LAYER.MINSCALE is too large for this MAP scale\n", layer->name);
      }
      return(MS_FALSE);
    }
610
  
611 612 613 614 615 616 617 618 619
    /* now check class scale boundaries (all layers *must* pass these tests) */
    if(layer->numclasses > 0) {
      for(i=0; i<layer->numclasses; i++) {
        if((layer->class[i]->maxscaledenom > 0) && (map->scaledenom > layer->class[i]->maxscaledenom))
          continue; /* can skip this one, next class */
        if((layer->class[i]->minscaledenom > 0) && (map->scaledenom <= layer->class[i]->minscaledenom))
          continue; /* can skip this one, next class */

        break; /* can't skip this class (or layer for that matter) */
620
      }
621 622 623 624 625 626 627 628 629 630 631
      if(i == layer->numclasses) {
        if( layer->debug >= MS_DEBUGLEVEL_V ) {
          msDebug("msLayerIsVisible(): Skipping layer (%s) because no CLASS in the layer is in-scale for this MAP scale\n", layer->name);
        }
        return(MS_FALSE);
      }
    }

  }

  if (layer->maxscaledenom <= 0 && layer->minscaledenom <= 0) {
632 633 634
    if((layer->maxgeowidth > 0) && ((map->extent.maxx - map->extent.minx) > layer->maxgeowidth)) {
      if( layer->debug >= MS_DEBUGLEVEL_V ) {
        msDebug("msLayerIsVisible(): Skipping layer (%s) because LAYER width is much smaller than map width\n", layer->name);
635
      }
636 637 638 639 640
      return(MS_FALSE);
    }
    if((layer->mingeowidth > 0) && ((map->extent.maxx - map->extent.minx) < layer->mingeowidth)) {
      if( layer->debug >= MS_DEBUGLEVEL_V ) {
        msDebug("msLayerIsVisible(): Skipping layer (%s) because LAYER width is much larger than map width\n", layer->name);
641
      }
642 643
      return(MS_FALSE);
    }
644 645 646 647
  }

  return MS_TRUE;  /* All tests passed.  Layer is visible. */
}
648 649 650


#define LAYER_NEEDS_COMPOSITING(layer) (((layer)->compositer != NULL) && ((layer)->compositer->next || (layer)->compositor->opacity < 100 || (layer)->compositor->compop != MS_COMPOP_SRC_OVER || (layer)->compositer->filter ))
651 652 653 654 655 656
/*
 * Generic function to render a layer object.
*/
int msDrawLayer(mapObj *map, layerObj *layer, imageObj *image)
{
  imageObj *image_draw = image;
657
  outputFormatObj *altFormat=NULL;
658
  int retcode=MS_SUCCESS;
659
  const char *alternativeFomatString = NULL;
660
  layerObj *maskLayer = NULL;
661 662

  if(!msLayerIsVisible(map, layer))
663
    return MS_SUCCESS;
664

665 666
  if(layer->compositer && !layer->compositer->next && layer->compositer->opacity == 0) return MS_SUCCESS; /* layer is completely transparent, skip it */
  
667 668 669 670 671

  /* conditions may have changed since this layer last drawn, so set
     layer->project true to recheck projection needs (Bug #673) */
  layer->project = MS_TRUE;

672 673 674 675 676 677
  /* make sure labelcache setting is set correctly if postlabelcache is set. This is done by the parser but
     may have been altered by a mapscript. see #5142 */
  if(layer->postlabelcache) {
    layer->labelcache = MS_FALSE;
  }

678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
  if(layer->mask) {
    int maskLayerIdx;
    /* render the mask layer in its own imageObj */
    if(!MS_IMAGE_RENDERER(image)->supports_pixel_buffer) {
      msSetError(MS_MISCERR, "Layer (%s) references references a mask layer, but the selected renderer does not support them", "msDrawLayer()",
                 layer->name);
      return (MS_FAILURE);
    }
    maskLayerIdx = msGetLayerIndex(map,layer->mask);
    if(maskLayerIdx == -1) {
      msSetError(MS_MISCERR, "Layer (%s) references unknown mask layer (%s)", "msDrawLayer()",
                 layer->name,layer->mask);
      return (MS_FAILURE);
    }
    maskLayer = GET_LAYER(map, maskLayerIdx);
    if(!maskLayer->maskimage) {
      int i;
      int origstatus, origlabelcache;
      altFormat =  msSelectOutputFormat(map, "png24");
      msInitializeRendererVTable(altFormat);
      /* TODO: check the png24 format hasn't been tampered with, i.e. it's agg */
      maskLayer->maskimage= msImageCreate(image->width, image->height,altFormat,
                                          image->imagepath, image->imageurl, map->resolution, map->defresolution, NULL);
      if (!maskLayer->maskimage) {
        msSetError(MS_MISCERR, "Unable to initialize mask image.", "msDrawLayer()");
        return (MS_FAILURE);
      }

      /*
       * force the masked layer to status on, and turn off the labelcache so that
       * eventual labels are added to the temporary image instead of being added
       * to the labelcache
       */
      origstatus = maskLayer->status;
      origlabelcache = maskLayer->labelcache;
      maskLayer->status = MS_ON;
      maskLayer->labelcache = MS_OFF;

      /* draw the mask layer in the temporary image */
      retcode = msDrawLayer(map, maskLayer, maskLayer->maskimage);
      maskLayer->status = origstatus;
      maskLayer->labelcache = origlabelcache;
      if(retcode != MS_SUCCESS) {
        return MS_FAILURE;
      }
      /*
       * hack to work around bug #3834: if we have use an alternate renderer, the symbolset may contain
       * symbols that reference it. We want to remove those references before the altFormat is destroyed
       * to avoid a segfault and/or a leak, and so the the main renderer doesn't pick the cache up thinking
       * it's for him.
       */
      for(i=0; i<map->symbolset.numsymbols; i++) {
        if (map->symbolset.symbol[i]!=NULL) {
          symbolObj *s = map->symbolset.symbol[i];
          if(s->renderer == MS_IMAGE_RENDERER(maskLayer->maskimage)) {
            MS_IMAGE_RENDERER(maskLayer->maskimage)->freeSymbol(s);
            s->renderer = NULL;
          }
        }
      }
      /* set the imagetype from the original outputformat back (it was removed by msSelectOutputFormat() */
      msFree(map->imagetype);
      map->imagetype = msStrdup(image->format->name);
    }

  }
  altFormat = NULL;
745 746 747
  /* inform the rendering device that layer draw is starting. */
  msImageStartLayer(map, layer, image);

748

749 750
  /*check if an alternative renderer should be used for this layer*/
  alternativeFomatString = msLayerGetProcessingKey( layer, "RENDERER");
751 752 753 754 755 756 757 758 759 760 761
  if (MS_RENDERER_PLUGIN(image_draw->format) && alternativeFomatString!=NULL &&
      (altFormat=  msSelectOutputFormat(map, alternativeFomatString))) {
    rendererVTableObj *renderer=NULL;
    msInitializeRendererVTable(altFormat);

    image_draw = msImageCreate(image->width, image->height,
                               altFormat, image->imagepath, image->imageurl, map->resolution, map->defresolution, &map->imagecolor);
    renderer = MS_IMAGE_RENDERER(image_draw);
    renderer->startLayer(image_draw,map,layer);
  } else if (MS_RENDERER_PLUGIN(image_draw->format)) {
    rendererVTableObj *renderer = MS_IMAGE_RENDERER(image_draw);
762
    if ((layer->mask && layer->connectiontype!=MS_WMS && layer->type != MS_LAYER_RASTER) || layer->compositer) {
763 764 765
      /* masking occurs at the pixel/layer level for raster images, so we don't need to create a temporary image
       in these cases
       */
766
      if (layer->mask || renderer->compositeRasterBuffer) {
767 768 769 770 771 772 773 774 775 776 777 778 779
        image_draw = msImageCreate(image->width, image->height,
                                   image->format, image->imagepath, image->imageurl, map->resolution, map->defresolution, NULL);
        if (!image_draw) {
          msSetError(MS_MISCERR, "Unable to initialize temporary transparent image.",
                     "msDrawLayer()");
          return (MS_FAILURE);
        }
        renderer->startLayer(image_draw,map,layer);
      }
    }
  }
  /*
  ** redirect procesing of some layer types.
780 781 782 783
  */
  if(layer->connectiontype == MS_WMS) {
#ifdef USE_WMS_LYR
    retcode = msDrawWMSLayer(map, layer, image_draw);
784
#else
785 786 787 788 789 790 791 792 793 794
    retcode = MS_FAILURE;
#endif
  } else if(layer->type == MS_LAYER_RASTER) {
    retcode = msDrawRasterLayer(map, layer, image_draw);
  } else if(layer->type == MS_LAYER_CHART) {
    retcode = msDrawChartLayer(map, layer, image_draw);
  } else {   /* must be a Vector layer */
    retcode = msDrawVectorLayer(map, layer, image_draw);
  }

795 796 797 798 799 800
  if (altFormat) {
    rendererVTableObj *renderer = MS_IMAGE_RENDERER(image);
    rendererVTableObj *altrenderer = MS_IMAGE_RENDERER(image_draw);
    rasterBufferObj rb;
    int i;
    memset(&rb,0,sizeof(rasterBufferObj));
801

802
    altrenderer->endLayer(image_draw,map,layer);
803

804 805 806 807 808 809 810 811
    retcode = altrenderer->getRasterBufferHandle(image_draw,&rb);
    if(UNLIKELY(retcode == MS_FAILURE)) {
      goto altformat_cleanup;
    }
    retcode = renderer->mergeRasterBuffer(image,&rb,((layer->compositer)?(layer->compositer->opacity*0.01):(1.0)),0,0,0,0,rb.width,rb.height);
    if(UNLIKELY(retcode == MS_FAILURE)) {
      goto altformat_cleanup;
    }
812

813
altformat_cleanup:
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
    /*
     * hack to work around bug #3834: if we have use an alternate renderer, the symbolset may contain
     * symbols that reference it. We want to remove those references before the altFormat is destroyed
     * to avoid a segfault and/or a leak, and so the the main renderer doesn't pick the cache up thinking
     * it's for him.
     */
    for(i=0; i<map->symbolset.numsymbols; i++) {
      if (map->symbolset.symbol[i]!=NULL) {
        symbolObj *s = map->symbolset.symbol[i];
        if(s->renderer == altrenderer) {
          altrenderer->freeSymbol(s);
          s->renderer = NULL;
        }
      }
    }
    msFreeImage(image_draw);
    /* set the imagetype from the original outputformat back (it was removed by msSelectOutputFormat() */
    msFree(map->imagetype);
    map->imagetype = msStrdup(image->format->name);
  } else if( image != image_draw) {
    rendererVTableObj *renderer = MS_IMAGE_RENDERER(image_draw);
    rasterBufferObj rb;
    memset(&rb,0,sizeof(rasterBufferObj));

    renderer->endLayer(image_draw,map,layer);

840 841 842 843
    retcode = renderer->getRasterBufferHandle(image_draw,&rb);
    if(UNLIKELY(retcode == MS_FAILURE)) {
      goto imagedraw_cleanup;
    }
844 845 846 847
    if(maskLayer && maskLayer->maskimage) {
      rasterBufferObj mask;
      unsigned int row,col;
      memset(&mask,0,sizeof(rasterBufferObj));
848 849 850 851
      retcode = MS_IMAGE_RENDERER(maskLayer->maskimage)->getRasterBufferHandle(maskLayer->maskimage,&mask);
      if(UNLIKELY(retcode == MS_FAILURE)) {
        goto imagedraw_cleanup;
      }
852 853 854 855 856 857 858 859 860 861 862 863 864
      /* modify the pixels of the overlay */

      if(rb.type == MS_BUFFER_BYTE_RGBA) {
        for(row=0; row<rb.height; row++) {
          unsigned char *ma,*a,*r,*g,*b;
          r=rb.data.rgba.r+row*rb.data.rgba.row_step;
          g=rb.data.rgba.g+row*rb.data.rgba.row_step;
          b=rb.data.rgba.b+row*rb.data.rgba.row_step;
          a=rb.data.rgba.a+row*rb.data.rgba.row_step;
          ma=mask.data.rgba.a+row*mask.data.rgba.row_step;
          for(col=0; col<rb.width; col++) {
            if(*ma == 0) {
              *a = *r = *g = *b = 0;
865
            }
866 867 868 869 870 871 872
            a+=rb.data.rgba.pixel_step;
            r+=rb.data.rgba.pixel_step;
            g+=rb.data.rgba.pixel_step;
            b+=rb.data.rgba.pixel_step;
            ma+=mask.data.rgba.pixel_step;
          }
        }
873
      }
874
    }
875 876 877 878 879 880 881 882 883 884 885
    if(!layer->compositer) {
      /*we have a mask layer with no composition configured, do a nomral blend */
      retcode = renderer->mergeRasterBuffer(image,&rb,1.0,0,0,0,0,rb.width,rb.height);
    } else {
      retcode = msCompositeRasterBuffer(image,&rb,layer->compositer);
    }
    if(UNLIKELY(retcode == MS_FAILURE)) {
      goto imagedraw_cleanup;
    }

imagedraw_cleanup:
886
    msFreeImage(image_draw);
887 888
  }

889
  msImageEndLayer(map,layer,image);
890 891 892 893 894 895
  return(retcode);
}

int msDrawVectorLayer(mapObj *map, layerObj *layer, imageObj *image)
{
  int         status, retcode=MS_SUCCESS;
896
  int         drawmode=MS_DRAWMODE_FEATURES;
897 898 899 900 901 902 903 904
  char        annotate=MS_TRUE;
  shapeObj    shape;
  rectObj     searchrect;
  char        cache=MS_FALSE;
  int         maxnumstyles=1;
  featureListNodeObjPtr shpcache=NULL, current=NULL;
  int nclasses = 0;
  int *classgroup = NULL;
905 906 907
  double minfeaturesize = -1;
  int maxfeatures=-1;
  int featuresdrawn=0;
908

909 910
  if (image)
    maxfeatures=msLayerGetMaxFeaturesToDraw(layer, image->format);
911 912

  /* TODO TBT: draw as raster layer in vector renderers */
913 914 915 916 917 918 919 920 921 922

  annotate = msEvalContext(map, layer, layer->labelrequires);
  if(map->scaledenom > 0) {
    if((layer->labelmaxscaledenom != -1) && (map->scaledenom >= layer->labelmaxscaledenom)) annotate = MS_FALSE;
    if((layer->labelminscaledenom != -1) && (map->scaledenom < layer->labelminscaledenom)) annotate = MS_FALSE;
  }

  /* open this layer */
  status = msLayerOpen(layer);
  if(status != MS_SUCCESS) return MS_FAILURE;
923

924
  /* build item list. STYLEITEM javascript needs the shape attributes */
925
  if (layer->styleitem && (strncasecmp(layer->styleitem, "javascript://", 13) == 0)) {  
926 927 928
    status = msLayerWhichItems(layer, MS_TRUE, NULL);
  } else {
    status = msLayerWhichItems(layer, MS_FALSE, NULL);
929
  }
930

931 932 933 934 935
  if(status != MS_SUCCESS) {
    msLayerClose(layer);
    return MS_FAILURE;
  }

936
  /* identify target shapes */
937
  if(layer->transform == MS_TRUE) {
938
    searchrect = map->extent;
939 940 941 942
#ifdef USE_PROJ
    if((map->projection.numargs > 0) && (layer->projection.numargs > 0))
      msProjectRect(&map->projection, &layer->projection, &searchrect); /* project the searchrect to source coords */
#endif
943
  } else {
944 945 946 947
    searchrect.minx = searchrect.miny = 0;
    searchrect.maxx = map->width-1;
    searchrect.maxy = map->height-1;
  }
948

949
  status = msLayerWhichShapes(layer, searchrect, MS_FALSE);
950 951 952 953 954 955 956
  if(status == MS_DONE) { /* no overlap */
    msLayerClose(layer);
    return MS_SUCCESS;
  } else if(status != MS_SUCCESS) {
    msLayerClose(layer);
    return MS_FAILURE;
  }
957

958 959
  /* step through the target shapes */
  msInitShape(&shape);
960

961 962
  nclasses = 0;
  classgroup = NULL;
963 964 965 966 967
  if(layer->classgroup && layer->numclasses > 0)
    classgroup = msAllocateValidClassGroups(layer, &nclasses);

  if(layer->minfeaturesize > 0)
    minfeaturesize = Pix2LayerGeoref(map, layer, layer->minfeaturesize);
968 969 970

  while((status = msLayerNextShape(layer, &shape)) == MS_SUCCESS) {

971 972 973
    /* Check if the shape size is ok to be drawn */
    if((shape.type == MS_SHAPE_LINE || shape.type == MS_SHAPE_POLYGON) && (minfeaturesize > 0) && (msShapeCheckSize(&shape, minfeaturesize) == MS_FALSE)) {
      if(layer->debug >= MS_DEBUGLEVEL_V)
974
        msDebug("msDrawVectorLayer(): Skipping shape (%ld) because LAYER::MINFEATURESIZE is bigger than shape size\n", shape.index);
975 976 977 978 979
      msFreeShape(&shape);
      continue;
    }

    shape.classindex = msShapeGetClass(layer, map, &shape, classgroup, nclasses);
980
    if((shape.classindex == -1) || (layer->class[shape.classindex]->status == MS_OFF)) {
981 982
      msFreeShape(&shape);
      continue;
983
    }
984 985

    if(maxfeatures >=0 && featuresdrawn >= maxfeatures) {
986
      msFreeShape(&shape);
987 988
      status = MS_DONE;
      break;
989 990 991
    }
    featuresdrawn++;

992
    cache = MS_FALSE;
993
    if(layer->type == MS_LAYER_LINE && (layer->class[shape.classindex]->numstyles > 1 || (layer->class[shape.classindex]->numstyles == 1 && layer->class[shape.classindex]->styles[0]->outlinewidth > 0))) {
994
      int i;
995
      cache = MS_TRUE; /* only line layers with multiple styles need be cached (I don't think POLYLINE layers need caching - SDL) */
996 997

      /* we can't handle caching with attribute binding other than for the first style (#3976) */
998
      for(i=1; i<layer->class[shape.classindex]->numstyles; i++) {
999 1000 1001
        if(layer->class[shape.classindex]->styles[i]->numbindings > 0) cache = MS_FALSE;
      }
    }
1002

1003 1004
    /* With 'STYLEITEM AUTO', we will have the datasource fill the class' */
    /* style parameters for this shape. */
1005
    if(layer->styleitem) {
1006 1007 1008
      if(strcasecmp(layer->styleitem, "AUTO") == 0) {
        if(msLayerGetAutoStyle(map, layer, layer->class[shape.classindex], &shape) != MS_SUCCESS) {
          retcode = MS_FAILURE;
1009
          msFreeShape(&shape);
1010
          break;
1011
        }
1012 1013 1014 1015
      } else {
        /* Generic feature style handling as per RFC-61 */
        if(msLayerGetFeatureStyle(map, layer, layer->class[shape.classindex], &shape) != MS_SUCCESS) {
          retcode = MS_FAILURE;
1016
          msFreeShape(&shape);
1017
          break;
1018
        }
1019
      }
1020

1021 1022 1023 1024
      /* __TODO__ For now, we can't cache features with 'AUTO' style */
      cache = MS_FALSE;
    }

1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
    /* RFC77 TODO: check return value, may need a more sophisticated if-then test. */
    if(annotate && layer->class[shape.classindex]->numlabels > 0) {
      drawmode |= MS_DRAWMODE_LABELS;
      if (msLayerGetProcessingKey(layer, "LABEL_NO_CLIP")) {
        drawmode |= MS_DRAWMODE_UNCLIPPEDLABELS;
      }
    }

    if (layer->type == MS_LAYER_LINE && msLayerGetProcessingKey(layer, "POLYLINE_NO_CLIP")) {
      drawmode |= MS_DRAWMODE_UNCLIPPEDLINES;
    }
1036

1037
    if (cache) {
1038 1039
      styleObj *pStyle = layer->class[shape.classindex]->styles[0];
      if (pStyle->outlinewidth > 0) {
1040 1041 1042 1043 1044 1045 1046 1047
        /*
         * RFC 49 implementation
         * if an outlinewidth is used:
         *  - augment the style's width to account for the outline width
         *  - swap the style color and outlinecolor
         *  - draw the shape (the outline) in the first pass of the
         *    caching mechanism
         */
1048
	msOutlineRenderingPrepareStyle(pStyle, map, layer, image);
1049 1050
      }
      status = msDrawShape(map, layer, &shape, image, 0, drawmode|MS_DRAWMODE_SINGLESTYLE); /* draw a single style */
1051
      if (pStyle->outlinewidth > 0) {
1052 1053 1054 1055 1056
        /*
         * RFC 49 implementation: switch back the styleobj to its
         * original state, so the line fill will be drawn in the
         * second pass of the caching mechanism
         */
1057
	msOutlineRenderingRestoreStyle(pStyle, map, layer, image);
1058
      }
1059 1060 1061
    }

    else
1062
      status = msDrawShape(map, layer, &shape, image, -1, drawmode); /* all styles  */
1063 1064 1065 1066 1067
    if(status != MS_SUCCESS) {
      msFreeShape(&shape);
      retcode = MS_FAILURE;
      break;
    }
1068
    
1069 1070 1071 1072
    if(shape.numlines == 0) { /* once clipped the shape didn't need to be drawn */
      msFreeShape(&shape);
      continue;
    }
1073

1074 1075
    if(cache) {
      if(insertFeatureList(&shpcache, &shape) == NULL) {
1076
        msFreeShape(&shape);
1077 1078 1079
        retcode = MS_FAILURE; /* problem adding to the cache */
        break;
      }
1080
    }
1081 1082

    maxnumstyles = MS_MAX(maxnumstyles, layer->class[shape.classindex]->numstyles);
1083

1084 1085
    msFreeShape(&shape);
  }
1086

1087 1088 1089
  if (classgroup)
    msFree(classgroup);

1090
  if(status != MS_DONE || retcode == MS_FAILURE) {
1091
    msLayerClose(layer);
1092 1093 1094 1095
    if(shpcache) {
      freeFeatureList(shpcache);
      shpcache = NULL;
    }
1096 1097
    return MS_FAILURE;
  }
1098 1099

  if(shpcache && MS_DRAW_FEATURES(drawmode)) {
1100 1101 1102 1103 1104
    int s;
    for(s=0; s<maxnumstyles; s++) {
      for(current=shpcache; current; current=current->next) {
        if(layer->class[current->shape.classindex]->numstyles > s) {
          styleObj *pStyle = layer->class[current->shape.classindex]->styles[s];
1105 1106
          if(pStyle->_geomtransform.type != MS_GEOMTRANSFORM_NONE)
            continue; /*skip this as it has already been rendered*/
1107 1108 1109 1110 1111 1112 1113
          if(map->scaledenom > 0) {
            if((pStyle->maxscaledenom != -1) && (map->scaledenom >= pStyle->maxscaledenom))
              continue;
            if((pStyle->minscaledenom != -1) && (map->scaledenom < pStyle->minscaledenom))
              continue;
          }
          if(s==0 && pStyle->outlinewidth>0 && MS_VALID_COLOR(pStyle->color)) {
1114 1115 1116
            if(UNLIKELY(MS_FAILURE == msDrawLineSymbol(map, image, &current->shape, pStyle, layer->scalefactor))) {
              return MS_FAILURE;
            }
1117
          } else if(s>0) {
1118 1119 1120 1121 1122 1123 1124 1125 1126
            if (pStyle->outlinewidth > 0 && MS_VALID_COLOR(pStyle->outlinecolor)) {
              /*
               * RFC 49 implementation
               * if an outlinewidth is used:
               *  - augment the style's width to account for the outline width
               *  - swap the style color and outlinecolor
               *  - draw the shape (the outline) in the first pass of the
               *    caching mechanism
               */
1127
	      msOutlineRenderingPrepareStyle(pStyle, map, layer, image);
1128 1129 1130
              if(UNLIKELY(MS_FAILURE == msDrawLineSymbol(map, image, &current->shape, pStyle, layer->scalefactor))) {
                return MS_FAILURE;
              }
1131 1132 1133 1134 1135
              /*
               * RFC 49 implementation: switch back the styleobj to its
               * original state, so the line fill will be drawn in the
               * second pass of the caching mechanism
               */
1136
	      msOutlineRenderingRestoreStyle(pStyle, map, layer, image);
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
            }
            /* draw a valid line, i.e. one with a color defined or of type pixmap*/
            if(MS_VALID_COLOR(pStyle->color) || 
                    (
                      pStyle->symbol<map->symbolset.numsymbols &&
                      ( 
                        map->symbolset.symbol[pStyle->symbol]->type == MS_SYMBOL_PIXMAP ||
                        map->symbolset.symbol[pStyle->symbol]->type == MS_SYMBOL_SVG
                      )
                    )
              ) {
1148 1149
              if(UNLIKELY(MS_FAILURE == msDrawLineSymbol(map, image, &current->shape, pStyle, layer->scalefactor)))
                return MS_FAILURE;
1150 1151 1152 1153
            }
          }
        }
      }
1154
    }
1155

1156
    freeFeatureList(shpcache);
1157
    shpcache = NULL;
1158 1159
  }

1160
  msLayerClose(layer);
1161
  return MS_SUCCESS;
1162

1163 1164 1165 1166 1167 1168 1169 1170 1171
}

/*
** Function to draw a layer IF it already has a result cache associated with it. Called by msDrawMap and via MapScript.
*/
int msDrawQueryLayer(mapObj *map, layerObj *layer, imageObj *image)
{
  int i, status;
  char annotate=MS_TRUE, cache=MS_FALSE;
1172
  int drawmode = MS_DRAWMODE_FEATURES|MS_DRAWMODE_QUERY;
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
  shapeObj shape;
  int maxnumstyles=1;

  featureListNodeObjPtr shpcache=NULL, current=NULL;

  colorObj *colorbuffer = NULL;
  int *mindistancebuffer = NULL;

  if(!layer->resultcache) return(msDrawLayer(map, layer, image));

  if(!msLayerIsVisible(map, layer)) return(MS_SUCCESS); /* not an error, just nothing to do */

  /* conditions may have changed since this layer last drawn, so set
     layer->project true to recheck projection needs (Bug #673) */
  layer->project = MS_TRUE;

  /* set annotation status */
  annotate = msEvalContext(map, layer, layer->labelrequires);
  if(map->scaledenom > 0) {
    if((layer->labelmaxscaledenom != -1) && (map->scaledenom >= layer->labelmaxscaledenom)) annotate = MS_FALSE;
    if((layer->labelminscaledenom != -1) && (map->scaledenom < layer->labelminscaledenom)) annotate = MS_FALSE;
  }

  /*
1197
  ** Certain query map styles require us to render all features only (MS_NORMAL) or first (MS_HILITE). With
1198 1199 1200 1201 1202
  ** single-pass queries we have to make a copy of the layer and work from it instead.
  */
  if(map->querymap.style == MS_NORMAL || map->querymap.style == MS_HILITE) {
    layerObj tmp_layer;

1203 1204
    if(initLayer(&tmp_layer, map) == -1)
      return(MS_FAILURE);
1205

1206 1207
    if (msCopyLayer(&tmp_layer, layer) != MS_SUCCESS)
      return(MS_FAILURE);
1208

1209 1210 1211
    /* disable the connection pool for this layer */
    msLayerSetProcessingKey(&tmp_layer, "CLOSE_CONNECTION", "ALWAYS");

1212 1213
    status = msDrawLayer(map, &tmp_layer, image);

1214
    freeLayer(&tmp_layer);
1215 1216 1217 1218 1219 1220 1221 1222

    if(map->querymap.style == MS_NORMAL || status != MS_SUCCESS) return(status);
  }


  /* if MS_HILITE, alter the one style (always at least 1 style), and set a MINDISTANCE for the labelObj to avoid duplicates */
  if(map->querymap.style == MS_HILITE) {
    if (layer->numclasses > 0) {
1223 1224
      colorbuffer = (colorObj*)msSmallMalloc(layer->numclasses*sizeof(colorObj));
      mindistancebuffer = (int*)msSmallMalloc(layer->numclasses*sizeof(int));
1225 1226 1227 1228
    }

    for(i=0; i<layer->numclasses; i++) {
      if(layer->type == MS_LAYER_POLYGON) { /* alter BOTTOM style since that's almost always the fill */
1229 1230
        if (layer->class[i]->styles == NULL) {
          msSetError(MS_MISCERR, "Don't know how to draw class %s of layer %s without a style definition.", "msDrawQueryLayer()", layer->class[i]->name, layer->name);
1231 1232
          msFree(colorbuffer);
          msFree(mindistancebuffer);
1233 1234
          return(MS_FAILURE);
        }
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
        if(MS_VALID_COLOR(layer->class[i]->styles[0]->color)) {
          colorbuffer[i] = layer->class[i]->styles[0]->color; /* save the color from the BOTTOM style */
          layer->class[i]->styles[0]->color = map->querymap.color;
        } else if(MS_VALID_COLOR(layer->class[i]->styles[0]->outlinecolor)) {
          colorbuffer[i] = layer->class[i]->styles[0]->outlinecolor; /* if no color, save the outlinecolor from the BOTTOM style */
          layer->class[i]->styles[0]->outlinecolor = map->querymap.color;
        }
      } else {
        if(MS_VALID_COLOR(layer->class[i]->styles[layer->class[i]->numstyles-1]->color)) {
          colorbuffer[i] = layer->class[i]->styles[layer->class[i]->numstyles-1]->color; /* save the color from the TOP style */
          layer->class[i]->styles[layer->class[i]->numstyles-1]->color = map->querymap.color;
        } else if(MS_VALID_COLOR(layer->class[i]->styles[layer->class[i]->numstyles-1]->outlinecolor)) {
1247
          colorbuffer[i] = layer->class[i]->styles[layer->class[i]->numstyles-1]->outlinecolor; /* if no color, save the outlinecolor from the TOP style */
1248 1249 1250 1251
          layer->class[i]->styles[layer->class[i]->numstyles-1]->outlinecolor = map->querymap.color;
        }
      }

1252 1253 1254 1255 1256
      mindistancebuffer[i] = -1; /* RFC77 TODO: only using the first label, is that cool? */
      if(layer->class[i]->numlabels > 0) {
        mindistancebuffer[i] = layer->class[i]->labels[0]->mindistance;
        layer->class[i]->labels[0]->mindistance = MS_MAX(0, layer->class[i]->labels[0]->mindistance);
      }
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
    }
  }

  /*
  ** Layer was opened as part of the query process, msLayerWhichItems() has also been run, shapes have been classified - start processing!
  */

  msInitShape(&shape);

  for(i=0; i<layer->resultcache->numresults; i++) {
1267
    status = msLayerGetShape(layer, &shape, &(layer->resultcache->results[i]));
1268
    if(status != MS_SUCCESS) {
1269 1270 1271
      msFree(colorbuffer);
      msFree(mindistancebuffer);
      return(MS_FAILURE);
1272 1273 1274 1275 1276
    }

    shape.classindex = layer->resultcache->results[i].classindex;
    /* classindex may be -1 here if there was a template at the top level
     * in this layer and the current shape selected even if it didn't
1277
     * match any class
1278
     *
1279
     * FrankW: classindex is also sometimes 0 even if there are no classes, so
1280 1281
     * we are careful not to use out of range class values as an index.
     */
1282 1283 1284
    if(shape.classindex==-1
        || shape.classindex >= layer->numclasses
        || layer->class[shape.classindex]->status == MS_OFF) {
1285 1286 1287 1288 1289
      msFreeShape(&shape);
      continue;
    }

    cache = MS_FALSE;
1290
    if(layer->type == MS_LAYER_LINE && layer->class[shape.classindex]->numstyles > 1)
1291 1292
      cache = MS_TRUE; /* only line layers with multiple styles need be cached (I don't think POLYLINE layers need caching - SDL) */

1293 1294 1295
    if(annotate && layer->class[shape.classindex]->numlabels > 0) {
      drawmode |= MS_DRAWMODE_LABELS;
    }
1296

1297 1298 1299 1300
    if(cache) {
      drawmode |= MS_DRAWMODE_SINGLESTYLE;
      status = msDrawShape(map, layer, &shape, image, 0, drawmode); /* draw only the first style */
    }
1301
    else
1302
      status = msDrawShape(map, layer, &shape, image, -1, drawmode); /* all styles  */
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
    if(status != MS_SUCCESS) {
      msLayerClose(layer);
      msFree(colorbuffer);
      msFree(mindistancebuffer);
      return(MS_FAILURE);
    }

    if(shape.numlines == 0) { /* once clipped the shape didn't need to be drawn */
      msFreeShape(&shape);
      continue;
    }

    if(cache) {
1316 1317 1318 1319 1320
      if(insertFeatureList(&shpcache, &shape) == NULL) {
        msFree(colorbuffer);
        msFree(mindistancebuffer);
        return(MS_FAILURE); /* problem adding to the cache */
      }
1321 1322 1323 1324 1325 1326 1327 1328
    }

    maxnumstyles = MS_MAX(maxnumstyles, layer->class[shape.classindex]->numstyles);
    msFreeShape(&shape);
  }

  if(shpcache) {
    int s;
1329

1330
    for(s=1; s<maxnumstyles; s++) {
1331
      for(current=shpcache; current; current=current->next) {
1332 1333 1334 1335 1336 1337 1338 1339
        if(layer->class[current->shape.classindex]->numstyles > s) {
          styleObj *curStyle = layer->class[current->shape.classindex]->styles[s];
          if(map->scaledenom > 0) {
            if((curStyle->maxscaledenom != -1) && (map->scaledenom >= curStyle->maxscaledenom))
              continue;
            if((curStyle->minscaledenom != -1) && (map->scaledenom < curStyle->minscaledenom))
              continue;
          }
1340 1341
          if(UNLIKELY(MS_FAILURE == msDrawLineSymbol(map, image, &current->shape, (layer->class[current->shape.classindex]->styles[s]), layer->scalefactor)))
            return MS_FAILURE;
1342 1343 1344
        }
      }
    }
1345

1346
    freeFeatureList(shpcache);
1347
    shpcache = NULL;
1348 1349 1350 1351 1352 1353
  }

  /* if MS_HILITE, restore color and mindistance values */
  if(map->querymap.style == MS_HILITE) {
    for(i=0; i<layer->numclasses; i++) {
      if(layer->type == MS_LAYER_POLYGON) {
1354
        if(MS_VALID_COLOR(layer->class[i]->styles[0]->color))
1355 1356 1357 1358 1359
          layer->class[i]->styles[0]->color = colorbuffer[i];
        else if(MS_VALID_COLOR(layer->class[i]->styles[0]->outlinecolor))
          layer->class[i]->styles[0]->outlinecolor = colorbuffer[i]; /* if no color, restore outlinecolor for the BOTTOM style */
      } else {
        if(MS_VALID_COLOR(layer->class[i]->styles[layer->class[i]->numstyles-1]->color))
1360
          layer->class[i]->styles[layer->class[i]->numstyles-1]->color = colorbuffer[i];
1361
        else if(MS_VALID_COLOR(layer->class[i]->styles[layer->class[i]->numstyles-1]->outlinecolor))
1362
          layer->class[i]->styles[layer->class[i]->numstyles-1]->outlinecolor = colorbuffer[i]; /* if no color, restore outlinecolor for the TOP style */
1363
      }
1364 1365 1366 1367

      if(layer->class[i]->numlabels > 0)
        layer->class[i]->labels[0]->mindistance = mindistancebuffer[i]; /* RFC77 TODO: again, only using the first label, is that cool? */

1368 1369 1370 1371 1372 1373 1374 1375 1376
    }

    msFree(colorbuffer);
    msFree(mindistancebuffer);
  }

  return(MS_SUCCESS);
}

1377 1378 1379 1380
/**
 * msDrawRasterLayerPlugin()
 */

1381 1382
static int
msDrawRasterLayerPlugin( mapObj *map, layerObj *layer, imageObj *image)
1383 1384

{
1385 1386 1387 1388 1389 1390 1391
  rendererVTableObj *renderer = MS_IMAGE_RENDERER(image);
  rasterBufferObj  *rb = msSmallCalloc(1,sizeof(rasterBufferObj));
  int ret;
  if( renderer->supports_pixel_buffer ) {
    if (MS_SUCCESS != renderer->getRasterBufferHandle( image, rb )) {
      msSetError(MS_MISCERR,"renderer failed to extract raster buffer","msDrawRasterLayer()");
      return MS_FAILURE;
1392
    }
1393 1394 1395 1396 1397 1398 1399 1400
    ret = msDrawRasterLayerLow( map, layer, image, rb );
  } else {
    if (MS_SUCCESS != renderer->initializeRasterBuffer( rb, image->width, image->height, MS_IMAGEMODE_RGBA )) {
      msSetError(MS_MISCERR,"renderer failed to create raster buffer","msDrawRasterLayer()");
      return MS_FAILURE;
    }

    ret = msDrawRasterLayerLow( map, layer, image, rb );
1401

1402
    if( ret == 0 ) {
1403
      ret = renderer->mergeRasterBuffer( image, rb, 1.0, 0, 0, 0, 0, rb->width, rb->height );
1404
    }
1405 1406 1407

    msFreeRasterBuffer(rb);
  }
1408 1409 1410 1411 1412
#define RB_GET_R(rb,x,y) *((rb)->data.rgba.r + (x) * (rb)->data.rgba.pixel_step + (y) * (rb)->data.rgba.row_step)
#define RB_GET_G(rb,x,y) *((rb)->data.rgba.g + (x) * (rb)->data.rgba.pixel_step + (y) * (rb)->data.rgba.row_step)
#define RB_GET_B(rb,x,y) *((rb)->data.rgba.b + (x) * (rb)->data.rgba.pixel_step + (y) * (rb)->data.rgba.row_step)
#define RB_GET_A(rb,x,y) *((rb)->data.rgba.a + (x) * (rb)->data.rgba.pixel_step + (y) * (rb)->data.rgba.row_step)

1413 1414 1415
  free(rb);

  return ret;
1416 1417
}

1418 1419 1420
/**
 * Generic function to render raster layers.
 */
1421
int msDrawRasterLayer(mapObj *map, layerObj *layer, imageObj *image)
1422
{
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
  
  int rv = MS_FAILURE;
  if (!image || !map || !layer) {
    return rv;
  }

  /* RFC-86 Scale dependant token replacements*/
  rv = msLayerApplyScaletokens(layer,(layer->map)?layer->map->scaledenom:-1);
  if (rv != MS_SUCCESS) return rv;
  if( MS_RENDERER_PLUGIN(image->format) )
    rv = msDrawRasterLayerPlugin(map, layer, image);
  else if( MS_RENDERER_RAWDATA(image->format) )
    rv = msDrawRasterLayerLow(map, layer, image, NULL);
  msLayerRestoreFromScaletokens(layer);
  return rv;
1438 1439 1440 1441 1442
}

/**
 * msDrawWMSLayer()
 *
1443
 * Draw a single WMS layer.
1444 1445 1446 1447 1448 1449 1450
 * Multiple WMS layers in a map are preloaded and then drawn using
 * msDrawWMSLayerLow()
 */

#ifdef USE_WMS_LYR
int msDrawWMSLayer(mapObj *map, layerObj *layer, imageObj *image)
{
1451
  int nStatus = MS_FAILURE;
1452

1453 1454 1455 1456 1457 1458
  if (image && map && layer) {
    /* ------------------------------------------------------------------
     * Start by downloading the layer
     * ------------------------------------------------------------------ */
    httpRequestObj asReqInfo[2];
    int numReq = 0;
1459

1460 1461 1462 1463 1464 1465 1466
    msHTTPInitRequestObj(asReqInfo, 2);

    if ( msPrepareWMSLayerRequest(1, map, layer, 1,
                                  0, NULL, 0, 0, 0, NULL,
                                  asReqInfo, &numReq) == MS_FAILURE  ||
         msOWSExecuteRequests(asReqInfo, numReq, map, MS_TRUE) == MS_FAILURE ) {
      return MS_FAILURE;
1467 1468
    }

1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
    /* ------------------------------------------------------------------
     * Then draw layer based on output format
     * ------------------------------------------------------------------ */
    if( MS_RENDERER_PLUGIN(image->format) )
      nStatus = msDrawWMSLayerLow(1, asReqInfo, numReq,
                                  map, layer, image) ;
    else if( MS_RENDERER_RAWDATA(image->format) )
      nStatus = msDrawWMSLayerLow(1, asReqInfo, numReq,
                                  map, layer, image) ;

    else {
      msSetError(MS_WMSCONNERR,
                 "Output format '%s' doesn't support WMS layers.",
                 "msDrawWMSLayer()", image->format->name);
      nStatus = MS_SUCCESS; /* Should we fail if output doesn't support WMS? */
    }
    /* Cleanup */
    msHTTPFreeRequestObj(asReqInfo, numReq);
  }

  return nStatus;
1490 1491 1492
}
#endif

1493
int circleLayerDrawShape(mapObj *map, imageObj *image, layerObj *layer, shapeObj *shape)
1494
{
1495 1496 1497 1498
  pointObj center;
  double r;
  int s;
  int c = shape->classindex;
1499

1500 1501
  if (shape->numlines != 1) return (MS_SUCCESS); /* invalid shape */
  if (shape->line[0].numpoints != 2) return (MS_SUCCESS); /* invalid shape */
1502

1503 1504 1505 1506 1507 1508 1509
  center.x = (shape->line[0].point[0].x + shape->line[0].point[1].x) / 2.0;
  center.y = (shape->line[0].point[0].y + shape->line[0].point[1].y) / 2.0;
  r = MS_ABS(center.x - shape->line[0].point[0].x);
  if (r == 0)
    r = MS_ABS(center.y - shape->line[0].point[0].y);
  if (r == 0)
    return (MS_SUCCESS);
1510

1511
  if (layer->transform == MS_TRUE) {
1512

1513 1514 1515 1516 1517 1518
#ifdef USE_PROJ
    if (layer->project && msProjectionsDiffer(&(layer->projection), &(map->projection)))
      msProjectPoint(&layer->projection, &map->projection, &center);
    else
      layer->project = MS_FALSE;
#endif
1519

1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
    center.x = MS_MAP2IMAGE_X(center.x, map->extent.minx, map->cellsize);
    center.y = MS_MAP2IMAGE_Y(center.y, map->extent.maxy, map->cellsize);
    r /= map->cellsize;
  } else
    msOffsetPointRelativeTo(&center, layer);

  for (s = 0; s < layer->class[c]->numstyles; s++) {
    if (msScaleInBounds(map->scaledenom,
                        layer->class[c]->styles[s]->minscaledenom,
                        layer->class[c]->styles[s]->maxscaledenom))
Bas Couwenberg's avatar