-
Notifications
You must be signed in to change notification settings - Fork 2
/
photoscenary.jl
1463 lines (1338 loc) · 61.6 KB
/
photoscenary.jl
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
#=
Autor: Adriano Bassignana Bargamo 2021
Licence: GPL 2
Exite code:
0 - regular execution
1 - The version check did not pass
Performance:
On average with a 70 mbit connection (7-8 MB / s) the ArcGIS site from a flow of 1 MB / s (8 mbit) This places a limit on the download capacity,
I don't know if it can be amplified with multiple connections, but I think not, as it is related to the IP of the machine.
The only possibility is to parallelize with more sophisticated techniques.
However if the files are large it is not necessary to increase the number of threads too much julia -t 6 can be absolutely fine in these cases.
While if smaller formats are used (series -c 0,1,2) the advantage of many threads is considerable.
Behavior of the program:
Currently it does not leave logs during some activities, eg it can be quite depressing not to see anything when starting a
download with very large images (eg 8K or 16K) especially if you use a lot of threads.
In this case all the work takes place in the background and no messages are observed.
Don't worry, the program is doing its job. However, a more effective monitor will soon be added.
----------
Execution with thread and CPU
julia -t 10 -p 2 photoscenary.jl ...
it is possible to manage multithreaded and multi CPU processes with Julia through these two options:
-t m : The maximum number of threads that can be followed simultaneously.
-p n : The number of CPUs that can be used
----------
Search LAT and LON from Airport Tower Freq Radio
using CSV
using CSVFiles
using DataFrames
using DataFramesMeta
df = CSV.File("airports.csv"; normalizenames=true, delim=" ", select=["LAT","LON","ICAO","NAME"], decimal='.')
...
CSV.Row: (LAT = -17.9318, LON = 31.0928, ICAO = "FVHA")
Search airport ID
for r in df
if cmp(r[3],"LIME") == 0 println(r) end
end
=#
using Pkg
if VERSION < v"1.5.4"
println("The actiual Julia is ",VERSION, " The current version is too old!\nPlease upgrade Julia to version 1.5.0 but preferably install the 1.6.x or later (exit code 500)")
ccall(:jl_exit, Cvoid, (Int32,), 500)
elseif VERSION >= v"1.6.0"
println("The actiual Julia is ",VERSION, " The current version is correct in order to obtain the best performances")
else
println("The actiual Julia is ",VERSION, " The current version is correct,\nIn order to obtain the best performancesy install the 1.6.x or later version")
end
versionProgram = "0.4.00"
versionProgramDate = "20230523"
homeProgramPath = pwd()
unCompletedTiles = Dict{Int64,Int64}()
println("\nPhotoscenary.jl ver: $versionProgram date: $versionProgramDate System prerequisite test\n")
begin
local restartIsRequestCauseUpgrade = 0
try
##using ImageView
##using JuliaDB Obsolete!
catch
restartIsRequestCauseUpgrade = 2
end
try
import ImageMagick
import Unicode: graphemes # To solve the problem of an error in extracting unicode characters from a string.
using MemPool
using Dates
using Unicode
using Downloads
using Logging
using Distributed
using LightXML
using ArgParse
using Printf
using HTTP
using FileIO
using Images # Warning: 20210910 possible problems with PLMakie
using ImageIO
using CSV
using DataFrames
using DataFramesMeta
using Serialization
using IndexedTables
using Geodesy
using Parsers
using Sockets
using EzXML
using ThreadSafeDicts
using Logging
catch
if restartIsRequestCauseUpgrade == 0 restartIsRequestCauseUpgrade = 1 end
end
try
if restartIsRequestCauseUpgrade >= 2
##Pkg.add("ImageView") # If this is execute is necessary to restart Julia
##Pkg.add("JuliaDB")
end
if restartIsRequestCauseUpgrade >= 1
println("\nInstal the packeges necessary for photoscenary.jl execution")
Pkg.add("MemPool")
Pkg.add("Dates")
Pkg.add("Unicode")
Pkg.add("Downloads")
Pkg.add("Logging")
Pkg.add("Distributed")
Pkg.add("LightXML")
Pkg.add("ImageMagick")
Pkg.add("ArgParse")
Pkg.add("Printf")
Pkg.add("HTTP")
Pkg.add("FileIO")
Pkg.add("Images")
Pkg.add("ImageIO")
Pkg.add("CSV")
Pkg.add("DataFrames")
Pkg.add("DataFramesMeta")
Pkg.add("Serialization")
Pkg.add("IndexedTables")
Pkg.add("Geodesy")
Pkg.add("Parsers")
Pkg.add("Sockets")
Pkg.add("EzXML")
Pkg.add("ThreadSafeDicts")
Pkg.add("Logging")
# Sometimes this package has problems with other packages installed in Julia it is better to run this command:
## Pkg.build("CodecZlib")
# The installation of the packages is complete
println("\nThe Julia system has been updated")
end
catch err
println("\nProblems loading library modules, program execution will now be interrupted\nError: $err (exit code 500)")
ccall(:jl_exit, Cvoid, (Int32,), 500)
end
if restartIsRequestCauseUpgrade >= 2
println("\nThe Julia packeges and extra packeges has been updateds!\n\n\tNote: Sometimes, especially on Windows machines,\n\tafter the restart, there may be print some orrors messages,\n\tnormally there is no problem if you wait a few tens of seconds, if the system seems to stop,\n\tyou can give a CTRL-C and restart the program execution operation again.\n\tThe package management system will solve any problems in the next restart of the program.\n\nNow the program ends and a re-execution is requested (exit code 100)")
ccall(:jl_exit, Cvoid, (Int32,), 100)
end
end
# It is essential to insert this declaration to allow the sharing of the image arrays
@everywhere using SharedArrays
#@distributed using SharedArrays
try
include("./Commons.jl")
include("./TilesDatabase.jl")
include("./Connector.jl")
include("./Geodesics.jl")
include("./Route.jl")
catch err
println("\nError, a julia module file is missing\nCheck that the files are loaded in the same directory that contains the photoscenary.jl program.\n$err")
ccall(:jl_exit, Cvoid, (Int32,), 500)
end
# Inizialize section
function inizializeParams()
# Build the paramsXml
paramsXml = nothing
if isfile("params.xml")
paramsXml = parse_file("params.xml")
if "params" == lowercase(name(LightXML.root(paramsXml)))
xroot = LightXML.root(paramsXml)
ces = get_elements_by_tagname(xroot,"versioning")
if ces != nothing && find_element(ces[1],"version") != nothing
set_content(find_element(ces[1],"version"),versionProgram)
end
end
end
if (paramsXml == nothing)
paramsXml = parse_string("<params><versioning><version>$versionProgram</version><autor>Adriano Bassignana</autor><year>2021</year><licence>GPL 2</licence></versioning></params>")
end
save_file(paramsXml,"params.xml")
end
function inizialize()
versionFromParams = nothing
imageMagickPath = nothing
if isfile("params.xml")
paramsXml = parse_file("params.xml")
if "params" == lowercase(name(LightXML.root(paramsXml)))
xroot = LightXML.root(paramsXml)
ces = get_elements_by_tagname(xroot,"versioning")
if ces != nothing && size(ces)[1] > 0 && find_element(ces[1],"version") != nothing
versionFromParams = content(find_element(ces[1],"version"))
end
img = get_elements_by_tagname(xroot,"imageMagick")
if img != nothing && size(img)[1] > 0 && find_element(img[1],"path") != nothing
imageMagickPath = strip(content(find_element(img[1],"path")))
if length(imageMagickPath) == 0 imageMagickPath = nothing end
end
end
end
if versionFromParams == nothing || versionFromParams != versionProgram
println("\nThe program version is change old version is $versionFromParams the actual version is $versionProgram ($versionProgramDate)")
inizializeParams()
end
println('\n',"Photoscenery generator by Julia compilator,\nProgram for uploading Orthophotos files\n")
paramsXml = parse_file("params.xml")
if "params" == lowercase(name(LightXML.root(paramsXml)))
ces = get_elements_by_tagname(LightXML.root(paramsXml),"versioning")
end
return imageMagickPath
end
struct MapServer
id::Int64
webUrlBase::Union{String,Nothing}
webUrlCommand::Union{String,Nothing}
name::Union{String,Nothing}
comment::Union{String,Nothing}
proxy::Union{String,Nothing}
errorCode::Int64
function MapServer(id,aProxy=nothing)
try
serversRoot = get_elements_by_tagname(LightXML.root(parse_file("params.xml")),"servers")
servers = get_elements_by_tagname(serversRoot[1], "server")
for server in servers
if server!= nothing
if strip(content(find_element(server,"id"))) == string(id)
webUrlBase = strip(content(find_element(server,"url-base")))
webUrlCommand = map(c -> c == '|' ? '&' : c, strip(content(find_element(server,"url-command"))))
name = strip(content(find_element(server,"name")))
comment = strip(content(find_element(server,"comment")))
proxy = aProxy
return new(id,webUrlBase,webUrlCommand,name,comment,proxy,0)
end
end
end
return new(id,nothing,nothing,nothing,nothing,nothing,410)
catch err
return new(id,nothing,nothing,nothing,nothing,nothing,411)
end
end
end
struct MapCoordinates
lat::Float64
lon::Float64
radius::Float64
latLL::Float64
lonLL::Float64
latUR::Float64
lonUR::Float64
isDeclarePolar::Bool
positionRoute::Union{FGFSPositionRoute,Nothing}
function MapCoordinates(lat::Float64,lon::Float64,radius::Float64)
(latLL,lonLL,latUR,lonUR) = Commons.latDegByCentralPoint(lat,lon,radius)
return new(lat,lon,radius,latLL,lonLL,latUR,lonUR,true)
end
function MapCoordinates(latLL::Float64,lonLL::Float64,latUR::Float64,lonUR::Float64)
lon = lonLL + (lonUR - lonLL) / 2.0
lat = latLL + (latUR - latLL) / 2.0
lonDist = abs(lonUR - lonLL) / 2.0
latDist = abs(latUR - latLL) / 2.0
posLL = LLA(latLL,lonLL, 0.0)
posUR = LLA(latUR,lonUR, 0.0)
radius = round(euclidean_distance(posUR,posLL) / 1852.0,digits=2)
return new(lat,lon,radius,latLL,lonLL,latUR,lonUR,false)
end
end
function getSizePixel(size)
if size <= 0
sizeWidth = 512
cols = 1
elseif size <= 1
sizeWidth = 1024
cols = 1
elseif size <= 2
sizeWidth = 2048
cols = 1
elseif size <= 3
sizeWidth = 4096
cols = 2
elseif size <= 4
sizeWidth = 8192
cols = 4
elseif size <= 5
sizeWidth = 16384
cols = 8
else
sizeWidth = 32768
cols = 8
end
return sizeWidth, cols
end
function getSizePixelWidthByDistance(size,sizeDwn,radius,distance,positionRoute::Union{FGFSPositionRoute,Nothing},unCompletedTilesAttemps)
if sizeDwn > size sizeDwn = size end
if unCompletedTilesAttemps > 0
size = size - unCompletedTilesAttemps
if size > 2
size = 2
elseif size < 0
size = 0
end
sizeDwn = sizeDwn - unCompletedTilesAttemps
if sizeDwn > 2
sizeDwn = 2
elseif sizeDwn < 0
sizeDwn = 0
end
end
if positionRoute != nothing
positionRoute.actual == nothing ? altitudeNm = 0.0 : altitudeNm = positionRoute.actual.altitudeFt * 0.000164579
else
altitudeNm = 0.0
end
sizePixelFound = Int64(round(size - (size-sizeDwn) * sqrt(distance^2.0 + altitudeNm^2.0) * 1.0 / radius))
if sizePixelFound > size
return getSizePixel(size)
elseif sizePixelFound < sizeDwn
return getSizePixel(sizeDwn)
else
return getSizePixel(sizePixelFound)
end
end
# Coordinates matrix generator
function coordinateMatrixGenerator(m::MapCoordinates,whiteTileIndexListDict,size,sizeDwn,unCompletedTilesAttemps,positionRoute::Union{FGFSPositionRoute,Nothing},isDebug)
numberOfTiles = 0
# Normalization to 0.125 deg
latLL = m.latLL - mod(m.latLL,0.125)
latUR = m.latUR - mod(m.latUR,0.125) + 0.125
lonLL = m.lonLL - mod(m.lonLL,Commons.tileWidth(m.lat))
lonUR = m.lonUR - mod(m.lonUR,Commons.tileWidth(m.lat)) + Commons.tileWidth(m.lat)
a = [(
string(lon >= 0.0 ? "e" : "w", lon >= 0.0 ? @sprintf("%03d",floor(abs(lon),digits=-1)) : @sprintf("%03d",ceil(abs(lon),digits=-1)),
lat >= 0.0 ? "n" : "s", lat >= 0.0 ? @sprintf("%02d",floor(abs(lat),digits=-1)) : @sprintf("%02d",ceil(abs(lat),digits=-1))),
string(lon >= 0.0 ? "e" : "w", lon >= 0.0 ? @sprintf("%03d",floor(Int,abs(lon))) : @sprintf("%03d",ceil(Int,abs(lon))),
lat >= 0.0 ? "n" : "s", lat >= 0.0 ? @sprintf("%02d",floor(Int,abs(lat))) : @sprintf("%02d",ceil(Int,abs(lat)))),
lon,
lat,
lon + Commons.tileWidth(lat),
lat + 0.125,
floor(Int,lat*10),
Commons.index(lat,lon),
Commons.x(lat,lon),
Commons.y(lat),
Commons.tileWidth(lat),
round(euclidean_distance(LLA(lat + (0.125/2.0),lon + Commons.tileWidth(lat)/2.0,0.0),LLA(m.lat,m.lon, 0.0)) / 1852.0 / 2.0,digits=3)
)
for lat in latLL:0.125:latUR for lon in lonLL:Commons.tileWidth(lat):lonUR
]
# print data sort by tile index
aSort = sort!(a,by = x -> x[12])
c = nothing
d = []
precIndex = nothing
counterIndex = 0
for b in aSort
if whiteTileIndexListDict == nothing || (whiteTileIndexListDict != nothing && haskey(whiteTileIndexListDict,b[8]))
if precIndex == nothing || precIndex != b[8]
if c != nothing push!(d,c) end
c = []
precIndex = b[8]
counterIndex = 1
else
counterIndex += 1
end
(widthByDistance,colsByDistance) = getSizePixelWidthByDistance(size,sizeDwn,m.radius,b[12],positionRoute,unCompletedTilesAttemps)
t = (b[1],b[2],b[3],b[5],b[4],b[6],b[8],counterIndex,b[11],0,b[12],widthByDistance,colsByDistance)
push!(c,t)
push!(c,0)
numberOfTiles += 1
if isDebug > 0 println("Tile id: ",t[7]," coordinates: ",t[1]," ",t[2],
" | lon: ",@sprintf("%03.6f ",t[3]),
@sprintf("%03.6f ",t[4]),
"lat: ",@sprintf("%03.6f ",t[5]),
@sprintf("%03.6f ",t[6])," | Counter: ",t[8]," Width: ",@sprintf("%03.6f ",t[9]),
"dist: $(t[11]) size: $(t[12]) | $(t[13])") end
end
end
if c != nothing
push!(d,c)
end
if isDebug > 0
println("\n----------")
println("CoordinateMatrix generator")
println("latLL: ",latLL," lonLL ",lonLL," latUR: ",latUR," lonUR ",lonUR,'\n')
println("Number of tiles to process: $numberOfTiles")
println("----------\n")
end
return d,numberOfTiles
end
function getMapServerReplace(urlCmd,varString,varValue,errorCode)
a = replace(urlCmd,varString => string(round(varValue,digits=6)))
if a != urlCmd
return a, errorCode
else
println("\nError: getMapServerReplace params.xml has problems in the servers section\n\tthe map server with id $id has the $varString value not correct or defined\n\t$webUrlCommand")
return a, errorCode + 1
end
end
function getMapServer(m::MapServer,latLL,lonLL,latUR,lonUR,szWidth,szHight)
urlCmd = m.webUrlCommand
errorCode = m.errorCode
if errorCode == 0
urlCmd,errorCode = getMapServerReplace(urlCmd,"{latLL}",latLL,0)
urlCmd,errorCode = getMapServerReplace(urlCmd,"{lonLL}",lonLL,errorCode)
urlCmd,errorCode = getMapServerReplace(urlCmd,"{latUR}",latUR,errorCode)
urlCmd,errorCode = getMapServerReplace(urlCmd,"{lonUR}",lonUR,errorCode)
urlCmd,errorCode = getMapServerReplace(urlCmd,"{szWidth}",szWidth,errorCode)
urlCmd,errorCode = getMapServerReplace(urlCmd,"{szHight}",szHight,errorCode)
return m.webUrlBase * urlCmd, errorCode > 0 ? 413 : 0
else
return "", 412
end
end
#Testing image magick
function checkImageMagick(imageMagickPath)
imageMagickTest = nothing
if imageMagickPath != nothing
println("\ncheckImageMagick - is define a path for imageMagick: $imageMagickPath")
println("In the params.xml configuration file\n")
end
try
if Base.Sys.iswindows()
imageMagickStatus = run(`magick convert -version`)
else
imageMagickStatus = run(`convert -version`)
end
if imageMagickPath == nothing
imageMagickTest = 1
else
imageMagickPath = nothing
imageMagickTest = 2
end
catch err
try
if Base.Sys.iswindows()
imageMagickTest = 4
elseif imageMagickPath != nothing
imageMagickWithPathUnix = normpath(imageMagickPath * "/" * "convert")
imageMagickStatus = run(`$imageMagickWithPathUnix -version`)
imageMagickTest = 3
else
imageMagickTest = 4
end
imageMagickPath = nothing
println("checkImageMagick - ImageMagic is operative!")
catch err
imageMagickTest = 5
end
end
if imageMagickTest == 1
println("\nImageMagic is operative!")
return true,imageMagickPath
elseif imageMagickTest == 2
println("\nImageMagic is operative!")
if Base.Sys.iswindows() == false
println("The path is: $imageMagickPath")
println("This path is not necessary\nI recommend removing it by editing the file: 'params.xml'\ngetting this situation:")
println("<imageMagick>")
println(" <path></path>")
println("</imageMagick>")
end
return true,imageMagickPath
elseif imageMagickTest == 3
println("\nImageMagic is operative!")
println("The path is: $imageMagickPath")
return true,imageMagickPath
elseif imageMagickTest == 4
println("\nError: The program, named: 'imageMagick' for converting files into .dds format (Error code 504)\nbut has not been well installed!")
println("It has often been verified that ImageMagick on Windows should be installed\nonly after having previously uninstalled ImageMagick.")
println("When installing imageMagick make sure you have at least flegged the following options:")
println("#1 [x] Add application direcory to your system path")
println("#2 [x] Install legacy utilities (e.g. convert)")
println("\nNow this application is stopped waiting for these issues to be fixed")
println("It is therefore necessary to install the program ImageMagick the home page is: https://imagemagick.org/")
println("You can install the program at this link: https://imagemagick.org/script/download.php")
println("If you are with the Windows operating system, absolutely remember, once ImageMagick is installed, to restart the PC!")
return false,imageMagickPath
elseif imageMagickTest == 5
println("\nError: The program imageMagick with the path: $imageMagickPath")
println("was not found, check if the path was written correctly or 'imageMagick' is installed on your system.")
return false,imageMagickPath
end
end
function fileWithRootHomePath(fileName)
return normpath(homeProgramPath * "/" * fileName)
end
function setPath(root,pathLiv1,pathLiv2)
rootDirectoryIsOk = false
path = root * "/" * pathLiv1 * "/" * pathLiv2
try
rootDirFiles = mkpath(path)
rootDirectoryIsOk = true
return path
catch err
println("The $root directory is inexistent, the directory will be is created")
return nothing
end
end
# Analyze the quality of the image
# > 0 Image quality
# == 0 Image does not exist
# -1 Image error
# Note: The algorithm does not work for DDS type files
function imageQuality(image, debugLevel)
if isfile(image)
try
img = ImageView.load(image)
sizeImg = size(img)[1]*size(img)[2]
if debugLevel > 0 println("imageQuality - The file $image id downloaded the size is: $sizeImg") end
return sizeImg
catch err
if debugLevel > 1 println("Error: imageQuality - The file $image is not downloaded") end
return -2
end
else
if debugLevel > 1 println("Error: imageQuality - The file $image is not present") end
return -1
end
end
function downloadImage(xy,lonLL,latLL,ΔLat,ΔLon,szWidth,szHight,sizeHight,imageWithPathTypePNG,task,mapServer::MapServer,debugLevel)
x = xy[1]
y = xy[2]
imageMatrix = zeros(RGB{N0f8},szHight,szWidth)
loLL = lonLL + (x - 1) * ΔLon
loUR = lonLL + x * ΔLon
laLL = latLL + (y - 1) * ΔLat
laUR = latLL + y * ΔLat
t0 = time()
downloadPNGIsComplete = 0
(servicesWebUrl,errorCode) = getMapServer(mapServer,laLL,loLL,laUR,loUR,szWidth,szHight)
if errorCode > 0
return downloadPNGIsComplete,time()-t0,xy,imageMatrix
end
if debugLevel > 0 @warn "downloadImage - HTTP image start to download url: $servicesWebUrl" end
tryDownloadFileImagePNG = 1
while tryDownloadFileImagePNG <= 2 && downloadPNGIsComplete == 0
try
imageMatrix = Images.load(Images.download(servicesWebUrl))
if debugLevel > 0 println(" ") end
print("\rThe image in ",@sprintf("%03.3f,%03.3f,%03.3f,%03.3f",loLL,laLL,loUR,laUR)," load in the matrix: x = $x y = $y Task: $task th: $(Threads.threadid()) try: $tryDownloadFileImagePNG",@sprintf(" time: %3.2f",(time()-t0)))
downloadPNGIsComplete = 1
catch err
# Typical error type 500
if debugLevel > 1 @warn "Error: downloadImage #3 - load image $imageWithPathTypePNG generic error id: $err tryDownloadFileImagePNG: $tryDownloadFileImagePNG" end
tryDownloadFileImagePNG += 1
end
end
if debugLevel > 2 @warn "DownloadImage #5" end
return downloadPNGIsComplete,time()-t0,xy,imageMatrix
end
function downloadImages(tp,imageWithPathTypePNG,mapServer::MapServer,debugLevel)
lonLL = tp[3]
latLL = tp[5]
lonUR = tp[4]
latUR = tp[6]
cols = tp[13]
sizeWidth = tp[12]
sizeHight = Int(sizeWidth / (8 * Commons.tileWidth((latUR + latLL) / 2.0)))
if debugLevel > 2
println("downloadImages - tp: $tp mapServer: $(mapServer.webUrlBase)")
println("downloadImages - sizeHight: $sizeHight sizeWidth: $sizeWidth")
end
imageMatrix = SharedArray(zeros(RGB{N0f8},sizeHight,sizeWidth))
downloadPNGIsCompleteNumber = 0
szWidth = Int(sizeWidth / cols)
szHight = Int(sizeHight / cols)
ΔLat = (latUR - latLL) / cols
ΔLon = (lonUR - lonLL) / cols
indexValues = [(x,y) for x in 1:cols for y in 1:cols]
fs = Dict{Int,Any}()
@sync for task in 1:(cols*cols)
if debugLevel > 1 println("downloadImages - indexValues[$task]: indexValues[task]") end
@async fs[task] = downloadImage(indexValues[task],lonLL,latLL,ΔLat,ΔLon,szWidth,szHight,sizeHight,imageWithPathTypePNG,task,mapServer,debugLevel)
end
res = Dict{Int,Tuple{Int64, Float64, Tuple{Int64, Int64}, Matrix{RGB{N0f8}}}}()
@sync for task in 1:(cols*cols)
@async res[task] = fetch(fs[task])
end
for task in 1:(cols*cols)
x = res[task][3][1]
y = res[task][3][2]
imageMatrix[1 + sizeHight - (szHight * y):sizeHight - szHight * (y - 1),1 + szWidth * (x - 1):szWidth * x] = res[task][4]
downloadPNGIsCompleteNumber += res[task][1]
end
if downloadPNGIsCompleteNumber > 0
try
Images.save(imageWithPathTypePNG,imageMatrix)
if debugLevel > 0 println("downloadImage - The file $imageWithPathTypePNG is downloaded") end
catch
if debugLevel > 1 println("Error: downloadImage - to download the $imageWithPathTypePNG file, error id: ",err) end
if isfile(imageWithPathTypePNG) rm(imageWithPathTypePNG) end
end
else
if isfile(imageWithPathTypePNG) rm(imageWithPathTypePNG) end
end
return downloadPNGIsCompleteNumber
end
function createDDSorPNGFile(rootPath,tp,overWriteTheTiles,imageMagickPath,mapServer::MapServer,tileDatabase::IndexedTable,isPngFileFormatOnly,pathToSave,debugLevel)
theBatchIsNotCompleted = false
t0 = time()
timeElaboration = nothing
theDDSorPNGFileIsOk = 0
tileIndex = 0
fileSizePNG = 0
fileSizeDDS = 0
format = isPngFileFormatOnly ? 0 : 1
isfileImagePNG = false
path = setPath(rootPath,tp[1],tp[2])
if debugLevel > 2
println("createDDSorPNGFile - tp: $tp path: $path overWriteTheTiles: $overWriteTheTiles imageMagickPath: $imageMagickPath")
println("createDDSorPNGFile - mapServer $mapServer isPngFileFormatOnly: $isPngFileFormatOnly pathToSave: $pathToSave")
end
if path != nothing
createDDSorPNGFile = false
tileIndex = tp[7]
imageWithPathTypePNG = normpath(path * "/" * string(tileIndex) * ".png")
imageWithPathTypeDDS = normpath(path * "/" * string(tileIndex) * ".dds")
# Check the image is present
if isPngFileFormatOnly
if isfile(imageWithPathTypeDDS) TilesDatabase.moveOrDeleteTiles(tileIndex,rootPath,1,pathToSave) end
dataFileImagePNG = getPNGSize(imageWithPathTypePNG)
if dataFileImagePNG[1]
if overWriteTheTiles >= 9
TilesDatabase.moveOrDeleteTiles(tileIndex,rootPath,0,pathToSave)
theDDSorPNGFileIsOk = -1
elseif overWriteTheTiles == 2 || dataFileImagePNG[2] < 512 || dataFileImagePNG[2] > 32768
createDDSorPNGFile = true
TilesDatabase.moveOrDeleteTiles(tileIndex,rootPath,0,pathToSave)
elseif overWriteTheTiles == 1 && tp[12] > dataFileImagePNG[2]
createDDSorPNGFile = true
else
theDDSorPNGFileIsOk = -3
end
else
if isfile(imageWithPathTypePNG) TilesDatabase.moveOrDeleteTiles(tileIndex,rootPath,0,pathToSave) end
if overWriteTheTiles < 9
createDDSorPNGFile = true
else
theDDSorPNGFileIsOk = -2
end
end
else
dataFileImageDDS = Commons.getDDSSize(imageWithPathTypeDDS)
dataFileImagePNG = Commons.getPNGSize(imageWithPathTypePNG)
if dataFileImageDDS[1]
if overWriteTheTiles >= 9
TilesDatabase.moveOrDeleteTiles(tileIndex,rootPath,1,pathToSave)
theDDSorPNGFileIsOk = -1
elseif overWriteTheTiles == 2 || dataFileImageDDS[2] < 512 || dataFileImageDDS[2] > 32768
createDDSorPNGFile = true
elseif overWriteTheTiles == 1 && tp[12] > dataFileImageDDS[2]
createDDSorPNGFile = true
else
theDDSorPNGFileIsOk = -3
end
else
if dataFileImagePNG[1]
if overWriteTheTiles >= 9
TilesDatabase.moveOrDeleteTiles(tileIndex,rootPath,0,pathToSave)
theDDSorPNGFileIsOk = -1
elseif overWriteTheTiles == 2 || dataFileImagePNG[2] < 512 || dataFileImagePNG[2] > 32768
isfileImagePNG = false
TilesDatabase.moveOrDeleteTiles(tileIndex,rootPath,0,pathToSave)
createDDSorPNGFile = true
elseif overWriteTheTiles == 1 && tp[12] >= dataFileImagePNG[2]
isfileImagePNG = true
createDDSorPNGFile = true
else
isfileImagePNG = false
TilesDatabase.moveOrDeleteTiles(tileIndex,rootPath,0,pathToSave)
createDDSorPNGFile = true
end
else
if isfile(imageWithPathTypeDDS) TilesDatabase.moveOrDeleteTiles(tileIndex,rootPath,1,pathToSave) end
if overWriteTheTiles < 9
createDDSorPNGFile = true
else
theDDSorPNGFileIsOk = -2
end
end
end
end
if createDDSorPNGFile
# Check if there is a file somewhere that could be used as DDS
dataFound::Union{Tuple{Int64,String,String,Bool},Nothing} = nothing
if !isfileImagePNG
TilesDatabase.moveOrDeleteTiles(tileIndex,rootPath,1,pathToSave)
if debugLevel > 2 println("createDDSorPNGFile - tileIndex: $tileIndex") end
dataFound = TilesDatabase.copyTilesByIndex(tileDatabase,tileIndex,tp[12],rootPath,format)
if debugLevel > 2 println("createDDSorPNGFile - dataFound: $dataFound") end
end
if debugLevel > 2 println("createDDSorPNGFile - dataFound (2): $dataFound") end
if dataFound != nothing
theBatchIsNotCompleted = false
dataFound[4] ? theDDSorPNGFileIsOk = -3 : theDDSorPNGFileIsOk = 3
if format == 0
fileSizePNG = stat(imageWithPathTypePNG).size
fileSizeDDS = 0
else
fileSizePNG = 0
fileSizeDDS = stat(imageWithPathTypeDDS).size
end
timeElaboration = time() - t0
else
if debugLevel > 0 println("createDDSorPNGFile $isfileImagePNG $tileIndex $rootPath $pathToSave") end
# The DDS or PNG file was not found, so it must be obtained from an external site
if !isfileImagePNG
TilesDatabase.moveOrDeleteTiles(tileIndex,rootPath,0,pathToSave)
TilesDatabase.moveOrDeleteTiles(tileIndex,rootPath,1,pathToSave)
# downloadImages section from map server
isfileImagePNG = downloadImages(tp,imageWithPathTypePNG,mapServer,debugLevel) > 0
end
if isPngFileFormatOnly
if isfileImagePNG > 0 && filesize(imageWithPathTypePNG) > 1024
try
fileSizePNG = stat(imageWithPathTypePNG).size
fileSizeDDS = 0
if debugLevel > 0 println("createDDSorPNGFile - The file $imageWithPathTypePNG is created") end
theBatchIsNotCompleted = false
theDDSorPNGFileIsOk = 1
timeElaboration = time() - t0
catch err
if debugLevel > 1 println("createDDSorPNGFile - Error to create $imageWithPathTypePNG file in png format") end
try
rm(imageWithPathTypePNG)
catch
if debugLevel > 1 println("createDDSorPNGFile - Error to remove the $imageWithPathTypePNG file") end
end
theBatchIsNotCompleted = true
if theDDSorPNGFileIsOk == 0 theDDSorPNGFileIsOk = -10 end
end
else
theBatchIsNotCompleted = true
if theDDSorPNGFileIsOk == 0 theDDSorPNGFileIsOk = -11 end
end
else
if isfileImagePNG > 0 && filesize(imageWithPathTypePNG) > 1024
# Conversion from .png to .dds
try
# Original version: -define dds:compression=DXT5 dxt5:$imageWithPathTypeDDS
# Compression factor (16K -> 64 MB): -define dds:mipmaps=0 -define dds:compression=dxt1
# Compression factor (16K -> 128 MB): -define dds:mipmaps=0 -define dds:compression=dxt5
oldFileIsPresent = isfile(imageWithPathTypeDDS)
TilesDatabase.moveOrDeleteTiles(tileIndex,rootPath,1,pathToSave)
fileSizePNG = stat(imageWithPathTypePNG).size
if Base.Sys.iswindows()
run(`magick convert $imageWithPathTypePNG -define dds:mipmaps=0 -define dds:compression=dxt1 $imageWithPathTypeDDS`)
else
imageMagickPath != nothing ? imageMagickWithPathUnix = normpath(imageMagickPath * "/" * "convert") : imageMagickWithPathUnix = "convert"
run(`$imageMagickWithPathUnix $imageWithPathTypePNG -define dds:mipmaps=0 -define dds:compression=dxt1 $imageWithPathTypeDDS`)
end
fileSizeDDS = stat(imageWithPathTypeDDS).size
if debugLevel > 0 println("createDDSorPNGFile - The file $imageWithPathTypeDDS is converted in the DDS file: $imageWithPathTypeDDS") end
rm(imageWithPathTypePNG)
theBatchIsNotCompleted = false
oldFileIsPresent ? theDDSorPNGFileIsOk = 2 : theDDSorPNGFileIsOk = 1
timeElaboration = time() - t0
catch err
if debugLevel > 1 println("createDDSorPNGFile - Error to convert the $imageWithPathTypePNG file in dds format") end
try
rm(imageWithPathTypePNG)
catch
if debugLevel > 1 println("createDDSorPNGFile - Error to remove the $imageWithPathTypePNG file") end
end
theBatchIsNotCompleted = true
if theDDSorPNGFileIsOk == 0 theDDSorPNGFileIsOk = -10 end
end
else
theBatchIsNotCompleted = true
if theDDSorPNGFileIsOk == 0 theDDSorPNGFileIsOk = -11 end
end
end
end
else
if theDDSorPNGFileIsOk == 0 theDDSorPNGFileIsOk = -12 end
end
end
return theBatchIsNotCompleted, tileIndex, theDDSorPNGFileIsOk, timeElaboration, string(tp[7]) * (format == 0 ? ".png" : ".dds"),"../" * tp[1] * "/" * tp[2], fileSizePNG, fileSizeDDS
end
# Main fuctions area
function parseCommandline(args)
if args != nothing && size(args)[1] == 1
try
outfile = args[1]
f = open(outfile,"r")
args = String[]
while ! eof(f)
line = readline(f)
if length(line) > 0 push!(args,line) end
end
parsed_args = parse_args(args,s)
println("\nArguments (params) read from the file: $outfile")
catch
end
end
s = ArgParseSettings()
@add_arg_table! s begin
"--args", "-g"
help = "The arguments files in txt format"
arg_type = String
default = nothing
"--map"
help = "The map server id"
arg_type = Int64
default = 1
"--latll"
help = "Lower left area lat"
arg_type = Float64
default = 0.0
"--lonll"
help = "Lower left area lon"
arg_type = Float64
default = 0.0
"--latur"
help = "Upper right area lat"
arg_type = Float64
default = 0.0
"--lonur"
help = "Upper right area lon"
arg_type = Float64
default = 0.0
"--lat", "-a"
help = "Latitude in deg of central point"
arg_type = Float64
default = nothing
"--lon", "-o"
help = "Longitude in deg of central point"
arg_type = Float64
default = nothing
"--sexagesimal", "-x"
help = "Set the sexagesimal unit degree.minutes"
action = :store_true
"--png"
help = "Set the only png format files"
action = :store_true
"--icao", "-i"
help = "ICAO airport code for extract LAT and LON"
arg_type = String
default = nothing
"--route"
help = "Route XML for extract route LAT and LON"
arg_type = String
default = nothing
"--tile", "-t"
help = "Tile index es coordinate reference"
arg_type = Int64
default = nothing
"--radius", "-r"
help = "Distance Radius around the center point (nm)"
arg_type = Float64
default = 0.0
"--size", "-s"
help = "Max size of image 0->512 1->1024 2->2048 3->4096 4->8192 5->16384 6->32768"
arg_type = Int64
default = 2
"--sdwn"
help = "Down size with distance"
arg_type = Int64
default = 0
"--over"
help = "Overwrite the tiles: |1|only if bigger resolution |2|for all"
arg_type = Int64
default = 0
"--search"
help = "Search the DDS or PNG files in the specific path"
arg_type = String
default = nothing
"--path", "-p"
help = "Path to store the dds images"
arg_type = String
default = nothing
"--save"
help = "Save the remove files in the specific path"
arg_type = String
default = nothing
"--nosave"
help = "Not save the DDS/PNG files"
action = :store_true
"--connect"
help = "IP and port FGFS program, default value and format: \"127.0.0.1:5000\""
arg_type = String
default = nothing
"--proxy"
help = "Proxy string ipv4:port for example: \"192.168.0.1:8080\""
default = nothing
"--attemps"
help = "Number of download attempts"
arg_type = Int64
default = 3
"--debug", "-d"
help = "Debug level"
arg_type = Int64
default = 0
"--version"
help = "Program version"
action = :store_true
end
parsed_args = parse_args(args,s)
outfile = parsed_args["args"]
if size(args)[1] == 0 || (size(args)[1] == 2 && outfile != nothing)
try
if outfile == nothing outfile = "args.txt" end
f = open(outfile,"r")
args = String[]
while ! eof(f)
line = readline(f)
if length(line) > 0 push!(args,line) end
end
parsed_args = parse_args(args,s)
println("\nArguments (params) read from the file: $outfile")
catch err
println("\nError to load arguments (params) put the default arguments\nerr: $err")
end
else
try
if outfile == nothing
outfile = "args.txt"
f = open(outfile, "w")
for i in eachindex(args)
println(f, args[i])
end
println("\nArguments (params) saved in the file: $outfile")
end
catch
end
end
for pa in parsed_args
println(" $(pa[1]) => $(pa[2])")
end
return parsed_args
end