From a8028c5fe78d8e9a05f171407ac129c4fbd65e87 Mon Sep 17 00:00:00 2001 From: 13693261870 <252740454@qq.com> Date: 星期三, 24 七月 2024 16:47:01 +0800 Subject: [PATCH] 1 --- SimuTools/Tools/Handle.cs | 479 +++++++++++++++++++++++++++++++++++++---------------------- 1 files changed, 297 insertions(+), 182 deletions(-) diff --git a/SimuTools/Tools/Handle.cs b/SimuTools/Tools/Handle.cs index b0dff5d..a7a4aa6 100644 --- a/SimuTools/Tools/Handle.cs +++ b/SimuTools/Tools/Handle.cs @@ -15,11 +15,19 @@ { public class Handle { + #region 鎴愬憳鍙橀噺 public static readonly int MAX = 256 * 256; - public static readonly string GdalPath = ConfigurationManager.AppSettings["gdalPath"]; + public static readonly double MAX_X_OFFSET = 0.002; + + public static readonly double MIN_X_OFFSET = -0.00005; + + public static readonly double WaterHeightOffset = 1.0; public static readonly string BaseDir = AppDomain.CurrentDomain.BaseDirectory; + + public static readonly string GdalPath = ConfigurationManager.AppSettings["gdalPath"]; + #endregion /// <summary> /// 杩愯 @@ -55,7 +63,7 @@ if (null == ds || 0 == ds.RasterCount || null == ds.GetSpatialRef()) return; SetTerrainInfo(ds, layer); - //CreateTerrainPng(ds, layer, outPath); + CreateTerrainPng(ds, layer, outPath); } finally { @@ -68,14 +76,37 @@ /// </summary> private static void SetTerrainInfo(Dataset ds, Domain.Layer layer) { + //String srsName = ds.GetSpatialRef().GetName(); + //layer.terrain.epsg = !string.IsNullOrEmpty(srsName) && srsName.Contains(GdalHelper.CGCS2000) ? "EPSG:4490" : "EPSG:4326"; + Geometry minPoint = GdalHelper.GetMinPoint(ds); Geometry maxPoint = GdalHelper.GetMaxPoint(ds); - layer.extension = new Extension(minPoint.GetX(0), minPoint.GetY(0), maxPoint.GetX(0), maxPoint.GetY(0)); + double minx = GetMinVal(minPoint.GetX(0), 10000000); + double miny = GetMinVal(minPoint.GetY(0), 10000000); + double maxx = GetMaxVal(maxPoint.GetX(0) + MAX_X_OFFSET, 10000000); + double maxy = GetMaxVal(maxPoint.GetY(0), 10000000); + layer.extension = new Extension(minx, miny, maxx, maxy, double.MaxValue, double.MinValue); - OSGeo.GDAL.Band band = ds.GetRasterBand(1); + Band band = ds.GetRasterBand(1); double[] mm = new double[2]; band.ComputeRasterMinMax(mm, 0); - layer.extension.SetHeight(mm[0], mm[1]); + layer.terrain.SetHeight(GetMinVal(mm[0]), GetMaxVal(mm[1])); + } + + /// <summary> + /// 鑾峰彇鏈�灏忓�� + /// </summary> + private static double GetMinVal(double val, double radix = 1000) + { + return Convert.ToInt32(Math.Floor(val * radix)) / radix; + } + + /// <summary> + /// 鑾峰彇鏈�澶у�� + /// </summary> + private static double GetMaxVal(double val, double radix = 1000) + { + return Convert.ToInt32(Math.Ceiling(val * radix)) / radix; } /// <summary> @@ -92,36 +123,30 @@ { string tif = Path.Combine(tempPath, DateTime.Now.Ticks.ToString() + ".tif"); //Resample(ds.GetDescription(), tif, sizes[0], sizes[1]); - Resample(ds, tif, sizes[0], sizes[1]); - if (!File.Exists(tif)) - { - continue; - } + Resample(ds, tif, sizes[0], sizes[1], layer); + if (!File.Exists(tif)) continue; string png = Path.Combine(terrainPath, sizes[0] + "_" + sizes[1] + ".png"); - Tif2Png(layer, tif, png, sizes[0], sizes[1]); + Terrain2Png(layer, tif, png, sizes[0], sizes[1]); } } /// <summary> /// 閲嶉噰鏍� /// </summary> - private static void Resample(Dataset ds, string dest, int width, int height) + private static void Resample(Dataset ds, string dest, int width, int height, Domain.Layer layer) { // https://blog.51cto.com/u_16099346/6691820 //string args = string.Format("-t_srs {0} -ts {1} {2} -r {3} -of {4}", "EPSG:4326", width, height, "bilinear", "GTiff"); //string[] options = Gdal.ParseCommandLine(args); string[] options = new string[] { - "-t_srs", - "EPSG:4326", - "-ts", - width.ToString(), - height.ToString(), - "-r", - "bilinear", - "-of", - "GTiff" + "-t_srs", "EPSG:4326", // layer.terrain.epsg, + "-ts", width.ToString(), height.ToString(), + "-te", layer.extension.minx.ToString(), layer.extension.miny.ToString(), layer.extension.maxx.ToString(), layer.extension.maxy.ToString(), + "-te_srs", "EPSG:4326", // layer.terrain.epsg, + "-r", "bilinear", + "-of", "GTiff" }; GDALWarpAppOptions warpAppOptions = new GDALWarpAppOptions(options); @@ -130,60 +155,9 @@ } /// <summary> - /// 閲嶉噰鏍� * + /// 鍦板舰杞琍NG /// </summary> - private static void Resample(string source, string dest, int width, int height) - { - // https://blog.51cto.com/u_16099346/6691820 - string cmd = string.Format("{0}gdalwarp.exe -t_srs {1} -ts {2} {3} -r {4} -of GTiff \"{5}\" \"{6}\"", GdalPath, "EPSG:4326", width, height, "bilinear", source, dest); - string err = ExecExe(cmd); - } - - /// <summary> - /// 鎵ц鍛戒护 - /// </summary> - public static string ExecExe(string cmd) - { - string str = null; - Process p = null; - try - { - p = new Process(); - p.StartInfo.FileName = "cmd.exe"; - p.StartInfo.UseShellExecute = false; - p.StartInfo.CreateNoWindow = true; - p.StartInfo.RedirectStandardInput = true; - p.StartInfo.RedirectStandardOutput = true; - p.StartInfo.RedirectStandardError = true; - p.Start(); - - StreamWriter si = p.StandardInput; - StreamReader se = p.StandardError; - - si.AutoFlush = true; - si.WriteLine(cmd); - si.WriteLine("exit"); - - str = se.ReadToEnd(); - se.Close(); - si.Close(); - } - catch (Exception ex) - { - LogOut.Error(ex.Message + "\r\n" + ex.StackTrace); - str = ex.Message; - } - finally - { - if (p != null) p.Close(); - } - return str; - } - - /// <summary> - /// Tif鍊艰浆瀛樿嚦Png - /// </summary> - private static void Tif2Png(Domain.Layer layer, string tif, string png, int width, int height, int heightOffset = 0) + private static void Terrain2Png(Domain.Layer layer, string tif, string png, int width, int height) { Dataset ds = null; try @@ -199,7 +173,8 @@ Graphics graphic = Graphics.FromImage(image); graphic.Clear(Color.Transparent); // 濉厖閫忔槑鑹� - double perHeight = (layer.extension.maxHeight - layer.extension.minHeight + heightOffset) * 100 / 65536; + //double perHeight = (layer.terrain.maxHeight - layer.terrain.minHeight) * 100 / 65536; + double differ = layer.terrain.maxHeight - layer.terrain.minHeight; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) @@ -207,10 +182,10 @@ int offset = x + y * width; if (float.IsNaN(buffer[offset]) || buffer[offset] < -999) continue; - //int val = Convert.ToInt32(buffer[offset] * 100); - int val = Convert.ToInt32((buffer[offset] - layer.extension.minHeight + heightOffset) * 100 / perHeight); - int r = val / 65536; - int g = (val - r * 65536) / 256; + //int val = Convert.ToInt32((buffer[offset] - layer.terrain.minHeight) * 100 / perHeight); + int val = Convert.ToInt32((buffer[offset] - layer.terrain.minHeight) / differ * 65536); + int r = 0; + int g = val / 256; int b = val % 256; Color color = Color.FromArgb(127, r, g, b); @@ -222,7 +197,7 @@ finally { if (null != ds) ds.Dispose(); - if (File.Exists(tif)) File.Delete(tif); + //if (File.Exists(tif)) File.Delete(tif); } } #endregion @@ -237,71 +212,10 @@ if (null == files || files.Count == 0) return; SetWaterData(layer, files); + SetWaterHeight(layer, files); if (files.Count != layer.waters.data.Count) return; - //ProcessWaters(files, outPath, layer); - } - - /// <summary> - /// 澶勭悊姘撮潰鏁版嵁 - /// </summary> - private static void ProcessWaters(List<string> files, string outPath, Domain.Layer layer) - { - /*for (int i = 0, c = files.Count; i < c; i++) - { - Dataset ds = null; - try - { - ds = Gdal.Open(files[i], Access.GA_ReadOnly); - if (null == ds || 0 == ds.RasterCount || null == ds.GetSpatialRef()) continue; - - CreateWaterPng(ds, layer, outPath, layer.waters.data[i]); - } - finally - { - if (null != ds) ds.Dispose(); - } - }*/ - Parallel.For(0, files.Count, i => - { - Dataset ds = null; - try - { - ds = Gdal.Open(files[i], Access.GA_ReadOnly); - if (null == ds || 0 == ds.RasterCount || null == ds.GetSpatialRef()) return; - - CreateWaterPng(ds, layer, outPath, layer.waters.data[i]); - } - finally - { - if (null != ds) ds.Dispose(); - } - }); - } - - /// <summary> - /// 鍒涘缓姘撮潰PNG - /// </summary> - private static void CreateWaterPng(Dataset ds, Domain.Layer layer, string outPath, long ticks) - { - string tempPath = Path.Combine(outPath, "temp"); - if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath); - string waterPath = Path.Combine(outPath, "waters", ticks.ToString()); - if (!Directory.Exists(waterPath)) Directory.CreateDirectory(waterPath); - - foreach (int[] sizes in layer.terrain.size) - { - string fileName = Path.GetFileNameWithoutExtension(ds.GetDescription()) + "_" + sizes[0] + "_" + sizes[1]; - string tif = Path.Combine(tempPath, fileName + ".tif"); - Resample(ds.GetDescription(), tif, sizes[0], sizes[1]); - if (!File.Exists(tif)) - { - continue; - } - - string png = Path.Combine(waterPath, sizes[0] + "_" + sizes[1] + ".png"); - Tif2Png(layer, tif, png, sizes[0], sizes[1], 1); - } + ProcessWaters(files, outPath, layer); } /// <summary> @@ -335,6 +249,123 @@ DateTime d = new DateTime(now.Year, now.Month, now.Day, hour, minute, second); layer.waters.data.Add((d.Ticks - startTicks) / 10000); + } + } + + /// <summary> + /// 璁剧疆姘撮潰楂樺害 + /// </summary> + private static void SetWaterHeight(Domain.Layer layer, List<string> files) + { + Parallel.For(0, files.Count, i => + { + Dataset ds = null; + try + { + ds = Gdal.Open(files[i], Access.GA_ReadOnly); + if (null == ds || 0 == ds.RasterCount || null == ds.GetSpatialRef()) return; + + double[] mm = new double[2]; + ds.GetRasterBand(1).ComputeRasterMinMax(mm, 0); + layer.extension.SetHeight(mm[0], mm[1]); + } + finally + { + if (null != ds) ds.Dispose(); + } + }); + layer.extension.minHeight = GetMinVal(layer.extension.minHeight); + layer.extension.maxHeight = GetMaxVal(layer.extension.maxHeight + WaterHeightOffset); + } + + /// <summary> + /// 澶勭悊姘撮潰鏁版嵁 + /// </summary> + private static void ProcessWaters(List<string> files, string outPath, Domain.Layer layer) + { + Parallel.For(0, files.Count, i => + //for (int i = 0; i < files.Count; i++) + { + Dataset ds = null; + try + { + ds = Gdal.Open(files[i], Access.GA_ReadOnly); + if (null == ds || 0 == ds.RasterCount || null == ds.GetSpatialRef()) return; + + CreateWaterPng(ds, layer, outPath, layer.waters.data[i]); + } + finally + { + if (null != ds) ds.Dispose(); + } + }); + } + + /// <summary> + /// 鍒涘缓姘撮潰PNG + /// </summary> + private static void CreateWaterPng(Dataset ds, Domain.Layer layer, string outPath, long ticks) + { + string tempPath = Path.Combine(outPath, "temp"); + if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath); + string waterPath = Path.Combine(outPath, "waters", ticks.ToString()); + if (!Directory.Exists(waterPath)) Directory.CreateDirectory(waterPath); + + foreach (int[] sizes in layer.terrain.size) + { + string fileName = Path.GetFileNameWithoutExtension(ds.GetDescription()) + "_" + sizes[0] + "_" + sizes[1]; + string tif = Path.Combine(tempPath, fileName + ".tif"); + Resample(ds, tif, sizes[0], sizes[1], layer); + if (!File.Exists(tif)) continue; + + string png = Path.Combine(waterPath, sizes[0] + "_" + sizes[1] + ".png"); + Water2Png(layer, tif, png, sizes[0], sizes[1]); + } + } + + /// <summary> + /// 姘撮潰杞琍NG + /// </summary> + private static void Water2Png(Domain.Layer layer, string tif, string png, int width, int height) + { + Dataset ds = null; + try + { + ds = Gdal.Open(tif, Access.GA_ReadOnly); + if (null == ds || 0 == ds.RasterCount) return; + + Band band = ds.GetRasterBand(1); + float[] buffer = new float[width * height]; + band.ReadRaster(0, 0, width, height, buffer, width, height, 0, 0); + + Bitmap image = new Bitmap(width, height); + Graphics graphic = Graphics.FromImage(image); + graphic.Clear(Color.Transparent); // 濉厖閫忔槑鑹� + + double perHeight = (layer.extension.maxHeight - layer.extension.minHeight) * 100 / 65536; + for (int x = 0; x < width; x++) + { + for (int y = 0; y < height; y++) + { + int offset = x + y * width; + if (float.IsNaN(buffer[offset]) || buffer[offset] < -999) continue; + + //int val = Convert.ToInt32(buffer[offset] * 100); + int val = Convert.ToInt32((buffer[offset] - layer.extension.minHeight + WaterHeightOffset) * 100 / perHeight); + int r = val / 65536; + int g = (val - r * 65536) / 256; + int b = val % 256; + + Color color = Color.FromArgb(127, r, g, b); + image.SetPixel(x, y, color); + } + } + image.Save(png, System.Drawing.Imaging.ImageFormat.Png); + } + finally + { + if (null != ds) ds.Dispose(); + //if (File.Exists(tif)) File.Delete(tif); } } #endregion @@ -384,11 +415,11 @@ { string vxName = Path.GetFileNameWithoutExtension(vxDs.GetDescription()) + "_" + sizes[0] + "_" + sizes[1]; string vxTif = Path.Combine(tempPath, vxName + ".tif"); - Resample(vxDs.GetDescription(), vxTif, sizes[0], sizes[1]); + Resample(vxDs, vxTif, sizes[0], sizes[1], layer); string vyName = Path.GetFileNameWithoutExtension(vyDs.GetDescription()) + "_" + sizes[0] + "_" + sizes[1]; string vyTif = Path.Combine(tempPath, vyName + ".tif"); - Resample(vyDs.GetDescription(), vyTif, sizes[0], sizes[1]); + Resample(vyDs, vyTif, sizes[0], sizes[1], layer); if (!File.Exists(vxTif) || !File.Exists(vyTif)) continue; @@ -413,21 +444,14 @@ vxDs.GetRasterBand(1).ReadRaster(0, 0, width, height, vxBuffer, width, height, 0, 0); vyDs.GetRasterBand(1).ReadRaster(0, 0, width, height, vyBuffer, width, height, 0, 0); - //double[] vxMm = new double[2]; - //vxDs.GetRasterBand(1).ComputeRasterMinMax(vxMm, 0); - //double[] vyMm = new double[2]; - //vyDs.GetRasterBand(1).ComputeRasterMinMax(vyMm, 0); - //double min = vxMm[0] < vyMm[0] ? vxMm[0] : vyMm[0]; - //double max = vxMm[1] > vyMm[1] ? vxMm[1] : vyMm[1]; - CreateFlowPng(vxBuffer, vyBuffer, png, width, height); } finally { if (null != vxDs) vxDs.Dispose(); if (null != vyDs) vyDs.Dispose(); - if (File.Exists(vxTif)) File.Delete(vxTif); - if (File.Exists(vyTif)) File.Delete(vyTif); + //if (File.Exists(vxTif)) File.Delete(vxTif); + //if (File.Exists(vyTif)) File.Delete(vyTif); } } @@ -448,17 +472,17 @@ int offset = x + y * width; float fx = GetFloatValue(vxBuffer[offset]); float fy = GetFloatValue(vyBuffer[offset]); + if (float.IsNaN(fx) && float.IsNaN(fy) || (fx == 0 && fy == 0)) continue; - double dv = GetXyValue(fx, fy); - double dx = float.IsNaN(fx) ? 0 : fx * 0.5 + 0.5; - double dy = float.IsNaN(fy) ? 0 : fy * 0.5 + 0.5; + fx = float.IsNaN(fx) ? 0 : fx; + fy = float.IsNaN(fy) ? 0 : fy; + double dr = Math.Sqrt(Math.Pow(fx, 2) + Math.Pow(fy, 2)); - int r = Convert.ToInt32(dv * 255); - if (r > 255) r = 255; - int g = Convert.ToInt32(dx * 255); - int b = Convert.ToInt32(dy * 255); + int r = Convert.ToInt32(dr / 4 * 255); + int g = Convert.ToInt32((fx / dr * 0.5 + 0.5) * 255); + int b = Convert.ToInt32((fy / dr * 0.5 + 0.5) * 255); - Color color = Color.FromArgb(127, r, g, b); + Color color = Color.FromArgb(127, GetSafeValue(r), GetSafeValue(g), GetSafeValue(b)); image.SetPixel(x, y, color); } } @@ -470,30 +494,18 @@ /// </summary> private static float GetFloatValue(float val) { - //return (float.IsNaN(val) || val < -999) ? float.NaN : val; - if (float.IsNaN(val) || val < -999) return float.NaN; - if (val > 1) return 1; - if (val < -1) return -1; - - return val; + return (float.IsNaN(val) || val < -999) ? float.NaN : val; } - private static double GetXyValue(float fx, float fy) + /// <summary> + /// 鑾峰彇瀹夊叏鍊� + /// </summary> + private static int GetSafeValue(int val) { - if (float.IsNaN(fx) && float.IsNaN(fy)) - { - return 0; - } - if (float.IsNaN(fx)) - { - return Math.Abs(fy); - } - if (float.IsNaN(fy)) - { - return Math.Abs(fx); - } + if (val < 0) return 0; + if (val > 255) return 255; - return Math.Sqrt(Math.Pow(fx, 2) + Math.Pow(fy, 2)); + return val; } #endregion @@ -514,5 +526,108 @@ } } #endregion + + #region 鏆傛椂涓嶇敤 + /// <summary> + /// 璁剧疆鍦板舰淇℃伅 + /// </summary> + private static void SetTerrainInfo(Dataset ds, string outPath, Domain.Layer layer) + { + string tempPath = Path.Combine(outPath, "temp"); + if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath); + + string tif = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(ds.GetDescription()) + ".tif"); + Resample(ds, tif); + if (!File.Exists(tif)) throw new Exception("楂樼▼鏂囦欢閲嶆姇褰卞け璐ワ紒"); + + Dataset tifDS = null; + try + { + tifDS = Gdal.Open(tif, Access.GA_ReadOnly); + if (null == tifDS || 0 == tifDS.RasterCount || null == tifDS.GetSpatialRef()) return; + + double[] transform = new double[6]; + tifDS.GetGeoTransform(transform); + double minx = transform[0]; + double miny = transform[3] - tifDS.RasterYSize * transform[1]; + double maxx = transform[0] + (tifDS.RasterYSize * transform[1]); + double maxy = transform[3]; + + layer.extension = new Extension(minx, miny, maxx, maxy, double.MaxValue, double.MinValue); + + Band band = tifDS.GetRasterBand(1); + double[] mm = new double[2]; + band.ComputeRasterMinMax(mm, 0); + layer.terrain.SetHeight(GetMinVal(mm[0]), GetMaxVal(mm[1])); + } + finally + { + if (null != tifDS) tifDS.Dispose(); + } + } + + /// <summary> + /// 閲嶉噰鏍� + /// </summary> + private static void Resample(Dataset ds, string dest) + { + string[] options = new string[] { "-t_srs", "EPSG:4326", "-r", "bilinear", "-of", "GTiff" }; + GDALWarpAppOptions warpAppOptions = new GDALWarpAppOptions(options); + + Dataset destDs = Gdal.Warp(dest, new Dataset[] { ds }, warpAppOptions, null, null); + destDs.Dispose(); + } + + /// <summary> + /// 閲嶉噰鏍� + /// </summary> + private static void Resample(string source, string dest, int width, int height) + { + // https://blog.51cto.com/u_16099346/6691820 + string cmd = string.Format("{0}gdalwarp.exe -t_srs {1} -ts {2} {3} -r {4} -of GTiff \"{5}\" \"{6}\"", GdalPath, "EPSG:4326", width, height, "bilinear", source, dest); + string err = ExecExe(cmd); + } + + /// <summary> + /// 鎵ц鍛戒护 + /// </summary> + public static string ExecExe(string cmd) + { + string str = null; + Process p = null; + try + { + p = new Process(); + p.StartInfo.FileName = "cmd.exe"; + p.StartInfo.UseShellExecute = false; + p.StartInfo.CreateNoWindow = true; + p.StartInfo.RedirectStandardInput = true; + p.StartInfo.RedirectStandardOutput = true; + p.StartInfo.RedirectStandardError = true; + p.Start(); + + StreamWriter si = p.StandardInput; + StreamReader se = p.StandardError; + + si.AutoFlush = true; + si.WriteLine(cmd); + si.WriteLine("exit"); + + str = se.ReadToEnd(); + se.Close(); + si.Close(); + } + catch (Exception ex) + { + LogOut.Error(ex.Message + "\r\n" + ex.StackTrace); + str = ex.Message; + } + finally + { + if (p != null) p.Close(); + } + return str; + } + #endregion } } -- Gitblit v1.9.3