Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: tiledWMS Client Driver
4 : * Purpose: Implementation of the OnEarth Tiled WMS minidriver.
5 : * http://onearth.jpl.nasa.gov/tiled.html
6 : * Author: Lucian Plesea (Lucian dot Plesea at jpl.nasa.gov)
7 : * Adam Nowacki
8 : *
9 : ******************************************************************************
10 : * Copyright (c) 2007, Adam Nowacki
11 : * Copyright (c) 2011-2012, Even Rouault <even dot rouault at spatialys.com>
12 : *
13 : * SPDX-License-Identifier: MIT
14 : ****************************************************************************/
15 :
16 : //
17 : // Also known as the OnEarth tile protocol
18 : //
19 : // A few open options are supported by tiled WMS
20 : //
21 : // TiledGroupName=<Name>
22 : //
23 : // This option is only valid when the WMS file does not contain a
24 : // TiledGroupName. The name value should match exactly the name declared by the
25 : // server, including possible white spaces, otherwise the open will fail.
26 : //
27 : // Change=<key>:<value>
28 : //
29 : // If the tiled group selected supports the change key, this option will set
30 : // the value The <key> here does not include the brackets present in the
31 : // GetTileService For example, if a TiledPattern include a key of ${time}, the
32 : // matching open option will be Change=time:<YYYY-MM-DD> The Change open option
33 : // may be present multiple times, with different keys If a key is not supported
34 : // by the selected TilePattern, the open will fail Alternate syntax is:
35 : // Change=<key>=<value>
36 : //
37 : // StoreConfiguration=Yes
38 : //
39 : // This boolean option is only useful when doing a createcopy of a tiledWMS
40 : // dataset into another tiledWMS dataset. When set, the source tiledWMS will
41 : // store the server configuration into the XML metadata representation, which
42 : // then gets copied to the XML output. This will eliminate the need to fetch
43 : // the server configuration when opening the output datafile
44 : //
45 :
46 : #include "wmsdriver.h"
47 : #include "minidriver_tiled_wms.h"
48 :
49 : #include <set>
50 :
51 : static const char SIG[] = "GDAL_WMS TiledWMS: ";
52 :
53 : /*
54 : *\brief Read a number from an xml element
55 : */
56 :
57 12 : static double getXMLNum(const CPLXMLNode *poRoot, const char *pszPath,
58 : const char *pszDefault)
59 : { // Sets errno
60 12 : return CPLAtof(CPLGetXMLValue(poRoot, pszPath, pszDefault));
61 : }
62 :
63 : /*
64 : *\brief Read a ColorEntry XML node, return a GDALColorEntry structure
65 : *
66 : */
67 :
68 0 : static GDALColorEntry GetXMLColorEntry(const CPLXMLNode *p)
69 : {
70 : GDALColorEntry ce;
71 0 : ce.c1 = static_cast<short>(getXMLNum(p, "c1", "0"));
72 0 : ce.c2 = static_cast<short>(getXMLNum(p, "c2", "0"));
73 0 : ce.c3 = static_cast<short>(getXMLNum(p, "c3", "0"));
74 0 : ce.c4 = static_cast<short>(getXMLNum(p, "c4", "255"));
75 0 : return ce;
76 : }
77 :
78 : /************************************************************************/
79 : /* SearchXMLSiblings() */
80 : /************************************************************************/
81 :
82 : /*
83 : * \brief Search for a sibling of the root node with a given name.
84 : *
85 : * Searches only the next siblings of the node passed in for the named element
86 : * or attribute. If the first character of the pszElement is '=', the search
87 : * includes the psRoot node
88 : *
89 : * @param psRoot the root node to search. This should be a node of type
90 : * CXT_Element. NULL is safe.
91 : *
92 : * @param pszElement the name of the element or attribute to search for.
93 : *
94 : *
95 : * @return The first matching node or NULL on failure.
96 : */
97 :
98 340 : static const CPLXMLNode *SearchXMLSiblings(const CPLXMLNode *psRoot,
99 : const char *pszElement)
100 :
101 : {
102 340 : if (psRoot == nullptr || pszElement == nullptr)
103 0 : return nullptr;
104 :
105 : // If the strings starts with '=', skip it and test the root
106 : // If not, start testing with the next sibling
107 340 : if (pszElement[0] == '=')
108 27 : pszElement++;
109 : else
110 313 : psRoot = psRoot->psNext;
111 :
112 4588 : for (; psRoot != nullptr; psRoot = psRoot->psNext)
113 : {
114 4275 : if ((psRoot->eType == CXT_Element || psRoot->eType == CXT_Attribute) &&
115 4275 : EQUAL(pszElement, psRoot->pszValue))
116 27 : return psRoot;
117 : }
118 313 : return nullptr;
119 : }
120 :
121 : /************************************************************************/
122 : /* SearchLeafGroupName() */
123 : /************************************************************************/
124 :
125 : /*
126 : * \brief Search for a leaf TileGroup node by name.
127 : *
128 : * @param psRoot the root node to search. This should be a node of type
129 : * CXT_Element. NULL is safe.
130 : *
131 : * @param pszElement the name of the TileGroup to search for.
132 : *
133 : * @return The XML node of the matching TileGroup or NULL on failure.
134 : */
135 :
136 310 : static CPLXMLNode *SearchLeafGroupName(CPLXMLNode *psRoot, const char *name)
137 :
138 : {
139 310 : if (psRoot == nullptr || name == nullptr)
140 0 : return nullptr;
141 :
142 : // Has to be a leaf TileGroup with the right name
143 310 : if (nullptr == SearchXMLSiblings(psRoot->psChild, "TiledGroup"))
144 : {
145 310 : if (EQUAL(name, CPLGetXMLValue(psRoot, "Name", "")))
146 3 : return psRoot;
147 : }
148 : else
149 : { // Is metagroup, try children then siblings
150 0 : CPLXMLNode *ret = SearchLeafGroupName(psRoot->psChild, name);
151 0 : if (nullptr != ret)
152 0 : return ret;
153 : }
154 307 : return SearchLeafGroupName(psRoot->psNext, name);
155 : }
156 :
157 : /************************************************************************/
158 : /* BandInterp() */
159 : /************************************************************************/
160 :
161 : /*
162 : * \brief Utility function to calculate color band interpretation.
163 : * Only handles Gray, GrayAlpha, RGB and RGBA, based on total band count
164 : *
165 : * @param nbands is the total number of bands in the image
166 : *
167 : * @param band is the band number, starting with 1
168 : *
169 : * @return GDALColorInterp of the band
170 : */
171 :
172 9 : static GDALColorInterp BandInterp(int nbands, int band)
173 : {
174 9 : switch (nbands)
175 : {
176 0 : case 1:
177 0 : return GCI_GrayIndex;
178 0 : case 2:
179 0 : return band == 1 ? GCI_GrayIndex : GCI_AlphaBand;
180 9 : case 3: // RGB
181 : case 4: // RBGA
182 9 : if (band < 3)
183 6 : return band == 1 ? GCI_RedBand : GCI_GreenBand;
184 3 : return band == 3 ? GCI_BlueBand : GCI_AlphaBand;
185 0 : default:
186 0 : return GCI_Undefined;
187 : }
188 : }
189 :
190 : /************************************************************************/
191 : /* FindBbox() */
192 : /************************************************************************/
193 :
194 : /*
195 : * \brief Utility function to find the position of the bbox parameter value
196 : * within a request string. The search for the bbox is case insensitive
197 : *
198 : * @param in, the string to search into
199 : *
200 : * @return The position from the beginning of the string or -1 if not found
201 : */
202 :
203 189 : static int FindBbox(CPLString in)
204 : {
205 :
206 189 : size_t pos = in.ifind("&bbox=");
207 189 : if (pos == std::string::npos)
208 0 : return -1;
209 189 : return (int)pos + 6;
210 : }
211 :
212 : /************************************************************************/
213 : /* FindChangePattern() */
214 : /************************************************************************/
215 :
216 : /*
217 : * \brief Build the right request pattern based on the change request list
218 : * It only gets called on initialization
219 : * @param cdata, possible request strings, white space separated
220 : * @param substs, the list of substitutions to be applied
221 : * @param keys, the list of available substitution keys
222 : * @param ret The return value, a matching request or an empty string
223 : */
224 :
225 27 : static void FindChangePattern(const char *cdata, const char *const *substs,
226 : const char *const *keys, CPLString &ret)
227 : {
228 : const CPLStringList aosTokens(CSLTokenizeString2(
229 27 : cdata, " \t\n\r", CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES));
230 27 : ret.clear();
231 :
232 27 : int matchcount = CSLCount(substs);
233 27 : int keycount = CSLCount(keys);
234 27 : if (keycount < matchcount)
235 : {
236 0 : return;
237 : }
238 :
239 : // A valid string has only the keys in the substs list and none other
240 36 : for (int j = 0; j < aosTokens.size(); j++)
241 : {
242 36 : ret = aosTokens[j]; // The target string
243 36 : bool matches = true;
244 :
245 72 : for (int k = 0; k < keycount && keys != nullptr; k++)
246 : {
247 36 : const char *key = keys[k];
248 36 : int sub_number = CSLPartialFindString(substs, key);
249 36 : if (sub_number != -1)
250 : { // It is a listed match
251 : // But is the match for the key position?
252 18 : char *found_key = nullptr;
253 : const char *found_value =
254 18 : CPLParseNameValue(substs[sub_number], &found_key);
255 18 : if (found_key != nullptr && EQUAL(found_key, key))
256 : { // Should exist in the request
257 18 : if (std::string::npos == ret.find(key))
258 0 : matches = false;
259 18 : if (matches)
260 : // Execute the substitution on the "ret" string
261 18 : URLSearchAndReplace(&ret, key, "%s", found_value);
262 : }
263 : else
264 : {
265 0 : matches = false;
266 : }
267 18 : CPLFree(found_key);
268 : }
269 : else
270 : { // Key not in the subst list, should not match
271 18 : if (std::string::npos != ret.find(key))
272 9 : matches = false;
273 : }
274 : } // Key loop
275 36 : if (matches)
276 : {
277 27 : return; // We got the string ready, all keys accounted for and
278 : // substs applied
279 : }
280 : }
281 0 : ret.clear();
282 : }
283 :
284 : WMSMiniDriver_TiledWMS::WMSMiniDriver_TiledWMS() = default;
285 :
286 : WMSMiniDriver_TiledWMS::~WMSMiniDriver_TiledWMS() = default;
287 :
288 : // Returns the scale of a WMS request as compared to the base resolution
289 162 : double WMSMiniDriver_TiledWMS::Scale(const char *request) const
290 : {
291 162 : int bbox = FindBbox(request);
292 162 : if (bbox < 0)
293 0 : return 0;
294 : double x, y, X, Y;
295 162 : CPLsscanf(request + bbox, "%lf,%lf,%lf,%lf", &x, &y, &X, &Y);
296 162 : return (m_data_window.m_x1 - m_data_window.m_x0) / (X - x) * m_bsx /
297 162 : m_data_window.m_sx;
298 : }
299 :
300 : // Finds, extracts, and returns the highest resolution request string from a
301 : // list, starting at item i
302 27 : CPLString WMSMiniDriver_TiledWMS::GetLowestScale(CPLStringList &list,
303 : int i) const
304 : {
305 27 : CPLString req;
306 27 : double scale = -1;
307 27 : int position = -1;
308 162 : while (nullptr != list[i])
309 : {
310 135 : double tscale = Scale(list[i]);
311 135 : if (tscale >= scale)
312 : {
313 27 : scale = tscale;
314 27 : position = i;
315 : }
316 135 : i++;
317 : }
318 27 : if (position > -1)
319 : {
320 27 : req = list[position];
321 : list.Assign(CSLRemoveStrings(list.StealList(), position, 1, nullptr),
322 27 : true);
323 : }
324 27 : return req;
325 : }
326 :
327 : /*
328 : *\Brief Initialize minidriver with info from the server
329 : */
330 :
331 4 : CPLErr WMSMiniDriver_TiledWMS::Initialize(CPLXMLNode *config,
332 : CPL_UNUSED char **OpenOptions)
333 : {
334 4 : CPLErr ret = CE_None;
335 8 : CPLXMLTreeCloser tileServiceConfig(nullptr);
336 4 : const CPLXMLNode *TG = nullptr;
337 :
338 8 : CPLStringList requests;
339 8 : CPLStringList substs;
340 8 : CPLStringList keys;
341 4 : CPLStringList changes;
342 :
343 : try
344 : { // Parse info from the WMS Service node
345 : // m_end_url = CPLGetXMLValue(config, "AdditionalArgs", "");
346 4 : m_base_url = CPLGetXMLValue(config, "ServerURL", "");
347 :
348 4 : if (m_base_url.empty())
349 0 : throw CPLOPrintf("%s ServerURL missing.", SIG);
350 :
351 : CPLString tiledGroupName(
352 8 : CSLFetchNameValueDef(OpenOptions, "TiledGroupName", ""));
353 : tiledGroupName =
354 4 : CPLGetXMLValue(config, "TiledGroupName", tiledGroupName);
355 4 : if (tiledGroupName.empty())
356 1 : throw CPLOPrintf("%s TiledGroupName missing.", SIG);
357 :
358 : // Change strings, key is an attribute, value is the value of the Change
359 : // node Multiple keys are possible
360 :
361 : // First process the changes from open options, if present
362 3 : changes = CSLFetchNameValueMultiple(OpenOptions, "Change");
363 : // Transfer them to subst list
364 5 : for (int i = 0; changes && changes[i] != nullptr; i++)
365 : {
366 2 : char *key = nullptr;
367 2 : const char *value = CPLParseNameValue(changes[i], &key);
368 : // Add the ${} around the key
369 2 : if (value != nullptr && key != nullptr)
370 2 : substs.SetNameValue(CPLOPrintf("${%s}", key), value);
371 2 : CPLFree(key);
372 : }
373 :
374 : // Then process the configuration file itself
375 3 : const CPLXMLNode *nodeChange = CPLSearchXMLNode(config, "Change");
376 3 : while (nodeChange != nullptr)
377 : {
378 0 : CPLString key = CPLGetXMLValue(nodeChange, "key", "");
379 0 : if (key.empty())
380 : throw CPLOPrintf(
381 : "%s Change element needs a non-empty \"key\" attribute",
382 0 : SIG);
383 0 : substs.SetNameValue(key, CPLGetXMLValue(nodeChange, "", ""));
384 0 : nodeChange = SearchXMLSiblings(nodeChange, "Change");
385 : }
386 :
387 3 : m_parent_dataset->SetMetadataItem("ServerURL", m_base_url, nullptr);
388 3 : m_parent_dataset->SetMetadataItem("TiledGroupName", tiledGroupName,
389 3 : nullptr);
390 5 : for (int i = 0, n = CSLCount(substs); i < n && substs; i++)
391 2 : m_parent_dataset->SetMetadataItem("Change", substs[i], nullptr);
392 :
393 : const char *pszConfiguration =
394 3 : CPLGetXMLValue(config, "Configuration", nullptr);
395 6 : CPLString decodedGTS;
396 :
397 3 : if (pszConfiguration)
398 : { // Probably XML encoded because it is XML itself
399 : // The copy will be replaced by the decoded result
400 1 : decodedGTS = pszConfiguration;
401 1 : WMSUtilDecode(decodedGTS,
402 : CPLGetXMLValue(config, "Configuration.encoding", ""));
403 : }
404 : else
405 : { // Not local, use the WMSdriver to fetch the server config
406 4 : CPLString getTileServiceUrl = m_base_url + "request=GetTileService";
407 :
408 : // This returns a string managed by the cfg cache, do not free
409 2 : const char *pszTmp = GDALWMSDataset::GetServerConfig(
410 : getTileServiceUrl,
411 2 : const_cast<char **>(m_parent_dataset->GetHTTPRequestOpts()));
412 2 : decodedGTS = pszTmp ? pszTmp : "";
413 :
414 2 : if (decodedGTS.empty())
415 0 : throw CPLOPrintf("%s Can't fetch server GetTileService", SIG);
416 : }
417 :
418 : // decodedGTS contains the GetTileService return now
419 3 : tileServiceConfig.reset(CPLParseXMLString(decodedGTS));
420 3 : if (!tileServiceConfig)
421 : throw CPLOPrintf("%s Error parsing the GetTileService response",
422 0 : SIG);
423 :
424 3 : if (nullptr ==
425 3 : (TG = CPLSearchXMLNode(tileServiceConfig.get(), "TiledPatterns")))
426 : throw CPLOPrintf(
427 0 : "%s Can't locate TiledPatterns in server response.", SIG);
428 :
429 : // Get the global base_url and bounding box, these can be overwritten at
430 : // the tileGroup level They are just pointers into existing structures,
431 : // cleanup is not required
432 : const char *global_base_url =
433 3 : CPLGetXMLValue(tileServiceConfig.get(),
434 : "TiledPatterns.OnlineResource.xlink:href", "");
435 3 : const CPLXMLNode *global_latlonbbox = CPLGetXMLNode(
436 : tileServiceConfig.get(), "TiledPatterns.LatLonBoundingBox");
437 : const CPLXMLNode *global_bbox =
438 3 : CPLGetXMLNode(tileServiceConfig.get(), "TiledPatterns.BoundingBox");
439 3 : const char *pszProjection = CPLGetXMLValue(
440 3 : tileServiceConfig.get(), "TiledPatterns.Projection", "");
441 3 : if (pszProjection[0] != 0)
442 0 : m_oSRS.SetFromUserInput(
443 : pszProjection,
444 : OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get());
445 :
446 3 : if (nullptr == (TG = SearchLeafGroupName(TG->psChild, tiledGroupName)))
447 : throw CPLOPrintf("%s No TiledGroup "
448 : "%s"
449 : " in server response.",
450 0 : SIG, tiledGroupName.c_str());
451 :
452 3 : int band_count = atoi(CPLGetXMLValue(TG, "Bands", "3"));
453 :
454 3 : if (!GDALCheckBandCount(band_count, FALSE))
455 : throw CPLOPrintf("%s Invalid number of bands in server response",
456 0 : SIG);
457 :
458 3 : if (nullptr != CPLGetXMLNode(TG, "Key"))
459 : { // Collect all keys defined by this tileset
460 3 : const CPLXMLNode *node = CPLGetXMLNode(TG, "Key");
461 6 : while (nullptr != node)
462 : { // the TEXT of the Key node
463 3 : const char *val = CPLGetXMLValue(node, nullptr, nullptr);
464 3 : if (nullptr != val)
465 3 : keys.AddString(val);
466 3 : node = SearchXMLSiblings(node, "Key");
467 : }
468 : }
469 :
470 : // Data values are attributes, they include NoData Min and Max
471 3 : if (nullptr != CPLGetXMLNode(TG, "DataValues"))
472 : {
473 : const char *nodata =
474 0 : CPLGetXMLValue(TG, "DataValues.NoData", nullptr);
475 0 : if (nodata != nullptr)
476 : {
477 0 : m_parent_dataset->WMSSetNoDataValue(nodata);
478 0 : m_parent_dataset->SetTileOO("@NDV", nodata);
479 : }
480 0 : const char *min = CPLGetXMLValue(TG, "DataValues.min", nullptr);
481 0 : if (min != nullptr)
482 0 : m_parent_dataset->WMSSetMinValue(min);
483 0 : const char *max = CPLGetXMLValue(TG, "DataValues.max", nullptr);
484 0 : if (max != nullptr)
485 0 : m_parent_dataset->WMSSetMaxValue(max);
486 : }
487 :
488 3 : m_parent_dataset->WMSSetBandsCount(band_count);
489 : GDALDataType dt =
490 3 : GDALGetDataTypeByName(CPLGetXMLValue(TG, "DataType", "Byte"));
491 3 : m_parent_dataset->WMSSetDataType(dt);
492 3 : if (dt != GDT_Byte)
493 0 : m_parent_dataset->SetTileOO("@DATATYPE", GDALGetDataTypeName(dt));
494 : // Let the TiledGroup override the projection
495 3 : pszProjection = CPLGetXMLValue(TG, "Projection", "");
496 3 : if (pszProjection[0] != 0)
497 3 : m_oSRS = ProjToSRS(pszProjection);
498 :
499 : m_base_url =
500 3 : CPLGetXMLValue(TG, "OnlineResource.xlink:href", global_base_url);
501 3 : if (m_base_url[0] == '\0')
502 : throw CPLOPrintf(
503 0 : "%s Can't locate OnlineResource in the server response", SIG);
504 :
505 : // Bounding box, local, global, local lat-lon, global lat-lon, in this
506 : // order
507 3 : const CPLXMLNode *bbox = CPLGetXMLNode(TG, "BoundingBox");
508 3 : if (nullptr == bbox)
509 3 : bbox = global_bbox;
510 3 : if (nullptr == bbox)
511 3 : bbox = CPLGetXMLNode(TG, "LatLonBoundingBox");
512 3 : if (nullptr == bbox)
513 0 : bbox = global_latlonbbox;
514 3 : if (nullptr == bbox)
515 : throw CPLOPrintf(
516 : "%s Can't locate the LatLonBoundingBox in server response",
517 0 : SIG);
518 :
519 : // Check for errors during conversion
520 3 : errno = 0;
521 3 : int err = 0;
522 3 : m_data_window.m_x0 = getXMLNum(bbox, "minx", "0");
523 3 : err |= errno;
524 3 : m_data_window.m_x1 = getXMLNum(bbox, "maxx", "-1");
525 3 : err |= errno;
526 3 : m_data_window.m_y0 = getXMLNum(bbox, "maxy", "0");
527 3 : err |= errno;
528 3 : m_data_window.m_y1 = getXMLNum(bbox, "miny", "-1");
529 3 : err |= errno;
530 3 : if (err)
531 0 : throw CPLOPrintf("%s Can't parse LatLonBoundingBox", SIG);
532 :
533 3 : if ((m_data_window.m_x1 - m_data_window.m_x0) <= 0 ||
534 3 : (m_data_window.m_y0 - m_data_window.m_y1) <= 0)
535 : throw CPLOPrintf(
536 0 : "%s Coordinate order in BBox problem in server response", SIG);
537 :
538 : // Is there a palette?
539 : //
540 : // Format is
541 : // <Palette>
542 : // <Size>N</Size> : Optional
543 : // <Model>RGBA|RGB</Model> : Optional, defaults to RGB
544 : // <Entry idx=i c1=v1 c2=v2 c3=v3 c4=v4/> :Optional
545 : // <Entry .../>
546 : // </Palette>
547 : // the idx attribute is optional, it autoincrements
548 : // The entries are vertices, interpolation takes place in between if the
549 : // indices are not successive index values have to be in increasing
550 : // order The palette starts initialized with zeros
551 : //
552 :
553 3 : bool bHasColorTable = false;
554 :
555 3 : if ((band_count == 1) && CPLGetXMLNode(TG, "Palette"))
556 : {
557 0 : const CPLXMLNode *node = CPLGetXMLNode(TG, "Palette");
558 :
559 0 : int entries = static_cast<int>(getXMLNum(node, "Size", "255"));
560 0 : GDALPaletteInterp eInterp = GPI_RGB; // RGB and RGBA are the same
561 :
562 0 : CPLString pModel = CPLGetXMLValue(node, "Model", "RGB");
563 0 : if (!pModel.empty() && pModel.find("RGB") == std::string::npos)
564 : throw CPLOPrintf(
565 : "%s Palette Model %s is unknown, use RGB or RGBA", SIG,
566 0 : pModel.c_str());
567 :
568 0 : if ((entries < 1) || (entries > 256))
569 0 : throw CPLOPrintf("%s Palette definition error", SIG);
570 :
571 : // Create it and initialize it to nothing
572 : int start_idx;
573 : int end_idx;
574 0 : GDALColorEntry ce_start = {0, 0, 0, 255};
575 0 : GDALColorEntry ce_end = {0, 0, 0, 255};
576 :
577 0 : auto poColorTable = std::make_unique<GDALColorTable>(eInterp);
578 0 : poColorTable->CreateColorRamp(0, &ce_start, entries - 1, &ce_end);
579 : // Read the values
580 0 : const CPLXMLNode *p = CPLGetXMLNode(node, "Entry");
581 0 : if (p)
582 : {
583 : // Initialize the first entry
584 0 : start_idx = static_cast<int>(getXMLNum(p, "idx", "0"));
585 0 : ce_start = GetXMLColorEntry(p);
586 :
587 0 : if (start_idx < 0)
588 : throw CPLOPrintf("%s Palette index %d not allowed", SIG,
589 0 : start_idx);
590 :
591 0 : poColorTable->SetColorEntry(start_idx, &ce_start);
592 0 : while (nullptr != (p = SearchXMLSiblings(p, "Entry")))
593 : {
594 : // For every entry, create a ramp
595 0 : ce_end = GetXMLColorEntry(p);
596 0 : end_idx = static_cast<int>(
597 0 : getXMLNum(p, "idx", CPLOPrintf("%d", start_idx + 1)));
598 0 : if ((end_idx <= start_idx) || (start_idx >= entries))
599 : throw CPLOPrintf("%s Index Error at index %d", SIG,
600 0 : end_idx);
601 :
602 0 : poColorTable->CreateColorRamp(start_idx, &ce_start, end_idx,
603 : &ce_end);
604 0 : ce_start = ce_end;
605 0 : start_idx = end_idx;
606 : }
607 : }
608 :
609 : // Dataset has ownership
610 0 : m_parent_dataset->SetColorTable(poColorTable.release());
611 0 : bHasColorTable = true;
612 : } // If palette
613 :
614 3 : int overview_count = 0;
615 3 : const CPLXMLNode *Pattern = TG->psChild;
616 :
617 3 : m_bsx = -1;
618 3 : m_bsy = -1;
619 3 : m_data_window.m_sx = 0;
620 3 : m_data_window.m_sy = 0;
621 :
622 27 : while (
623 57 : (nullptr != Pattern) &&
624 27 : (nullptr != (Pattern = SearchXMLSiblings(Pattern, "=TilePattern"))))
625 : {
626 : int mbsx, mbsy, sx, sy;
627 : double x, y, X, Y;
628 :
629 27 : CPLString request;
630 27 : FindChangePattern(Pattern->psChild->pszValue, substs, keys,
631 27 : request);
632 27 : if (request.empty())
633 0 : break; // No point to drag, this level doesn't match the keys
634 :
635 27 : const CPLStringList aosTokens(CSLTokenizeString2(request, "&", 0));
636 :
637 27 : const char *pszWIDTH = aosTokens.FetchNameValue("WIDTH");
638 27 : const char *pszHEIGHT = aosTokens.FetchNameValue("HEIGHT");
639 27 : if (pszWIDTH == nullptr || pszHEIGHT == nullptr)
640 : throw CPLOPrintf(
641 : "%s Cannot find width or height parameters in %s", SIG,
642 0 : request.c_str());
643 :
644 27 : mbsx = atoi(pszWIDTH);
645 27 : mbsy = atoi(pszHEIGHT);
646 : // If unset until now, try to get the projection from the
647 : // pattern
648 27 : if (m_oSRS.IsEmpty())
649 : {
650 0 : const char *pszSRS = aosTokens.FetchNameValueDef("SRS", "");
651 0 : if (pszSRS[0] != 0)
652 0 : m_oSRS = ProjToSRS(pszSRS);
653 : }
654 :
655 27 : if (-1 == m_bsx)
656 3 : m_bsx = mbsx;
657 27 : if (-1 == m_bsy)
658 3 : m_bsy = mbsy;
659 27 : if ((m_bsx != mbsx) || (m_bsy != mbsy))
660 0 : throw CPLOPrintf("%s Tileset uses different block sizes", SIG);
661 :
662 27 : if (CPLsscanf(aosTokens.FetchNameValueDef("BBOX", ""),
663 27 : "%lf,%lf,%lf,%lf", &x, &y, &X, &Y) != 4)
664 : throw CPLOPrintf("%s Error parsing BBOX, pattern %d\n", SIG,
665 0 : overview_count + 1);
666 :
667 : // Pick the largest size
668 27 : sx = static_cast<int>((m_data_window.m_x1 - m_data_window.m_x0) /
669 27 : (X - x) * m_bsx);
670 27 : sy = static_cast<int>(fabs(
671 27 : (m_data_window.m_y1 - m_data_window.m_y0) / (Y - y) * m_bsy));
672 27 : if (sx > m_data_window.m_sx)
673 3 : m_data_window.m_sx = sx;
674 27 : if (sy > m_data_window.m_sy)
675 3 : m_data_window.m_sy = sy;
676 :
677 : // Only use overlays where the top coordinate is within a pixel from
678 : // the top of coverage
679 : double pix_off, temp;
680 27 : pix_off =
681 27 : m_bsy * modf(fabs((Y - m_data_window.m_y0) / (Y - y)), &temp);
682 27 : if ((pix_off < 1) || ((m_bsy - pix_off) < 1))
683 : {
684 27 : requests.AddString(request);
685 27 : overview_count++;
686 : }
687 : else
688 : { // Just a warning
689 0 : CPLError(CE_Warning, CPLE_AppDefined,
690 : "%s Overlay size %dX%d can't be used due to alignment",
691 : SIG, sx, sy);
692 : }
693 :
694 27 : Pattern = Pattern->psNext;
695 : } // Search for matching TilePattern
696 :
697 : // Did we find anything
698 3 : if (requests.empty())
699 : throw CPLOPrintf("Can't find any usable TilePattern, maybe the "
700 0 : "Changes are not correct?");
701 :
702 : // The tlevel is needed, the tx and ty are not used by this minidriver
703 3 : m_data_window.m_tlevel = 0;
704 3 : m_data_window.m_tx = 0;
705 3 : m_data_window.m_ty = 0;
706 :
707 : // Make sure the parent_dataset values are set before creating the bands
708 3 : m_parent_dataset->WMSSetBlockSize(m_bsx, m_bsy);
709 3 : m_parent_dataset->WMSSetRasterSize(m_data_window.m_sx,
710 : m_data_window.m_sy);
711 :
712 3 : m_parent_dataset->WMSSetDataWindow(m_data_window);
713 : // m_parent_dataset->WMSSetOverviewCount(overview_count);
714 3 : m_parent_dataset->WMSSetClamp(false);
715 :
716 : // Ready for the Rasterband creation
717 30 : for (int i = 0; i < overview_count; i++)
718 : {
719 54 : CPLString request = GetLowestScale(requests, i);
720 27 : double scale = Scale(request);
721 :
722 : // Base scale should be very close to 1
723 27 : if ((0 == i) && (fabs(scale - 1) > 1e-6))
724 0 : throw CPLOPrintf("%s Base resolution pattern missing", SIG);
725 :
726 : // Prepare the request and insert it back into the list
727 : // Find returns an answer relative to the original string start!
728 27 : size_t startBbox = FindBbox(request);
729 27 : size_t endBbox = request.find('&', startBbox);
730 27 : if (endBbox == std::string::npos)
731 27 : endBbox = request.size();
732 27 : request.replace(startBbox, endBbox - startBbox, "${GDAL_BBOX}");
733 27 : requests.InsertString(i, request);
734 :
735 : // Create the Rasterband or overview
736 108 : for (int j = 1; j <= band_count; j++)
737 : {
738 81 : if (i != 0)
739 : {
740 72 : m_parent_dataset->mGetBand(j)->AddOverview(scale);
741 : }
742 : else
743 : { // Base resolution
744 : GDALWMSRasterBand *band =
745 9 : new GDALWMSRasterBand(m_parent_dataset, j, 1);
746 9 : if (bHasColorTable)
747 0 : band->SetColorInterpretation(GCI_PaletteIndex);
748 : else
749 9 : band->SetColorInterpretation(BandInterp(band_count, j));
750 9 : m_parent_dataset->mSetBand(j, band);
751 : }
752 : }
753 : }
754 :
755 3 : if ((overview_count == 0) || (m_bsx < 1) || (m_bsy < 1))
756 0 : throw CPLOPrintf("%s No usable TilePattern elements found", SIG);
757 :
758 : // Do we need to modify the output XML
759 3 : if (0 != CSLCount(OpenOptions))
760 : {
761 : // Get the proposed XML, it will exist at this point
762 : CPLXMLTreeCloser cfg_root(CPLParseXMLString(
763 4 : m_parent_dataset->GetMetadataItem("XML", "WMS")));
764 2 : char *pszXML = nullptr;
765 :
766 2 : if (cfg_root)
767 : {
768 2 : bool modified = false;
769 :
770 : // Set openoption StoreConfiguration to Yes to save the server
771 : // GTS in the output XML
772 2 : if (CSLFetchBoolean(OpenOptions, "StoreConfiguration", 0) &&
773 : nullptr ==
774 0 : CPLGetXMLNode(cfg_root.get(), "Service.Configuration"))
775 : {
776 0 : char *xmlencodedGTS = CPLEscapeString(
777 0 : decodedGTS, static_cast<int>(decodedGTS.size()),
778 : CPLES_XML);
779 :
780 : // It doesn't have a Service.Configuration element, safe to
781 : // add one
782 0 : CPLXMLNode *scfg = CPLCreateXMLElementAndValue(
783 : CPLGetXMLNode(cfg_root.get(), "Service"),
784 : "Configuration", xmlencodedGTS);
785 0 : CPLAddXMLAttributeAndValue(scfg, "encoding", "XMLencoded");
786 0 : modified = true;
787 0 : CPLFree(xmlencodedGTS);
788 : }
789 :
790 : // Set the TiledGroupName if it's not already there and we have
791 : // it as an open option
792 3 : if (!CPLGetXMLNode(cfg_root.get(), "Service.TiledGroupName") &&
793 1 : nullptr != CSLFetchNameValue(OpenOptions, "TiledGroupName"))
794 : {
795 1 : CPLCreateXMLElementAndValue(
796 : CPLGetXMLNode(cfg_root.get(), "Service"),
797 : "TiledGroupName",
798 : CSLFetchNameValue(OpenOptions, "TiledGroupName"));
799 1 : modified = true;
800 : }
801 :
802 2 : if (!substs.empty())
803 : {
804 : // Get all the existing Change elements
805 4 : std::set<std::string> oExistingKeys;
806 : auto nodechange =
807 2 : CPLGetXMLNode(cfg_root.get(), "Service.Change");
808 2 : while (nodechange)
809 : {
810 : const char *key =
811 0 : CPLGetXMLValue(nodechange, "Key", nullptr);
812 0 : if (key)
813 0 : oExistingKeys.insert(key);
814 0 : nodechange = nodechange->psNext;
815 : }
816 :
817 4 : for (int i = 0, n = substs.size(); i < n && substs; i++)
818 : {
819 2 : CPLString kv(substs[i]);
820 : auto sep_pos =
821 2 : kv.find_first_of("=:"); // It should find it
822 2 : if (sep_pos == CPLString::npos)
823 0 : continue;
824 4 : CPLString key(kv.substr(0, sep_pos));
825 4 : CPLString val(kv.substr(sep_pos + 1));
826 : // Add to the cfg_root if this change is not already
827 : // there
828 2 : if (oExistingKeys.find(key) == oExistingKeys.end())
829 : {
830 2 : auto cnode = CPLCreateXMLElementAndValue(
831 : CPLGetXMLNode(cfg_root.get(), "Service"),
832 : "Change", val);
833 2 : CPLAddXMLAttributeAndValue(cnode, "Key", key);
834 2 : modified = true;
835 : }
836 : }
837 : }
838 :
839 2 : if (modified)
840 : {
841 2 : pszXML = CPLSerializeXMLTree(cfg_root.get());
842 2 : m_parent_dataset->SetXML(pszXML);
843 : }
844 : }
845 :
846 2 : CPLFree(pszXML);
847 : }
848 : }
849 2 : catch (const CPLString &msg)
850 : {
851 1 : ret = CE_Failure;
852 1 : CPLError(ret, CPLE_AppDefined, "%s", msg.c_str());
853 : }
854 :
855 4 : m_requests = std::move(requests);
856 8 : return ret;
857 : }
858 :
859 0 : CPLErr WMSMiniDriver_TiledWMS::TiledImageRequest(
860 : WMSHTTPRequest &request, const GDALWMSImageRequestInfo &iri,
861 : const GDALWMSTiledImageRequestInfo &tiri)
862 : {
863 0 : CPLString &url = request.URL;
864 0 : url = m_base_url;
865 0 : URLPrepare(url);
866 0 : url += CSLGetField(m_requests.List(), -tiri.m_level);
867 0 : URLSearchAndReplace(&url, "${GDAL_BBOX}", "%013.8f,%013.8f,%013.8f,%013.8f",
868 0 : iri.m_x0, iri.m_y1, iri.m_x1, iri.m_y0);
869 0 : return CE_None;
870 : }
|