-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathocd_file_export.cpp
3129 lines (2724 loc) · 104 KB
/
ocd_file_export.cpp
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
805
806
807
808
809
810
811
812
813
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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2016-2021 Kai Pastor
*
* Some parts taken from file_format_oc*d8{.h,_p.h,cpp} which are
* Copyright 2012 Pete Curtis
*
* This file is part of OpenOrienteering.
*
* OpenOrienteering is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenOrienteering is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenOrienteering. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ocd_file_export.h"
#include <algorithm>
#include <array>
#include <cstddef>
#include <iterator>
#include <memory>
#include <utility>
#include <stdexcept>
#include <type_traits>
#include <vector>
#include <Qt>
#include <QtGlobal>
#include <QtMath>
#include <QDir>
#include <QFileInfo>
#include <QFlags>
#include <QFontMetricsF>
#include <QIODevice>
#include <QLatin1Char>
#include <QLatin1String>
#include <QObject>
#include <QPoint>
#include <QPointF>
#include <QRectF>
#include <QString>
#include <QTextCodec>
#include <QTextDecoder>
#include <QTextEncoder>
#include <QTextStream>
#include <QTransform>
#include <QVarLengthArray>
#include <QVariant>
#include "settings.h"
#include "core/georeferencing.h"
#include "core/map.h"
#include "core/map_color.h"
#include "core/map_coord.h"
#include "core/map_grid.h"
#include "core/map_part.h"
#include "core/map_view.h"
#include "core/objects/object.h"
#include "core/objects/object_operations.h"
#include "core/objects/text_object.h"
#include "core/symbols/area_symbol.h"
#include "core/symbols/combined_symbol.h"
#include "core/symbols/line_symbol.h"
#include "core/symbols/point_symbol.h"
#include "core/symbols/symbol.h"
#include "core/symbols/text_symbol.h"
#include "fileformats/file_format.h"
#include "fileformats/file_import_export.h"
#include "fileformats/ocd_file_format.h"
#include "fileformats/ocd_georef_fields.h"
#include "fileformats/ocd_icon.h"
#include "fileformats/ocd_types.h"
#include "fileformats/ocd_types_v8.h"
#include "fileformats/ocd_types_v9.h"
#include "fileformats/ocd_types_v11.h" // IWYU pragma: keep
#include "fileformats/ocd_types_v12.h" // IWYU pragma: keep
#include "templates/template.h"
#include "templates/template_map.h"
#include "util/encoding.h"
#include "util/util.h"
namespace OpenOrienteering {
namespace {
/// \todo De-duplicate (ocd_file_import.cpp)
static QTextCodec* codecFromSettings()
{
const auto& settings = Settings::getInstance();
const auto name = settings.getSetting(Settings::General_Local8BitEncoding).toByteArray();
return Util::codecForName(name);
}
/**
* Returns the index of the first color which can be assumed to be a pure spot color.
*
* During OCD import, spot colors are appended as regular colors at the end of
* the color list. This function tries to recover the index where the spot colors
* start, by looking at definition and usage of the colors at the end of the list.
*/
int beginOfSpotColors(const Map* map)
{
const auto num_colors = map->getNumColors();
auto first_pure_spot_color = num_colors;
for (auto i = num_colors; i > 0; )
{
--i;
const auto color = map->getColor(i);
if (color->getSpotColorMethod() != MapColor::SpotColor
|| map->isColorUsedByASymbol(color))
break;
--first_pure_spot_color;
}
return first_pure_spot_color;
}
quint32 makeSymbolNumber(const Symbol* symbol, quint32 symbol_number_factor)
{
auto number = quint32(0);
if (symbol->getNumberComponent(1) >= 0)
{
number = quint32(symbol->getNumberComponent(1));
if (symbol->getNumberComponent(2) >= 0 && symbol_number_factor >= 1000)
number = number * 100 + quint32(symbol->getNumberComponent(2)) % 100;
}
number = quint32(symbol->getNumberComponent(0)) * symbol_number_factor + number % symbol_number_factor;
// Symbol number 0.0 is not valid
return (number == 0) ? 1 : number;
}
void copySymbolHead(const Symbol& source, Symbol& symbol)
{
for (auto i = 0u; i < Symbol::number_components; ++i)
symbol.setNumberComponent(i, source.getNumberComponent(i));
symbol.setName(source.getName());
symbol.setHidden(source.isHidden());
symbol.setProtected(source.isProtected());
symbol.setHidden(source.isHidden());
symbol.setProtected(source.isProtected());
}
/**
* Test if the fill patterns constitute OCD structure "aligned rows".
*
* An "aligned rows" structure in OCD format is a basic pattern (Mapper: point symbol)
* which is repeated a along a row (OCD: structure width, Mapper: point distance)
* and in parallel rows (OCD: structure height, Mapper: line spacing).
*
* OCD format does not support multiple fill patterns in the way Mapper does.
* But if two Mapper fill patterns are equal in type, frequency and rotation,
* it is possible to merge them to a single OCD structure.
*/
bool isStructureAlignedRows(const AreaSymbol::FillPattern& first, const AreaSymbol::FillPattern& second) noexcept
{
return first.type == AreaSymbol::FillPattern::PointPattern
&& second.type == AreaSymbol::FillPattern::PointPattern
&& first.rotatable() == second.rotatable()
&& qFuzzyCompare(first.angle, second.angle)
&& first.line_spacing == second.line_spacing
&& first.point_distance == second.point_distance;
}
/**
* Test if the fill patterns constitute OCD structure "shifted rows".
*
* A "shifted rows" structure in OCD format is a variation of the "aligned rows"
* structure which prints the basic pattern with an offset of half structure
* in every second row.
*
* In Mapper, there is no explicit shifted rows structure. Basic row and shifted
* row need to be represented as explicit fill patterns with individual offsets.
* OCD format does not support custom offsets at all. To properly recognize what
* can be exported as OCD structure "shifted rows", we must establish the
* equality of two fill patterns, the equality of the frequency of the patterns,
* and the fact that the X and Y offsets from one pattern to the other is half
* the frequency of the patterns.
*
* Note that we explicitly allow for single bit errors (0.001 mm) when comparing
* the offset between first and second pattern with (half) pattern frequency.
*/
bool isStructureShiftedRows(const AreaSymbol::FillPattern& first, const AreaSymbol::FillPattern& second)
{
auto renamed = [](PointSymbol const& symbol, QString const& name) {
auto clone = duplicate(symbol);
clone->setName(name);
return clone;
};
return isStructureAlignedRows(first, second)
&& first.line_spacing
&& qAbs((first.line_offset - second.line_offset + first.line_spacing) % first.line_spacing - first.line_spacing / 2) <= 1
&& first.point_distance
&& qAbs((first.offset_along_line - second.offset_along_line + first.point_distance) % first.point_distance - first.point_distance / 2) <= 1
&& first.point
&& second.point
&& first.point->equals(renamed(*second.point, first.point->getName()).get());
}
using FillPatternSequence = QVarLengthArray<const AreaSymbol::FillPattern*, 8>;
/**
* Transform an area fill pattern sequence for OCD structure export.
*
* In Mapper, fill patterns are point symbols which are placed at certain offsets
* and which are repeated in X and Y direction. OCD format does not support such
* offsets, so we must move the point symbols elements instead.
*
* In addition, Mappper allows multiple explicit fill patterns. OCD format does
* not support such a structure. For some cases, we may resolve this situation
* by merging the Mapper fill patterns into a single OCD fill pattern.
*
* For simplicity, this function always creates and returns a clone,
* even if no adjustments are necessary.
*/
std::unique_ptr<PointSymbol> postProcessFillPattern(const FillPatternSequence& patterns, int structure_mode)
{
auto* first_point_pattern = patterns.front();
auto point_symbol = duplicate(*first_point_pattern->point);
// If the (cloned) first point pattern has non-zero offsets,
// we must apply them to the elements.
if (first_point_pattern->line_offset != 0
|| first_point_pattern->offset_along_line != 0)
{
for (int i = 0, last = point_symbol->getNumElements(); i < last; ++i)
{
if (auto* element = point_symbol->getElementObject(i))
element->move(first_point_pattern->line_offset, first_point_pattern->offset_along_line);
}
if ((point_symbol->getInnerRadius() > 0 && point_symbol->getInnerColor())
|| (point_symbol->getOuterWidth() > 0 && point_symbol->getOuterColor()))
{
// The central dot/circle must be converted to an explicit element to apply the offset.
auto* primary_element = new PointSymbol();
primary_element->setInnerRadius(point_symbol->getInnerRadius());
primary_element->setInnerColor(point_symbol->getInnerColor());
primary_element->setOuterWidth(point_symbol->getOuterWidth());
primary_element->setOuterColor(point_symbol->getOuterColor());
auto* object = new PointObject(primary_element);
object->setPosition(first_point_pattern->line_offset, first_point_pattern->offset_along_line);
point_symbol->addElement(0, object, primary_element);
// Now, the central dot/circle have been replaced by primary_element.
point_symbol->setInnerColor(nullptr);
point_symbol->setOuterColor(nullptr);
}
}
// Any remaining point patterns must be appended to the elements of
// point_symbol, applying offsets if needed, ...
using std::begin; using std::end;
auto first = begin(patterns) + 1;
auto last = end(patterns);
// ... except for the second pattern when the OCD structure is "shifted rows".
if (structure_mode == Ocd::StructureShiftedRows)
{
FILEFORMAT_ASSERT(patterns.size() == 2);
if (first != last)
++first;
}
auto i = point_symbol->getNumElements();
for (auto it = first; it != last; ++it)
{
auto const* pattern = *it;
auto const* pattern_symbol = pattern->point;
if ((pattern_symbol->getInnerRadius() > 0 && pattern_symbol->getInnerColor())
|| (pattern_symbol->getOuterWidth() > 0 && pattern_symbol->getOuterColor()))
{
auto* primary_element = new PointSymbol();
primary_element->setInnerRadius(pattern_symbol->getInnerRadius());
primary_element->setInnerColor(pattern_symbol->getInnerColor());
primary_element->setOuterWidth(pattern_symbol->getOuterWidth());
primary_element->setOuterColor(pattern_symbol->getOuterColor());
auto* object = new PointObject(primary_element);
object->setPosition(pattern->line_offset, pattern->offset_along_line);
point_symbol->addElement(i, object, primary_element);
++i;
}
for (int k = 0, last = pattern_symbol->getNumElements(); k < last; ++k)
{
auto* element_symbol = pattern_symbol->getElementSymbol(k);
auto* element_object = pattern_symbol->getElementObject(k);
if (!element_symbol || !element_object)
continue;
auto* object = element_object->duplicate();
object->move(pattern->line_offset, pattern->offset_along_line);
point_symbol->addElement(i, object, duplicate(*element_symbol).release());
++i;
}
}
return point_symbol;
}
/**
* Test if a Mapper line symbol can be represented by the double line/filling aspect
* of an OCD line symbol.
*
* This function helps to merge elements of combined symbols into OCD line symbols.
*/
bool maybeDoubleFilling(const LineSymbol* line)
{
return line
&& line->hasBorder()
&& line->getCapStyle() != LineSymbol::PointedCap
&& (!line->getDashSymbol() || line->getDashSymbol()->isEmpty())
&& (!line->getMidSymbol() || line->getMidSymbol()->isEmpty())
&& (!line->getStartSymbol() || line->getStartSymbol()->isEmpty())
&& (!line->getEndSymbol() || line->getEndSymbol()->isEmpty());
}
/**
* Test if a Mapper line symbol can be represented by the framing aspect
* of an OCD line symbol.
*
* This function helps to merge elements of combined symbols into OCD line symbols.
*/
bool maybeFraming(const LineSymbol* line)
{
return line
&& !line->hasBorder()
&& !line->isDashed()
&& line->getCapStyle() != LineSymbol::PointedCap
&& (!line->getDashSymbol() || line->getDashSymbol()->isEmpty())
&& (!line->getMidSymbol() || line->getMidSymbol()->isEmpty())
&& (!line->getStartSymbol() || line->getStartSymbol()->isEmpty())
&& (!line->getEndSymbol() || line->getEndSymbol()->isEmpty());
}
/**
* Test if a Mapper line symbol can be represented by the main line aspect
* of an OCD line symbol.
*
* This function helps to merge elements of combined symbols into OCD line symbols.
*/
bool maybeMainLine(const LineSymbol* line)
{
return line
&& !line->hasBorder();
}
/**
* Efficiently convert a single coordinate value to the OCD format.
*
* This function handles two responsibilities at the same time,
* in a constexpr implementation:
*
* - convert from 1/100 mm to 1/10 mm, rounding half up (for intervals of equal size),
* - shift by 8 bits (which are reserved for flags in OCD format).
*
* Neither rounding (the result of an integer division) half up
* nor shifting of signed integers ("implementation-defined")
* come out of the box in C++.
*/
constexpr qint32 convertPointMember(qint32 value)
{
return (value < -5) ? qint32(0x80000000u | ((0x7fffffu & quint32((value-4)/10)) << 8)) : qint32((0x7fffffu & quint32((value+5)/10)) << 8);
}
// convertPointMember() shall round half up.
Q_STATIC_ASSERT(convertPointMember(-16) == qint32(0xfffffe00u)); // __ down __
Q_STATIC_ASSERT(convertPointMember(-15) == qint32(0xffffff00u)); // up
Q_STATIC_ASSERT(convertPointMember( -6) == qint32(0xffffff00u)); // __ down __
Q_STATIC_ASSERT(convertPointMember( -5) == qint32(0x00000000u)); // up
Q_STATIC_ASSERT(convertPointMember( -1) == qint32(0x00000000u)); // up
Q_STATIC_ASSERT(convertPointMember( 0) == qint32(0x00000000u)); // unchanged
Q_STATIC_ASSERT(convertPointMember( +1) == qint32(0x00000000u)); // down
Q_STATIC_ASSERT(convertPointMember( +4) == qint32(0x00000000u)); // __ down __
Q_STATIC_ASSERT(convertPointMember( +5) == qint32(0x00000100u)); // up
Q_STATIC_ASSERT(convertPointMember(+14) == qint32(0x00000100u)); // __ down __
Q_STATIC_ASSERT(convertPointMember(+15) == qint32(0x00000200u)); // up
/**
* Convert a pair of coordinates to a point in OCD format.
*
* \see convertPointMember()
*/
Ocd::OcdPoint32 convertPoint(qint32 x, qint32 y)
{
return { convertPointMember(x), convertPointMember(-y) };
}
/**
* Convert a MapCoord's coordinate values to a point in OCD format.
*
* This function does not deal with flags.
*
* \see convertPointMember()
*/
Ocd::OcdPoint32 convertPoint(const MapCoord& coord)
{
return convertPoint(coord.nativeX(), coord.nativeY());
}
/**
* Convert a size to the OCD format.
*
* This function converts from 1/100 mm to 1/10 mm, rounding half up for positive values.
*/
constexpr qint16 convertSize(qint32 size)
{
return qint16((size+5) / 10);
}
/**
* Convert a size to the OCD format.
*
* This function converts from 1/100 mm to 1/10 mm, rounding half up for positive values.
*/
constexpr qint32 convertSize(qint64 size)
{
return qint32((size+5) / 10);
}
/**
* Convert an angle to the OCD format.
*
* This function converts from radians to 1/10 degrees, rounding to the nearest integer.
*/
int convertRotation(qreal angle)
{
return qRound(10 * qRadiansToDegrees(angle));
}
int getPatternSize(const PointSymbol* point)
{
if (!point)
return 0;
int count = 0;
for (int i = 0; i < point->getNumElements(); ++i)
{
int factor = 1;
if (point->getElementSymbol(i)->getType() == Symbol::Point)
{
factor = 0;
const PointSymbol* point_symbol = static_cast<const PointSymbol*>(point->getElementSymbol(i));
if (point_symbol->getInnerRadius() > 0 && point_symbol->getInnerColor())
++factor;
if (point_symbol->getOuterWidth() > 0 && point_symbol->getOuterColor())
++factor;
}
count += factor * int(2 + point->getElementObject(i)->getRawCoordinateVector().size());
}
if (point->getInnerRadius() > 0 && point->getInnerColor())
count += 2 + 1;
if (point->getOuterWidth() > 0 && point->getOuterColor())
count += 2 + 1;
return count * int(sizeof(Ocd::OcdPoint32));
}
/// String 9: color
QString stringForColor(int i, const MapColor& color)
{
const auto& cmyk = color.getCmyk();
QString string_9;
QTextStream out(&string_9, QIODevice::Append);
out << color.getName()
<< "\tn" << i
<< "\tc" << qRound(cmyk.c * 100)
<< "\tm" << qRound(cmyk.m * 100)
<< "\ty" << qRound(cmyk.y * 100)
<< "\tk" << qRound(cmyk.k * 100)
<< "\to" << (color.getKnockout() ? '0' : '1')
<< "\tt" << qRound(color.getOpacity() * 100);
if (color.getSpotColorMethod() == MapColor::CustomColor)
{
for (const auto& component : color.getComponents())
{
out << "\ts" << component.spot_color->getSpotColorName()
<< "\tp" << qRound(component.factor * 100);
}
}
else if (color.getSpotColorMethod() == MapColor::SpotColor)
{
out << "\ts" << color.getSpotColorName()
<< "\tp" << 100;
}
return string_9;
}
/// String 10: spot color
QString stringForSpotColor(int i, const MapColor& color)
{
const auto& cmyk = color.getCmyk();
QString string_10;
QTextStream out(&string_10, QIODevice::Append);
out << color.getSpotColorName()
<< "\tn" << i
<< "\tv1"
<< fixed << qSetRealNumberPrecision(1)
<< "\tc" << qRound(cmyk.c * 200)/2.0
<< "\tm" << qRound(cmyk.m * 200)/2.0
<< "\ty" << qRound(cmyk.y * 200)/2.0
<< "\tk" << qRound(cmyk.k * 200)/2.0
<< "\tf" << color.getScreenFrequency() * 10
<< "\ta" << color.getScreenAngle();
return string_10;
}
/// String 1030: view
QString stringForViewPar(const MapView& view, const MapCoord& area_offset, quint16 version)
{
QString string_1030;
QTextStream out(&string_1030, QIODevice::Append);
if (version == 8)
{
out << "\ts0\tt1";
}
else
{
const auto center = view.center() - area_offset;
const auto hatched = view.getMap()->isAreaHatchingEnabled() ? '1' : '0';
out << qSetRealNumberPrecision(6)
<< "\tx" << center.x()
<< "\ty" << -center.y()
<< "\tz" << view.getZoom()
<< "\tv0"
<< "\tm50"
<< "\tt50"
<< "\tb50"
<< "\tc50"
<< "\th" << hatched
<< "\td0";
}
if (version > 10)
{
const auto keyline = view.getMap()->isBaselineViewEnabled() ? '1' : '0';
out << "\tk" << keyline;
}
return string_1030;
}
} // namespace
quint16 OcdFileExport::default_version = 9;
OcdFileExport::OcdFileExport(const QString& path, const Map* map, const MapView* view, quint16 version)
: Exporter { path, map, view }
, ocd_version { version }
{
#ifdef MAPPER_DEVELOPMENT_BUILD
if (!ocd_version)
{
if (path.endsWith(QLatin1String("test-v8.ocd")))
ocd_version = 8;
else if (path.endsWith(QLatin1String("test-v9.ocd")))
ocd_version = 9;
else if (path.endsWith(QLatin1String("test-v10.ocd")))
ocd_version = 10;
else if (path.endsWith(QLatin1String("test-v11.ocd")))
ocd_version = 11;
else if (path.endsWith(QLatin1String("test-v12.ocd")))
ocd_version = 12;
}
#endif
if (!ocd_version)
ocd_version = decltype(ocd_version)(map->property(OcdFileFormat::versionProperty()).toInt());
if (!ocd_version)
ocd_version = default_version;
}
OcdFileExport::~OcdFileExport() = default;
template<class Encoding>
QTextCodec* OcdFileExport::determineEncoding()
{
return nullptr;
}
template<>
QTextCodec* OcdFileExport::determineEncoding<Ocd::Custom8BitEncoding>()
{
auto encoding = codecFromSettings();
if (!encoding)
{
addWarning(::OpenOrienteering::OcdFileExport::tr("Encoding '%1' is not available. Check the settings.")
.arg(Settings::getInstance().getSetting(Settings::General_Local8BitEncoding).toString()));
encoding = QTextCodec::codecForLocale();
}
return encoding;
}
bool OcdFileExport::exportImplementation()
{
switch (ocd_version)
{
case 8:
return exportImplementation<Ocd::FormatV8>();
case 9:
case 10:
return exportImplementation<Ocd::FormatV9>();
case 11:
return exportImplementation<Ocd::FormatV11>();
case 12:
return exportImplementation<Ocd::FormatV12>();
default:
throw FileFormatException(
::OpenOrienteering::Exporter::tr("Could not write file: %1").
arg(::OpenOrienteering::OcdFileExport::tr("OCD files of version %1 are not supported!")
.arg(ocd_version))
);
}
}
namespace {
void setupFileHeaderGeneric(quint16 actual_version, Ocd::FileHeaderGeneric& header)
{
header.version = actual_version;
header.file_type = Ocd::TypeMap;
switch (actual_version)
{
case 8:
header.file_type = Ocd::TypeMapV8;
break;
case 9:
header.subversion = 4;
break;
case 10:
header.subversion = 2;
break;
case 11:
header.subversion = 3;
break;
default:
; // nothing
}
}
} // namespace
template<class Format>
bool OcdFileExport::exportImplementation()
{
OcdFile<Format> file;
custom_8bit_encoding = determineEncoding<typename Format::Encoding>();
if (custom_8bit_encoding)
{
addParameterString = [&file, this](qint32 string_type, const QString& string) {
file.strings().insert(string_type, custom_8bit_encoding->fromUnicode(string));
};
}
else
{
addParameterString = [&file](qint32 string_type, const QString& string) {
file.strings().insert(string_type, string.toUtf8());
};
}
// Check for a necessary offset (and add related warnings early).
area_offset = calculateAreaOffset();
uses_registration_color = map->isColorUsedByASymbol(map->getRegistrationColor());
setupFileHeaderGeneric(ocd_version, *file.header());
exportSetup(file); // includes colors
exportSymbols(file);
exportObjects(file);
exportTemplates(file);
exportExtras(file);
auto& data = file.constByteArray();
return device()->write(data) == data.size();
}
MapCoord OcdFileExport::calculateAreaOffset()
{
auto area_offset = QPointF{};
// Attention: When changing ocd_bounds, update the warning messages, too.
auto ocd_bounds = QRectF{QPointF{-2000, -2000}, QPointF{2000, 2000}};
auto objects_extent = map->calculateExtent();
if (objects_extent.isValid() && !ocd_bounds.contains(objects_extent))
{
if (objects_extent.width() < ocd_bounds.width()
&& objects_extent.height() < ocd_bounds.height())
{
// The extent fits into the limited area.
addWarning(::OpenOrienteering::OcdFileExport::tr("Coordinates are adjusted to fit into the OCAD 8 drawing area (-2 m ... 2 m)."));
area_offset = objects_extent.center();
}
else
{
// The extent is too wide to fit.
// Only move the objects if they are completely outside the drawing area.
// This avoids repeated moves on open/save/close cycles.
if (!objects_extent.intersects(ocd_bounds))
{
addWarning(::OpenOrienteering::OcdFileExport::tr("Coordinates are adjusted to fit into the OCAD 8 drawing area (-2 m ... 2 m)."));
std::size_t count = 0;
auto calculate_average_center = [&area_offset, &count](const Object* object) {
area_offset *= qreal(count)/qreal(count+1);
++count;
area_offset += object->getExtent().center() / count;
};
map->applyOnAllObjects(calculate_average_center);
}
addWarning(::OpenOrienteering::OcdFileExport::tr("Some coordinates remain outside of the OCAD 8 drawing area."
" They might be unreachable in OCAD."));
}
if (area_offset.manhattanLength() > 0)
{
// Round offset to 100 m in projected coordinates, to avoid crude grid offset.
constexpr auto unit = 100;
auto projected_offset = map->getGeoreferencing().toProjectedCoords(MapCoordF(area_offset));
projected_offset.rx() = qreal(qRound(projected_offset.x()/unit)) * unit;
projected_offset.ry() = qreal(qRound(projected_offset.y()/unit)) * unit;
area_offset = map->getGeoreferencing().toMapCoordF(projected_offset);
}
}
return MapCoord{area_offset};
}
template<>
void OcdFileExport::exportSetup(OcdFile<Ocd::FormatV8>& file)
{
{
auto setup = reinterpret_cast<Ocd::SetupV8*>(file.byteArray().data() + file.header()->setup_pos);
const auto& georef = map->getGeoreferencing();
auto add_warning = [this](const QString& w){ addWarning(w); };
auto fields = OcdGeorefFields::fromGeoref(georef, add_warning);
setup->map_scale = fields.m;
setup->real_offset_x = fields.x;
setup->real_offset_y = fields.y;
setup->real_angle = fields.a;
if (fields.i)
addWarning(::OpenOrienteering::OcdFileExport::tr("The georeferencing cannot be saved in OCD version 8."));
if (view)
{
setup->center = convertPoint(view->center() - area_offset);
setup->zoom = view->getZoom();
}
else
{
setup->zoom = 1;
}
}
{
auto notes = custom_8bit_encoding->fromUnicode(map->getMapNotes());
if (!notes.isEmpty())
{
auto size = notes.size() + 1;
if (size > 32768)
{
/// \todo addWarning(...)
size = 32768;
notes.truncate(23767);
}
file.header()->info_pos = quint32(file.byteArray().size());
file.header()->info_size = quint32(size);
file.byteArray().append(notes).append('\0');
}
}
{
auto& symbol_header = file.header()->symbol_header;
auto num_colors = map->getNumColors();
auto spotColorNumber = [this, num_colors](const MapColor* color)->quint16 {
quint16 number = 0;
for (auto i = 0; i < num_colors; ++i)
{
const auto* current = map->getColor(i);
if (current == color)
break;
if (current->getSpotColorMethod() == MapColor::SpotColor)
++number;
}
return number;
};
symbol_header.num_separations = spotColorNumber(nullptr);
if (symbol_header.num_separations > 24)
throw FileFormatException(::OpenOrienteering::OcdFileExport::tr("The map contains more than 24 spot colors which is not supported by OCD version 8."));
auto begin_of_spot_colors = beginOfSpotColors(map);
if (uses_registration_color)
++begin_of_spot_colors; // in ocd output (ocd_number below)
if (begin_of_spot_colors > 256)
throw FileFormatException(::OpenOrienteering::OcdFileExport::tr("The map contains more than 256 colors which is not supported by OCD version 8."));
using std::begin; using std::end;
auto separation_info = symbol_header.separation_info;
auto color_info = symbol_header.color_info;
quint16 ocd_number = 0;
if (uses_registration_color)
{
color_info->number = 0;
color_info->name = toOcdString(Map::getRegistrationColor()->getName());
color_info->cmyk = { 200, 200, 200, 200 }; // OC*D stores CMYK values as integers from 0-200.
std::fill(begin(color_info->separations), begin(color_info->separations) + symbol_header.num_separations, 200);
std::fill(begin(color_info->separations) + symbol_header.num_separations, end(color_info->separations), 255);
++color_info;
++ocd_number;
}
for (int i = 0; i < num_colors; ++i)
{
const auto* color = map->getColor(i);
const auto& cmyk = color->getCmyk();
// OC*D stores CMYK values as integers from 0-200.
auto ocd_cmyk = Ocd::CmykV8 {
quint8(qRound(200 * cmyk.c)),
quint8(qRound(200 * cmyk.m)),
quint8(qRound(200 * cmyk.y)),
quint8(qRound(200 * cmyk.k))
};
if (color->getSpotColorMethod() == MapColor::SpotColor)
{
separation_info->name = toOcdString(color->getSpotColorName());
separation_info->cmyk = ocd_cmyk;
separation_info->raster_freq = quint16(qRound(10 * color->getScreenFrequency()));
separation_info->raster_angle = quint16(qRound(10 * color->getScreenAngle()));
++separation_info;
if (ocd_number >= begin_of_spot_colors)
continue; // Just a spot color, not a regular map color.
std::fill(begin(color_info->separations), end(color_info->separations), 255);
auto index = spotColorNumber(color);
if (index >= symbol_header.num_separations)
throw FileFormatException(::OpenOrienteering::OcdFileExport::tr("Invalid spot color."));
color_info->separations[index] = 200;
}
else
{
std::fill(begin(color_info->separations), end(color_info->separations), 255);
if (color->getSpotColorMethod() == MapColor::CustomColor)
{
for (const auto& component : color->getComponents())
{
auto index = spotColorNumber(component.spot_color);
if (index >= symbol_header.num_separations)
throw FileFormatException(::OpenOrienteering::OcdFileExport::tr("Invalid spot color."));
color_info->separations[index] = quint8(qRound(component.factor * 200));
}
}
}
color_info->number = ocd_number;
color_info->name = toOcdString(color->getName());
color_info->cmyk = ocd_cmyk;
++color_info;
++ocd_number;
}
symbol_header.num_colors = ocd_number;
}
}
template<class Format>
void OcdFileExport::exportSetup(OcdFile<Format>& /*file*/)
{
exportGeoreferencing();
exportSetup();
}
void OcdFileExport::exportGeoreferencing()
{
const auto& georef = map->getGeoreferencing();
auto add_warning = [this](const QString& w){ addWarning(w); };
auto fields = OcdGeorefFields::fromGeoref(georef, add_warning);
auto& grid = map->getGrid();
auto grid_spacing_real = 500.0;
auto grid_spacing_map = 50.0;
auto spacing = std::min(grid.getHorizontalSpacing(), grid.getVerticalSpacing());
switch (grid.getUnit())
{
case MapGrid::MillimetersOnMap:
grid_spacing_map = spacing;
grid_spacing_real = spacing * georef.getScaleDenominator() / 1000;
break;
case MapGrid::MetersInTerrain:
grid_spacing_map = spacing * 1000 / georef.getScaleDenominator();
grid_spacing_real = spacing;
break;
}
QString string_1039;
QTextStream out(&string_1039, QIODevice::Append);
out << fixed
<< "\tm" << fields.m
<< qSetRealNumberPrecision(4)
<< "\tg" << grid_spacing_map
<< "\tr" << fields.r
<< "\tx" << fields.x
<< "\ty" << fields.y
<< qSetRealNumberPrecision(8)
<< "\ta" << fields.a
<< qSetRealNumberPrecision(6)
<< "\td" << grid_spacing_real
<< "\ti" << fields.i;
if (ocd_version > 9)
{
out << qSetRealNumberPrecision(2)
<< "\tb" << 0.0
<< "\tc" << 0.0;
}
addParameterString(1039, string_1039);
}
void OcdFileExport::exportSetup()
{
// View
if (view)
{
addParameterString(1030, stringForViewPar(*view, area_offset, ocd_version));
}
// Map notes
if (ocd_version >= 9 && !map->getMapNotes().isEmpty())
{
auto param = 1061;
auto notes = map->getMapNotes();
if (ocd_version <= 10 && !notes.isEmpty())
{
param = 11;
if (!notes.endsWith(QLatin1Char('\n')))
notes.append(QLatin1Char('\n'));
}
notes.replace(QLatin1String("\n"), QLatin1String("\r\n"));
notes.replace(QLatin1String("\r\r"), QLatin1String("\r")); // just in case
addParameterString(param, notes);