File: pc_schema.c

package info (click to toggle)
pgpointcloud 1.2.5-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,892 kB
  • sloc: sql: 40,767; ansic: 11,045; xml: 935; makefile: 297; cpp: 282; perl: 248; python: 178; sh: 92
file content (666 lines) | stat: -rw-r--r-- 17,021 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
/***********************************************************************
 * pc_schema.c
 *
 *  Pointclound schema handling. Parse and emit the XML format for
 *  representing packed multidimensional point data.
 *
 *  PgSQL Pointcloud is free and open source software provided
 *  by the Government of Canada
 *  Copyright (c) 2013 Natural Resources Canada
 *
 ***********************************************************************/

#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>

#include "pc_api_internal.h"
#include "stringbuffer.h"

static char *INTERPRETATION_STRINGS[NUM_INTERPRETATIONS] = {
    "unknown",  "int8_t",  "uint8_t",  "int16_t", "uint16_t", "int32_t",
    "uint32_t", "int64_t", "uint64_t", "double",  "float"};

static size_t INTERPRETATION_SIZES[NUM_INTERPRETATIONS] = {
    -1,    /* PC_UNKNOWN */
    1,  1, /* PC_INT8, PC_UINT8, */
    2,  2, /* PC_INT16, PC_UINT16 */
    4,  4, /* PC_INT32, PC_UINT32 */
    8,  8, /* PC_INT64, PC_UINT64 */
    8,  4  /* PC_DOUBLE, PC_FLOAT */
};

/** Convert XML string token to type interpretation number */
const char *pc_interpretation_string(uint32_t interp)
{
  if (interp < NUM_INTERPRETATIONS)
    return INTERPRETATION_STRINGS[interp];
  else
    return "unknown";
}

/** Convert XML string token to type interpretation number */
static int pc_interpretation_number(const char *str)
{
  if (str[0] == 'i' || str[0] == 'I')
  {
    if (str[3] == '8')
      return PC_INT8;
    if (str[3] == '1')
      return PC_INT16;
    if (str[3] == '3')
      return PC_INT32;
    if (str[3] == '6')
      return PC_INT64;
  }
  else if (str[0] == 'u' || str[0] == 'U')
  {
    if (str[4] == '8')
      return PC_UINT8;
    if (str[4] == '1')
      return PC_UINT16;
    if (str[4] == '3')
      return PC_UINT32;
    if (str[4] == '6')
      return PC_UINT64;
  }
  else if (str[0] == 'd' || str[0] == 'D')
  {
    return PC_DOUBLE;
  }
  else if (str[0] == 'f' || str[0] == 'F')
  {
    return PC_FLOAT;
  }
  else
    return PC_UNKNOWN;

  return PC_UNKNOWN;
}

const char *pc_compression_name(int num)
{
  switch (num)
  {
  case PC_NONE:
    return "none";
  case PC_DIMENSIONAL:
    return "dimensional";
  case PC_LAZPERF:
    return "laz";
  default:
    return "UNKNOWN";
  }
}

static int pc_compression_number(const char *str)
{
  if (!str)
    return PC_NONE;

  if ((str[0] == 'd' || str[0] == 'D') && (strcasecmp(str, "dimensional") == 0))
  {
    return PC_DIMENSIONAL;
  }

  if ((str[0] == 'l' || str[0] == 'L') && (strcasecmp(str, "laz") == 0))
  {
    return PC_LAZPERF;
  }

  if ((str[0] == 'n' || str[0] == 'N') && (strcasecmp(str, "none") == 0))
  {
    return PC_NONE;
  }

  return PC_NONE;
}

/** Convert type interpretation number size in bytes */
size_t pc_interpretation_size(uint32_t interp)
{
  if (interp < NUM_INTERPRETATIONS)
  {
    return INTERPRETATION_SIZES[interp];
  }
  else
  {
    pcerror("pc_interpretation_size: invalid interpretation");
    return 0;
  }
}

/** Allocate clean memory for a PCDIMENSION struct */
static PCDIMENSION *pc_dimension_new()
{
  PCDIMENSION *pcd = pcalloc(sizeof(PCDIMENSION));
  /* Default scaling value is 1! */
  pcd->scale = 1.0;
  return pcd;
}

static PCDIMENSION *pc_dimension_clone(const PCDIMENSION *dim)
{
  PCDIMENSION *pcd = pc_dimension_new();
  /* Copy all the inline data */
  memcpy(pcd, dim, sizeof(PCDIMENSION));
  /* Copy the referenced data */
  if (dim->name)
    pcd->name = pcstrdup(dim->name);
  if (dim->description)
    pcd->description = pcstrdup(dim->description);
  return pcd;
}

/** Release the memory behind the PCDIMENSION struct */
static void pc_dimension_free(PCDIMENSION *pcd)
{
  /* Assumption: No memory in the dimension is owned somewhere else */
  if (pcd->description)
    pcfree(pcd->description);
  if (pcd->name)
    pcfree(pcd->name);
  pcfree(pcd);
}

static PCSCHEMA *pc_schema_new(uint32_t ndims)
{
  PCSCHEMA *pcs = pcalloc(sizeof(PCSCHEMA));
  pcs->dims = pcalloc(sizeof(PCDIMENSION *) * ndims);
  pcs->namehash = create_string_hashtable();
  pcs->ndims = ndims;
  /* pcalloc memsets to 0, so xdim,ydim,zdim and mdim are already NULL */
  return pcs;
}

/** Complete the byte offsets of dimensions from the ordered sizes */
static void pc_schema_calculate_byteoffsets(PCSCHEMA *pcs)
{
  int i;
  size_t byteoffset = 0;
  for (i = 0; i < pcs->ndims; i++)
  {
    if (pcs->dims[i])
    {
      pcs->dims[i]->byteoffset = byteoffset;
      pcs->dims[i]->size = pc_interpretation_size(pcs->dims[i]->interpretation);
      byteoffset += pcs->dims[i]->size;
    }
  }
  pcs->size = byteoffset;
}

void pc_schema_set_dimension(PCSCHEMA *s, PCDIMENSION *d)
{
  s->dims[d->position] = d;
  if (d->name)
    hashtable_insert(s->namehash, d->name, d);
  pc_schema_calculate_byteoffsets(s);
}

PCSCHEMA *pc_schema_clone(const PCSCHEMA *s)
{
  int i;
  PCSCHEMA *pcs = pc_schema_new(s->ndims);
  pcs->pcid = s->pcid;
  pcs->srid = s->srid;
  pcs->compression = s->compression;
  for (i = 0; i < pcs->ndims; i++)
  {
    if (s->dims[i])
    {
      pc_schema_set_dimension(pcs, pc_dimension_clone(s->dims[i]));
    }
  }
  pcs->xdim = s->xdim ? pcs->dims[s->xdim->position] : NULL;
  pcs->ydim = s->ydim ? pcs->dims[s->ydim->position] : NULL;
  pcs->zdim = s->zdim ? pcs->dims[s->zdim->position] : NULL;
  pcs->mdim = s->mdim ? pcs->dims[s->mdim->position] : NULL;
  pc_schema_calculate_byteoffsets(pcs);
  return pcs;
}

/** Release the memory behind the PCSCHEMA struct */
void pc_schema_free(PCSCHEMA *pcs)
{
  int i;

  for (i = 0; i < pcs->ndims; i++)
  {
    if (pcs->dims[i])
    {
      pc_dimension_free(pcs->dims[i]);
      pcs->dims[i] = 0;
    }
  }
  pcfree(pcs->dims);

  if (pcs->namehash)
    hashtable_destroy(pcs->namehash, 0);

  pcfree(pcs);
}

/** Convert a PCSCHEMA to a human-readable JSON string */
char *pc_schema_to_json(const PCSCHEMA *pcs)
{
  int i;
  char *str;
  stringbuffer_t *sb = stringbuffer_create();
  stringbuffer_append(sb, "{");

  if (pcs->pcid)
    stringbuffer_aprintf(sb, "\"pcid\" : %d,\n", pcs->pcid);
  if (pcs->srid)
    stringbuffer_aprintf(sb, "\"srid\" : %d,\n", pcs->srid);
  if (pcs->compression)
    stringbuffer_aprintf(sb, "\"compression\" : %d,\n", pcs->compression);

  if (pcs->ndims)
  {

    stringbuffer_append(sb, "\"dims\" : [\n");

    for (i = 0; i < pcs->ndims; i++)
    {
      if (pcs->dims[i])
      {
        PCDIMENSION *d = pcs->dims[i];

        if (i)
          stringbuffer_append(sb, ",");
        stringbuffer_append(sb, "\n { \n");

        if (d->name)
          stringbuffer_aprintf(sb, "  \"name\" : \"%s\",\n", d->name);
        if (d->description)
          stringbuffer_aprintf(sb, "  \"description\" : \"%s\",\n",
                               d->description);

        stringbuffer_aprintf(sb, "  \"size\" : %d,\n", d->size);
        stringbuffer_aprintf(sb, "  \"byteoffset\" : %d,\n", d->byteoffset);
        stringbuffer_aprintf(sb, "  \"scale\" : %g,\n", d->scale);
        stringbuffer_aprintf(sb, "  \"interpretation\" : \"%s\",\n",
                             pc_interpretation_string(d->interpretation));
        stringbuffer_aprintf(sb, "  \"offset\" : %g,\n", d->offset);

        stringbuffer_aprintf(sb, "  \"active\" : %d\n", d->active);
        stringbuffer_append(sb, " }");
      }
    }
    stringbuffer_append(sb, "\n]\n");
  }
  stringbuffer_append(sb, "}\n");
  str = stringbuffer_getstringcopy(sb);
  stringbuffer_destroy(sb);
  return str;
}

void pc_schema_check_xyzm(PCSCHEMA *s)
{
  int i;
  for (i = 0; i < s->ndims; i++)
  {
    char *dimname = s->dims[i]->name;
    if (!dimname)
      continue;
    if (strcasecmp(dimname, "X") == 0 ||
        strcasecmp(dimname, "Longitude") == 0 ||
        strcasecmp(dimname, "Lon") == 0)
    {
      s->xdim = s->dims[i];
      continue;
    }
    if (strcasecmp(dimname, "Y") == 0 || strcasecmp(dimname, "Latitude") == 0 ||
        strcasecmp(dimname, "Lat") == 0)
    {
      s->ydim = s->dims[i];
      continue;
    }
    if (strcasecmp(dimname, "Z") == 0 || strcasecmp(dimname, "H") == 0 ||
        strcasecmp(dimname, "Height") == 0)
    {
      s->zdim = s->dims[i];
      continue;
    }
    if (strcasecmp(dimname, "M") == 0 || strcasecmp(dimname, "T") == 0 ||
        strcasecmp(dimname, "Time") == 0 || strcasecmp(dimname, "GPSTime") == 0)
    {
      s->mdim = s->dims[i];
      continue;
    }
  }
}

static char *xml_node_get_content(xmlNodePtr node)
{
  xmlNodePtr cur = node->children;
  if (cur)
  {
    do
    {
      if (cur->type == XML_TEXT_NODE)
      {
        return (char *)(cur->content);
      }
    } while ((cur = cur->next));
  }
  return "";
}

/** Population a PCSCHEMA struct from the XML representation */
PCSCHEMA *pc_schema_from_xml(const char *xml_str)
{
  xmlDocPtr xml_doc = NULL;
  xmlNodePtr xml_root = NULL;
  xmlNsPtr xml_ns = NULL;
  xmlXPathContextPtr xpath_ctx = NULL;
  xmlXPathObjectPtr xpath_obj = NULL;
  xmlNodeSetPtr nodes;
  PCSCHEMA *s = NULL;
  const char *xml_ptr = xml_str;

  /* Roll forward to start of XML string */
  while ((*xml_ptr != '\0') && (*xml_ptr != '<'))
  {
    xml_ptr++;
  }

  size_t xml_size = strlen(xml_ptr);
  static xmlChar *xpath_str = (xmlChar *)("/pc:PointCloudSchema/pc:dimension");
  static xmlChar *xpath_metadata_str =
      (xmlChar *)("/pc:PointCloudSchema/pc:metadata/Metadata");

  /* Parse XML doc */
  xmlInitParser();
  xml_doc = xmlReadMemory(xml_ptr, xml_size, NULL, NULL, 0);
  if (!xml_doc)
  {
    pcwarn("unable to parse schema XML");
    goto cleanup;
  }

  /* Capture the namespace */
  xml_root = xmlDocGetRootElement(xml_doc);
  if (xml_root->ns)
    xml_ns = xml_root->ns;

  /* Create xpath evaluation context */
  xpath_ctx = xmlXPathNewContext(xml_doc);
  if (!xpath_ctx)
  {
    pcwarn("unable to create new XPath context to read schema XML");
    goto cleanup;
  }

  /* Register the root namespace if there is one */
  if (xml_ns)
    xmlXPathRegisterNs(xpath_ctx, (xmlChar *)"pc", xml_ns->href);

  /* Evaluate xpath expression */
  xpath_obj = xmlXPathEvalExpression(xpath_str, xpath_ctx);
  if (!xpath_obj)
  {
    pcwarn("unable to evaluate xpath expression \"%s\" against schema XML",
           xpath_str);
    goto cleanup;
  }

  /* Iterate on the dimensions we found */
  if ((nodes = xpath_obj->nodesetval))
  {
    int ndims = nodes->nodeNr;
    int i;
    s = pc_schema_new(ndims);

    for (i = 0; i < ndims; i++)
    {
      /* This is a "dimension" */
      if (nodes->nodeTab[i]->type == XML_ELEMENT_NODE)
      {
        xmlNodePtr cur = nodes->nodeTab[i];
        xmlNodePtr child;
        PCDIMENSION *d = pc_dimension_new();

        /* These are the values of the dimension */
        for (child = cur->children; child; child = child->next)
        {
          if (child->type == XML_ELEMENT_NODE && child->children != NULL)
          {
            char *content = (char *)(child->children->content);
            char *name = (char *)(child->name);
            if (strcmp(name, "name") == 0)
              d->name = pcstrdup(content);
            else if (strcmp(name, "description") == 0)
              d->description = pcstrdup(content);
            else if (strcmp(name, "size") == 0)
              d->size = atoi(content);
            else if (strcmp(name, "active") == 0)
              d->active = atoi(content);
            else if (strcmp(name, "position") == 0)
              d->position = atoi(content) - 1;
            else if (strcmp(name, "interpretation") == 0)
              d->interpretation = pc_interpretation_number(content);
            else if (strcmp(name, "scale") == 0)
              d->scale = atof(content);
            else if (strcmp(name, "offset") == 0)
              d->offset = atof(content);
            else if (strcmp(name, "uuid") == 0)
            /* Ignore this tag for now */ {
            }
            else if (strcmp(name, "parent_uuid") == 0)
            /* Ignore this tag for now */ {
            }
            else
              pcinfo("unhandled schema type element \"%s\" "
                     "encountered",
                     name);
          }
        }

        /* Convert interprestation to size */
        d->size = pc_interpretation_size(d->interpretation);

        /* Store the dimension in the schema */
        if (d->position >= ndims)
        {
          pcwarn("schema dimension states position \"%d\", but "
                 "number of XML "
                 "dimensions is \"%d\"",
                 d->position + 1, ndims);
          pc_dimension_free(d);
          goto cleanup;
        }
        else if (s->dims[d->position])
        {
          pcwarn("schema dimension at position \"%d\" is declared twice",
                 d->position + 1, ndims);
          pc_dimension_free(d);
          goto cleanup;
        }
        pc_schema_set_dimension(s, d);
      }
    }

    /* Complete the byte offsets of dimensions from the ordered sizes */
    pc_schema_calculate_byteoffsets(s);
    /* Check XYZM positions */
    pc_schema_check_xyzm(s);
  }

  xmlXPathFreeObject(xpath_obj);

  /* SEARCH FOR METADATA ENTRIES */
  xpath_obj = xmlXPathEvalExpression(xpath_metadata_str, xpath_ctx);
  if (!xpath_obj)
  {
    pcwarn("unable to evaluate xpath expression \"%s\" against schema XML",
           xpath_metadata_str);
    goto cleanup;
  }

  /* Iterate on the <Metadata> we find */
  if ((nodes = xpath_obj->nodesetval))
  {
    int i;

    for (i = 0; i < nodes->nodeNr; i++)
    {
      char *metadata_name = "";
      char *metadata_value = "";
      /* Read the metadata name and value from the node */
      /* <Metadata name="somename">somevalue</Metadata> */
      xmlNodePtr cur = nodes->nodeTab[i];
      if (cur->type == XML_ELEMENT_NODE &&
          strcmp((char *)(cur->name), "Metadata") == 0)
      {
        metadata_name = (char *)xmlGetProp(cur, (xmlChar *)"name");
        metadata_value = xml_node_get_content(cur);
      }

      /* Store the compression type on the schema */
      if (strcmp(metadata_name, "compression") == 0)
      {
        int compression = pc_compression_number(metadata_value);
        if (compression >= 0)
        {
          s->compression = compression;
        }
      }
      xmlFree(metadata_name);
    }
  }

cleanup:
  if (s && !pc_schema_is_valid(s))
  {
    pc_schema_free(s);
    s = NULL;
  }

  if (xpath_obj)
    xmlXPathFreeObject(xpath_obj);
  if (xpath_ctx)
    xmlXPathFreeContext(xpath_ctx);
  if (xml_doc)
    xmlFreeDoc(xml_doc);
  xmlCleanupParser();

  return s;
}

uint32_t pc_schema_is_valid(const PCSCHEMA *s)
{
  int i;

  if (!s->xdim)
  {
    pcwarn("schema does not include an X coordinate");
    return PC_FALSE;
  }

  if (!s->ydim)
  {
    pcwarn("schema does not include a Y coordinate");
    return PC_FALSE;
  }

  if (!s->ndims)
  {
    pcwarn("schema has no dimensions");
    return PC_FALSE;
  }

  for (i = 0; i < s->ndims; i++)
  {
    if (!s->dims[i])
    {
      pcwarn("schema is missing a dimension at position %d", i);
      return PC_FALSE;
    }
  }

  return PC_TRUE;
}

PCDIMENSION *pc_schema_get_dimension(const PCSCHEMA *s, uint32_t dim)
{
  if (s && s->ndims > dim)
  {
    return s->dims[dim];
  }
  return NULL;
}

PCDIMENSION *pc_schema_get_dimension_by_name(const PCSCHEMA *s,
                                             const char *name)
{
  if (!(s && s->namehash))
    return NULL;

  return hashtable_search(s->namehash, name);
}

size_t pc_schema_get_size(const PCSCHEMA *s) { return s->size; }

/**
 * Return true if the schemas have the same dimensions with the same
 * interpretations and at the same locations. The scales and offsets
 * may be different though. Otherwise return false.
 */
uint32_t pc_schema_same_dimensions(const PCSCHEMA *s1, const PCSCHEMA *s2)
{
  size_t i;

  if (s1->ndims != s2->ndims)
    return PC_FALSE;

  for (i = 0; i < s1->ndims; i++)
  {
    PCDIMENSION *s1dim = s1->dims[i];
    PCDIMENSION *s2dim = s2->dims[i];

    if (strcasecmp(s1dim->name, s2dim->name) != 0)
      return PC_FALSE;

    if (s1dim->interpretation != s2dim->interpretation)
      return PC_FALSE;
  }

  return PC_TRUE;
}

/**
 * Return false if s1 and s2 don't have the same srids, or if there are
 * dimensions in s2 that are also in s1 but don't have the same interpretations,
 * scales or offsets. Otherwise return true. The function is used to determine
 * if re-interpretating the patch data is required when changing from one schema
 * (s1) to another (s2).
 */
uint32_t pc_schema_same_interpretations(const PCSCHEMA *s1, const PCSCHEMA *s2)
{
  size_t i;

  if (s1->srid != s2->srid)
    return PC_FALSE;

  for (i = 0; i < s2->ndims; i++)
  {
    PCDIMENSION *s2dim = s2->dims[i];
    PCDIMENSION *s1dim = pc_schema_get_dimension_by_name(s1, s2dim->name);

    if (s1dim)
    {
      if (s1dim->interpretation != s2dim->interpretation)
        return PC_FALSE;

      if (s1dim->scale != s2dim->scale)
        return PC_FALSE;

      if (s1dim->offset != s2dim->offset)
        return PC_FALSE;
    }
  }

  return PC_TRUE;
}