Exemplo n.º 1
0
        public void Execute()
        {
            var activityLogger = new ConsoleActivityLogger {
                LogLevel = ActivityLogLevel.Verbose
            };

            // Use all available encryption protocols supported in the .NET Framework 4.0.
            // TLS versions > 1.0 are supported and available via the extensions.
            // see https://blogs.perficient.com/microsoft/2016/04/tsl-1-2-and-net-support/
            // This is a global setting for all HTTP requests.
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolTypeExtensions.Tls11 |
                                                   SecurityProtocolTypeExtensions.Tls12 | SecurityProtocolType.Ssl3;

            // first make sure that the SRTM directory exists
            if (!Directory.Exists(_srtmDir))
            {
                Directory.CreateDirectory(_srtmDir);
            }

            var       srtmIndexFilename = Path.Combine(_srtmDir, "SrtmIndex.dat");
            SrtmIndex srtmIndex         = null;

            SrtmIndex.SrtmSource = _srtmSource;

            try {
                srtmIndex = SrtmIndex.Load(srtmIndexFilename);
            }
            catch (Exception) {
                // in case of exception, regenerate the index
                _generateIndex = true;
            }

            if (_generateIndex)
            {
                srtmIndex = new SrtmIndex {
                    ActivityLogger = activityLogger
                };
                srtmIndex.Generate();
                srtmIndex.Save(srtmIndexFilename);

                srtmIndex = SrtmIndex.Load(srtmIndexFilename);
            }

            Srtm3Storage.SrtmSource = _srtmSource;
            var storage = new Srtm3Storage(Path.Combine(_srtmDir, "SrtmCache"), srtmIndex)
            {
                ActivityLogger = activityLogger
            };
            var peaks = new List <PointOfInterest>();

            foreach (var bound in _bounds)
            {
                var corrBounds = new Bounds2(bound.MinX - _corrX, bound.MinY - _corrY,
                                             bound.MaxX - _corrX, bound.MaxY - _corrY);

                activityLogger.LogFormat(ActivityLogLevel.Normal, "Calculating contour data for bound {0}...", corrBounds);

                var dem = (IRasterDigitalElevationModel)storage?.LoadDemForArea(corrBounds);
                peaks.AddRange(ElevationAnalyzer.FindPeaks(dem, _howMany));

                // clear up some memory used in storage object
                if (_bounds.Count == 1)
                {
                    storage = null;
                    GC.Collect();
                }

                var statistics = dem?.CalculateStatistics();

                activityLogger.Log(ActivityLogLevel.Normal, string.Format(CultureInfo.InvariantCulture,
                                                                          "DEM data points count: {0}", dem?.DataPointsCount));
                activityLogger.Log(ActivityLogLevel.Normal, string.Format(CultureInfo.InvariantCulture,
                                                                          "DEM minimum elevation: {0}", statistics?.MinElevation));
                activityLogger.Log(ActivityLogLevel.Normal, string.Format(CultureInfo.InvariantCulture,
                                                                          "DEM maximum elevation: {0}", statistics?.MaxElevation));
                activityLogger.Log(ActivityLogLevel.Normal, string.Format(CultureInfo.InvariantCulture,
                                                                          "DEM has missing points: {0}", statistics?.HasMissingPoints));
            }


            activityLogger.Log(ActivityLogLevel.Normal, "Saving Peaks to file...");
            using (var fs = new FileStream(_outputKmlFile, FileMode.Create, FileAccess.Write))
                using (var sw = new StreamWriter(fs)) {
                    sw.WriteLine(
                        "<?xml version=\"1.0\" encoding=\"utf-8\"?> <kml xmlns=\"http://earth.google.com/kml/2.2\" ><Document>");
                    foreach (var peak in peaks)
                    {
                        sw.WriteLine("<Placemark><name>{0}</name><Point><coordinates>{1},{2}</coordinates></Point></Placemark>",
                                     peak.Text, peak.Position.Longitude.ToString(CultureInfo.InvariantCulture).Replace(',', '.'),
                                     peak.Position.Latitude.ToString(CultureInfo.InvariantCulture).Replace(',', '.'));
                    }

                    sw.WriteLine("</Document></kml>");
                }


            activityLogger.Log(ActivityLogLevel.Normal, "Done.");
        }
Exemplo n.º 2
0
        public void Execute()
        {
            ConsoleActivityLogger activityLogger = new ConsoleActivityLogger();

            activityLogger.LogLevel = ActivityLogLevel.Verbose;

            // Use all available encryption protocols supported in the .NET Framework 4.0.
            // TLS versions > 1.0 are supported and available via the extensions.
            // see https://blogs.perficient.com/microsoft/2016/04/tsl-1-2-and-net-support/
            // This is a global setting for all HTTP requests.
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolTypeExtensions.Tls11 | SecurityProtocolTypeExtensions.Tls12 | SecurityProtocolType.Ssl3;

            // first make sure that the SRTM directory exists
            if (!Directory.Exists(srtmDir))
            {
                Directory.CreateDirectory(srtmDir);
            }

            string    srtmIndexFilename = Path.Combine(srtmDir, "SrtmIndex.dat");
            SrtmIndex srtmIndex         = null;

            SrtmIndex.SrtmSource = srtmSource;

            try
            {
                srtmIndex = SrtmIndex.Load(srtmIndexFilename);
            }
            catch (Exception)
            {
                // in case of exception, regenerate the index
                generateIndex = true;
            }

            if (generateIndex)
            {
                srtmIndex = new SrtmIndex();
                srtmIndex.ActivityLogger = activityLogger;
                srtmIndex.Generate();
                srtmIndex.Save(srtmIndexFilename);

                srtmIndex = SrtmIndex.Load(srtmIndexFilename);
            }

            Srtm3Storage.SrtmSource = srtmSource;
            Srtm3Storage storage = new Srtm3Storage(Path.Combine(srtmDir, "SrtmCache"), srtmIndex);

            storage.ActivityLogger = activityLogger;

            IIsopletingAlgorithm alg = new Igor4IsopletingAlgorithm();

            alg.ActivityLogger = activityLogger;

            double elevationStepInUnits = elevationStep * elevationUnits;

            contourMarker.Configure(elevationUnits);

            // Default: Start with highest possible ID and count down. That should give maximum space
            // between contour data and real OSM data.
            IdCounter nodeCounter = new IdCounter(incrementId, firstNodeId);
            IdCounter wayCounter  = new IdCounter(incrementId, firstWayId);

            OutputSettings settings = new OutputSettings();

            settings.ContourMarker       = contourMarker;
            settings.LongitudeCorrection = corrX;
            settings.LatitudeCorrection  = corrY;
            settings.MaxWayNodes         = maxWayNodes;

            // The following IDs and name do exist in the OSM database.
            settings.UserName    = "******";
            settings.UserId      = 941874;
            settings.ChangesetId = 13341398;

            OutputBase output = null;

            if (largeAreaMode)
            {
                output = new DirectOutput(new FileInfo(outputOsmFile), settings);
            }
            else
            {
                output = new DatabaseOutput(new FileInfo(outputOsmFile), settings);
            }

            output.Begin();

            if (osmMergeFile != null)
            {
                activityLogger.LogFormat(ActivityLogLevel.Normal, "Importing dataset from {0}", osmMergeFile);
                output.Merge(osmMergeFile);
            }

            if (this.splitWidth != 0 && this.splitHeight != 0)
            {
                List <Bounds2> newBounds = new List <Bounds2> ();

                foreach (Bounds2 bound in this.bounds)
                {
                    newBounds.AddRange(BoundsSplitter.Split(bound, this.splitWidth, this.splitHeight));
                }

                this.bounds = newBounds;

                activityLogger.LogFormat(ActivityLogLevel.Normal, "Will process {0} seperate bounds.", bounds.Count);
            }

            foreach (Bounds2 bound in this.bounds)
            {
                Bounds2 corrBounds = new Bounds2(bound.MinX - corrX, bound.MinY - corrY,
                                                 bound.MaxX - corrX, bound.MaxY - corrY);

                activityLogger.LogFormat(ActivityLogLevel.Normal, "Calculating contour data for bound {0}...", corrBounds);

                IRasterDigitalElevationModel dem = (IRasterDigitalElevationModel)storage.LoadDemForArea(corrBounds);

                // clear up some memory used in storage object
                if (this.bounds.Count == 1)
                {
                    storage = null;
                    GC.Collect();
                }

                DigitalElevationModelStatistics statistics = dem.CalculateStatistics();

                activityLogger.Log(ActivityLogLevel.Normal, String.Format(CultureInfo.InvariantCulture,
                                                                          "DEM data points count: {0}", dem.DataPointsCount));
                activityLogger.Log(ActivityLogLevel.Normal, String.Format(CultureInfo.InvariantCulture,
                                                                          "DEM minimum elevation: {0}", statistics.MinElevation));
                activityLogger.Log(ActivityLogLevel.Normal, String.Format(CultureInfo.InvariantCulture,
                                                                          "DEM maximum elevation: {0}", statistics.MaxElevation));
                activityLogger.Log(ActivityLogLevel.Normal, String.Format(CultureInfo.InvariantCulture,
                                                                          "DEM has missing points: {0}", statistics.HasMissingPoints));

                try
                {
                    alg.Isoplete(dem, elevationStepInUnits, delegate(Isohypse isohypse)
                    {
                        output.ProcessIsohypse(isohypse, delegate() { return(GetNextId(nodeCounter, true)); },
                                               delegate() { return(GetNextId(wayCounter, false)); });
                    });
                }
                catch (OutOfMemoryException)
                {
                    string msg = "Not enough memory. ";
                    if (this.splitWidth == 0 && this.splitHeight == 0)
                    {
                        msg += "Try to decrease the bounding box or use the splitbounds parameter.";
                    }
                    else
                    {
                        msg += "Try to decrease the splitbounds value.";
                    }

                    activityLogger.Log(ActivityLogLevel.Error, msg);
                    break;
                }
            }

            if (!largeAreaMode)
            {
                activityLogger.Log(ActivityLogLevel.Normal, "Saving contour data to file...");
            }

            output.End();

            activityLogger.Log(ActivityLogLevel.Normal, "Done.");

            // TODO: SVG file generator code

            //            using (FileStream stream = File.Open ("test.svg", FileMode.Create, FileAccess.Write))
            //            {
            //                using (StreamWriter writer = new StreamWriter (stream))
            //                {
            //                    int width = 1000;
            //                    int height = 800;
            //                    double aspectRatio = (maxLat - minLat) / height;
            //                    aspectRatio = Math.Max (aspectRatio, (maxLng - minLng) / width);

            //                    writer.WriteLine (String.Format (System.Globalization.CultureInfo.InvariantCulture,
            //                        @"<?xml version='1.0' encoding='utf-8' standalone='yes'?>
            //<!DOCTYPE svg[]>
            //<svg viewBox='{0} {1} {2} {3}' width='{2}' height='{3}' id='0'>", 0, 0, width, height));

            //                    foreach (Isohypse isohypse in isoCollection.Isohypses.Values)
            //                    {
            //                        foreach (Polyline polyline in isohypse.Segments)
            //                        {
            //                            StringBuilder pathString = new StringBuilder ();
            //                            for (int i = 0; i < polyline.VerticesCount; i++)
            //                            {
            //                                Point3 point = polyline.Vertices[i];

            //                                if (i == 0)
            //                                {
            //                                    pathString.AppendFormat ("M ");
            //                                }
            //                                else if (i == 1)
            //                                {
            //                                    pathString.AppendFormat ("C ");
            //                                }

            //                                pathString.AppendFormat (System.Globalization.CultureInfo.InvariantCulture, "{0},{1} ",
            //                                    (point.X - minLng) / aspectRatio, (maxLat - point.Y) / aspectRatio);

            //                                if (i > 0)
            //                                    pathString.AppendFormat (System.Globalization.CultureInfo.InvariantCulture, "{0},{1} ",
            //                                        (point.X - minLng) / aspectRatio, (maxLat - point.Y) / aspectRatio);
            //                            }

            //                            writer.WriteLine (@"<path d='{0}' fill='none' stroke='black' stroke-width='0.25px'/>", pathString.ToString ());
            //                        }
            //                    }

            //                    writer.WriteLine (@"</svg>");
            //                }
            //            }
        }