Repository navigation
Expand file tree
/
Copy pathmod_data.cc
More file actions
804 lines (687 loc) · 26.2 KB
/
Copy pathmod_data.cc
File metadata and controls
804 lines (687 loc) · 26.2 KB
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
667
668
669
670
671
672
673
674
675
676
677
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
#include "mod_data.h"
#include "composite_data.h"
#include "translated_data.h"
#include "vicar_data.h"
#include "z_offset_data.h"
#include <stdexcept>
#include <fstream>
#include <list>
#include <sstream>
#include <utility>
namespace rsvp
{
namespace
{
// The tokens run together, for an error message
std::string join_tokens(const std::list<std::string> &tokens)
{
std::string joined;
for (const auto &t : tokens)
{
joined += t;
}
return joined;
}
// Pop the block at the front of `tokens` - from its opening `{` to
// the matching (not just the next) `}` - into a list of its own, to
// be sent through another round of parsing.
//
// The front of `tokens` must be a `{`. Throws `missing_brace_error`
// if the tokens run out before the matching `}`.
std::list<std::string>
extract_block(std::list<std::string> *tokens,
const std::string &missing_brace_error)
{
std::list<std::string> block;
// The opening `{` of the first iteration takes this to 1
int stack_depth = 0;
for (;;)
{
if (tokens->empty())
{
// We haven't found our final closing `}`, but we've run
// out of tokens. Abort!
throw std::runtime_error(missing_brace_error);
}
block.push_back(tokens->front());
if (tokens->front() == "{")
{
stack_depth += 1;
}
else if (tokens->front() == "}")
{
stack_depth -= 1;
}
tokens->pop_front();
if (stack_depth <= 0)
{
return block;
}
}
}
}
// Parse the `alpha_band` from the properties tokens
static bool apply_properties(const std::shared_ptr<ImageData> &image,
std::list<std::string> *tokens,
const std::string &filename)
{
// No image is a failure case
if (!image)
{
return false;
}
// No tokens is not a failure case - there are just no properties!
if (tokens->empty())
{
return true;
}
if (tokens->size() < 3 || tokens->front() != "[" ||
tokens->back() != "]")
{
throw std::runtime_error(
filename +
": Invalid property arguments in terrain mod file: " +
join_tokens(*tokens));
}
// Pop off the opening and closing brackets
tokens->pop_front();
tokens->pop_back();
while (not tokens->empty())
{
if (tokens->front() == "alpha_band")
{
if (tokens->size() < 2)
{
// `alpha_band` needs a channel
throw std::runtime_error(
filename +
": Invalid syntax in terrain mod file: "
"`alpha_band` requires a band number");
}
// Pop off the `alpha_band`
tokens->pop_front();
int alpha_band;
try
{
size_t len;
alpha_band = std::stoi(tokens->front(), &len, 10);
// Check that we consumed the entire token - otherwise
// something went wrong and we should abort
if (len < tokens->front().size())
{
throw std::logic_error("");
}
}
catch (const std::logic_error &)
{
throw std::runtime_error(
filename +
": Invalid syntax in terrain mod file: "
"error parsing alpha_band; invalid int value `" +
tokens->front() + "`");
}
// Pop off the value
tokens->pop_front();
// Refuse a band the image does not have here, where the
// file can be named, rather than when a composite first
// blends by it. That only follows from the band count when
// there is more than one: a single-band image is blended as
// opaque and its alpha band never read, and a composite
// reports the count of its first child, which says nothing
// about the rest. A negative band means no alpha band at
// all, which is allowed.
const int bands = image->get_bands();
if (bands > 1 && alpha_band >= bands)
{
throw std::runtime_error(
filename + ": alpha_band " +
std::to_string(alpha_band) +
" is out of range for an image with " +
std::to_string(image->get_bands()) + " band(s)");
}
// Apply it to the image
image->set_alpha_band(alpha_band);
}
else
{
throw std::runtime_error(
filename +
": Found invalid image property token in terrain mod "
"file: " +
tokens->front());
}
}
return true;
}
std::shared_ptr<ImageData>
ModData::read_modfile(const std::string &filename)
{
std::ifstream mod_file(filename);
std::string token;
std::list<std::string> tokens;
// If we failed to open the file, abort
if (!mod_file.is_open())
{
throw std::runtime_error("Could not open mod file: " + filename);
}
// Build up a list of whitespace-separated tokens
while (mod_file >> token)
{
tokens.push_back(token);
}
mod_file.close();
// If the first token is not "I~", this is not a valid .mod file
if (tokens.empty() or tokens.front() != "I~")
{
throw std::runtime_error(
filename + ": No leading `I~` in this mod file - saw `" +
token + "` instead!");
}
// Remove the leading "I~"
tokens.pop_front();
// As far as we can tell, we've got a valid mod file - so return the
// parsing of that!
return parse_imagedata(&tokens, filename);
}
std::shared_ptr<ImageData>
ModData::read_bare_vicarfile(const std::string &filename)
{
std::shared_ptr<VicarData> raw_result =
VicarData::read_vicarfile(filename);
if (raw_result)
{
// Try to set the alpha channel appropriately for terrain
// classification ".tc" files and heightmap ".ht" files.
const auto alpha_band_to_set =
(get_file_extension(filename) == "tc") ? 1 : 2;
raw_result->set_alpha_band(alpha_band_to_set);
double x_offset = 0.0;
double y_offset = 0.0;
double map_scale = 1.0;
std::string token;
size_t equal_pos;
std::stringstream comment_stream(raw_result->get_labels());
while (comment_stream >> token)
{
equal_pos = token.find('=');
// We're tokenizing on spaces, so it's always possible to break
// up a quoted string by accident - just ignore those for our
// use case
if (equal_pos == std::string::npos)
{
continue;
}
std::string tag = token.substr(0, equal_pos);
std::string value =
token.substr(equal_pos + 1, std::string::npos);
if (tag == "TASK")
{
// On MSL, the labels we care about appear in the system
// labels (before any PROPERTY labels). On M2020, they
// appear in the PROPERTY=SURFACE_PROJECTION_PARMS section.
// So... in either case, if we hit a TASK, we've gone too
// far, but otherwise we might be vulnerable to repeated
// keys.
break;
}
if (tag == "X_AXIS_MINIMUM")
{
std::stringstream valuestream(value);
valuestream >> x_offset;
}
else if (tag == "Y_AXIS_MINIMUM")
{
std::stringstream valuestream(value);
valuestream >> y_offset;
}
else if (tag == "MAP_SCALE")
{
if (value.find('(') != std::string::npos)
{
// We have an M2020-style
// `MAP_SCALE=(0.0158105,0.0158105)`.
double other_scale = -1.0;
if (sscanf(value.c_str(),
"(%lf,%lf)",
&map_scale,
&other_scale) != 2)
{
throw std::runtime_error(
filename +
": Could not parse a MAP_SCALE from `" +
value + "`");
}
}
else
{
// We have an MSL-style `MAP_SCALE=0.046456`
std::stringstream valuestream(value);
valuestream >> map_scale;
}
}
}
auto result = std::make_shared<AlphaBlendingCompositeData>();
// .mod files do not support rotations, so that parameter will
// always be zero.
result->add_image(std::make_shared<TranslatedData>(
raw_result, x_offset, y_offset, map_scale, 0.0));
result->set_alpha_band(alpha_band_to_set);
return result;
}
return nullptr;
}
std::shared_ptr<ImageData>
ModData::parse_imagedata(std::list<std::string> *tokens,
const std::string &filename)
{
/* Per the VSL README.MOD file:
Following this header, which is used by the Image class to
identify the mod file type, is a block which specifies some
combination of one or more images with the following form:
{ block_type block_argument_1 ... block_argument_n
[ optional_block_parameters ]
}
Note that all separators {,},[,],etc. must be surrounded
by white space characters for the parser to correctly
identify them.
We therefore expect the next non-blank character to be a '{',
and the last to be a '}'.
*/
// Special handling of "empty" case
if (tokens->size() == 2 && tokens->front() == "{" &&
tokens->back() == "}")
{
throw std::runtime_error(
filename +
": Invalid image arguments; argument is an empty block {}; "
"expects at least one argument in the form: { block_type "
"block_argument_1 ... block_argument_n "
"[ optional_block_parameters ] }");
}
if (tokens->size() < 3 || tokens->front() != "{" ||
tokens->back() != "}")
{
throw std::runtime_error(
filename +
": Invalid image arguments: expects at least one argument in "
"the form: { block_type block_argument_1 ... "
"block_argument_n [ optional_block_parameters ] }");
}
tokens->pop_front();
tokens->pop_back();
if (tokens->front() == "composite" || tokens->front() == "scoredmap")
{
return parse_compdata(tokens, filename);
}
else if (tokens->front() == "transform")
{
return parse_transdata(tokens, filename);
}
else if (tokens->front() == "file")
{
return parse_filedata(tokens, filename);
}
else if (tokens->front() == "deinterpolate")
{
return parse_deinterpolate(tokens, filename);
}
else if (tokens->front() == "zoffset")
{
return parse_zoffset(tokens, filename);
}
else
{
throw std::runtime_error(
filename + ": Unknown Image arguments: " + tokens->front());
}
}
std::shared_ptr<ImageData>
ModData::parse_zoffset(std::list<std::string> *tokens,
const std::string &filename)
{
// zoffset blocks have the form:
//
// { zoffset block z_offset z_scale }
//
// ModData::parse_imagedata stripped off the surrounding brackets
if (tokens->size() < 4 || tokens->front() != "zoffset")
{
throw std::runtime_error(
filename +
": Invalid z offset argument form: expected form `{ "
"zoffset block z_offset z_scale }` but got `" +
join_tokens(*tokens) + "`");
}
tokens->pop_front();
// Check that we appear to have a block
if (tokens->front() != "{")
{
throw std::runtime_error(
filename +
": Invalid z offset argument form: expected "
"block as first argument");
}
// Extract the embedded block
std::list<std::string> local_tokens = extract_block(
tokens, filename + ": Z offset arguments missing closing `}`");
// We've extracted the embedded block, and now we need to extract the
// offset and scale
if (tokens->size() != 2)
{
throw std::runtime_error(
filename +
": ZOffset block does not have proper offset and scale");
}
double z_offset;
double z_scale;
try
{
z_offset = std::stod(tokens->front());
}
catch (const std::exception &e)
{
throw std::runtime_error(
filename + ": Error parsing z_offset: Invalid double value `" +
tokens->front() + "`: " + e.what());
}
// Pop off the offset value
tokens->pop_front();
try
{
z_scale = std::stod(tokens->front());
}
catch (const std::exception &e)
{
throw std::runtime_error(
filename + ": Error parsing z_scale: Invalid double value `" +
tokens->front() + "`: " + e.what());
}
// Pop off the value
tokens->pop_front();
// We've now extracted everything - actually allocate some memory now.
std::shared_ptr<ImageData> embedded =
ModData::parse_imagedata(&local_tokens, filename);
if (embedded == nullptr)
{
throw std::runtime_error(filename +
": Unable to parse embedded image data");
}
auto result = std::make_shared<ZOffsetData>(embedded);
for (int band = 0; band < result->get_bands(); band++)
{
result->set_offset_and_scale(band, z_offset, z_scale);
}
return result;
}
std::shared_ptr<ImageData>
ModData::parse_deinterpolate(std::list<std::string> *tokens,
const std::string &filename)
{
// Deinterpolate blocks have the form:
//
// { deinterpolate block }
//
// ModData::parse_imagedata stripped off the surrounding brackets
if (tokens->size() < 4 || tokens->front() != "deinterpolate")
{
throw std::runtime_error(
filename +
": Invalid deinterpolate arguments: arguments should have the "
"form { deinterpolate block } but got " +
join_tokens(*tokens));
}
tokens->pop_front();
std::shared_ptr<ImageData> result = parse_imagedata(tokens, filename);
if (result)
{
result->set_interpolating(false);
}
return result;
}
std::shared_ptr<ImageData>
ModData::parse_filedata(std::list<std::string> *tokens,
const std::string &filename)
{
// Files have the form:
//
// { file filespec [ parameters ] }
//
// ModData::parse_imagedata stripped off the surrounding brackets
if (tokens->size() < 2 || tokens->front() != "file")
{
throw std::runtime_error(
filename +
": Invalid file arguments: arguments should have the "
"form { file filespec [ parameters ] } but got " +
join_tokens(*tokens));
}
// Pop off "file"
tokens->pop_front();
// Now we have the file path at the front of the list
std::string path;
if (tokens->front().at(0) == '/')
{
path = tokens->front();
}
else
{
size_t last_slash = filename.rfind('/');
if (last_slash == std::string::npos)
{
throw std::runtime_error("Invalid mod data filepath. Expected "
"absolute filepath. Got: " +
filename);
}
path = filename.substr(0, last_slash) + "/" + tokens->front();
}
// Pop off the path
tokens->pop_front();
// We come to an interesting case. As currently established, .ht and
// .tc files contain their own offsets/scalings, and we can create the
// appropriate hierarchy of `TranslatedData` and `VicarData` objects
// with `ModData::read_bare_vicarfile`. That way we can use a raw vicar
// file as a heightmap in RSVP by specifying the following (pseudo)
// RML:
//
// <Terrain><Heightfile>heightmap.ht</Heightfile</Terrain>
//
// _However_, as currently used on MSL, mod files generated by OPGS
// explicitly contain the the transforms extracted from the file
// headers:
//
// ~I { transform { file heightmap.ht } <translated_parms> }
//
// That means that we _must_ ignore the transform in the file headers
// and must _not_ use `ModData::read_bare_vicarfile` to parse .ht and
// .tc files to prevent double-transforming the data.
const std::string extension = get_file_extension(path);
std::shared_ptr<ImageData> result;
if (extension == "ht" || extension == "tc")
{
// Parse .ht and .tc files as raw, untransformed vicar files
result = VicarData::read_vicarfile(path);
}
else
{
// Parse everything else in our usual manner
result = ImageData::read(path);
}
// Fail fast if we didn't parse the file appropriately
if (result == nullptr)
{
throw std::runtime_error(
filename + ": Unable to read filedata from: " + path);
}
// Try to set the alpha channel appropriately for terrain
// classification ".tc" files and heightmap ".ht" files.
if (extension == "tc")
{
result->set_alpha_band(1);
}
else if (extension == "ht")
{
result->set_alpha_band(2);
}
// Now that we've set that default value, go apply the remaining
// properties (which may overwrite the alpha_band)
if (!apply_properties(result, tokens, filename))
{
throw std::runtime_error(
filename + ": Unable to apply properties to image data");
}
return result;
}
std::shared_ptr<ImageData>
ModData::parse_compdata(std::list<std::string> *tokens,
const std::string &filename)
{
// Composites have the form:
//
// { composite block_1 block_2 ... block_n [ parameters ] }
//
// ModData::parse_imagedata stripped off the surrounding brackets.
// This function also handles "scoredmap"s
// Check for special "empty case". Added when addressing Issue #3071.
bool is_valid_empty_case =
(tokens->size() == 1 && tokens->front() == "composite");
// We need the empty case or at least 3 tokens (`composite { }`)
if (!is_valid_empty_case &&
(tokens->size() < 3 ||
(tokens->front() != "composite" &&
tokens->front() != "scoredmap")))
{
throw std::runtime_error(
filename +
": Invalid composite arguments: expected arguments of the "
"form `composite|scoredmap "
"block_1 block_2 ... block_n [ parameters ]` but got: " +
join_tokens(*tokens));
}
std::string composite_type = tokens->front();
// Pop off "composite"
tokens->pop_front();
if (!is_valid_empty_case && tokens->front() != "{")
{
throw std::runtime_error(
filename +
": Invalid composite arguments: first block missing `{`");
}
std::shared_ptr<CompositeData> result;
if (composite_type == "composite")
{
result = std::make_shared<AlphaBlendingCompositeData>();
}
else
{
result = std::make_shared<ScoredCompositeData>();
}
// Bail out quickly if we failed.
if (result == nullptr)
{
throw std::runtime_error(
filename + ": Unable to create the image's CompositeData");
}
// Parse each embedded block in turn
while (not tokens->empty() and tokens->front() == "{")
{
std::list<std::string> local_tokens = extract_block(
tokens,
filename +
": Invalid composite arguments: contains "
"block missing closing `}`");
std::shared_ptr<ImageData> embedded =
ModData::parse_imagedata(&local_tokens, filename);
if (embedded == nullptr)
{
throw std::runtime_error(
filename +
": Invalid composite arguments: unable to parse "
"embedded image");
}
result->add_image(embedded);
}
// Try to set the alpha band appropriately for composited heightmaps
// (.mod files) and composited terrain classifications (.mod_tc files)
const std::string file_extension = get_file_extension(filename);
if (!file_extension.empty())
{
if (file_extension == "mod")
{
result->set_alpha_band(2);
}
else if (file_extension == "mod_tc")
{
result->set_alpha_band(1);
}
// Now that we've set that default value, go apply the remaining
// properties (which may overwrite the alpha_band)
if (!apply_properties(result, tokens, filename))
{
throw std::runtime_error(
filename + ": Unable to apply properties to compdata");
}
}
if (!tokens->empty())
{
throw std::runtime_error(
filename +
": Invalid composite arguments: found unexpected tokens: " +
join_tokens(*tokens));
}
return result;
}
std::shared_ptr<ImageData>
ModData::parse_transdata(std::list<std::string> *tokens,
const std::string &filename)
{
// Transforms have the form:
//
// { transform block t1 t2 t3 t4 t5 t6 }
//
// ModData::parse_imagedata stripped off the surrounding brackets, so
// we need at _least_ 8 tokens
if (tokens->size() < 8 || tokens->front() != "transform")
{
throw std::runtime_error(
filename +
": Invalid transdata arguments: expected arguments of the "
"form `transform block t1 t2 t3 t4 t5 t6` but got: " +
join_tokens(*tokens));
}
// Pop off "transform"
tokens->pop_front();
double affine_transform[6] = {0};
for (int i = 5; i >= 0; i--)
{
try
{
affine_transform[i] = std::stod(tokens->back());
}
catch (const std::exception &e)
{
throw std::runtime_error(
filename +
": Error parsing transform: invalid double value `" +
tokens->back() + "`: " + e.what());
}
tokens->pop_back();
}
// At this point, we've stripped off everything but the contained
// block. For that... we go back to the start and recurse again!
std::shared_ptr<ImageData> contents =
ModData::parse_imagedata(tokens, filename);
// If something failed in the deeper parsing, abort
if (contents == nullptr)
{
throw std::runtime_error(filename +
": Unable to parse transform ImageData");
}
return std::make_shared<TranslatedData>(contents,
affine_transform[0],
affine_transform[1],
affine_transform[2],
affine_transform[3],
affine_transform[4],
affine_transform[5]);
}
}