dcb
2025-05-08 256c1b584af7ed549e3efc3909c8c8b55a7a3331
src/main/java/com/se/nsl/service/TestService.java
@@ -3,12 +3,10 @@
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.se.nsl.config.PropertiesConfig;
import com.se.nsl.domain.dto.ExtensionDto;
import com.se.nsl.domain.dto.LayerDto;
import com.se.nsl.domain.dto.PointDto;
import com.se.nsl.domain.dto.ResultDto;
import com.se.nsl.domain.dto.*;
import com.se.nsl.domain.po.DataPo;
import com.se.nsl.domain.po.PondingPo;
import com.se.nsl.domain.po.SimuData;
import com.se.nsl.domain.vo.BuildingDepthVo;
import com.se.nsl.helper.ComHelper;
import com.se.nsl.helper.GdalHelper;
@@ -17,7 +15,8 @@
import org.gdal.gdal.Band;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.gdal;
import org.gdal.gdalconst.gdalconst;
//import org.gdal.gdalconstConstants.gdalconst;
import org.gdal.gdalconst.gdalconstConstants;
import org.gdal.ogr.*;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
@@ -35,6 +34,7 @@
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
@Slf4j
@Service
@@ -46,9 +46,26 @@
    @Resource
    ResultService resultService;
    public final static double MIN_VAL = 0.00001;
    public final static double MAX_X_OFFSET = 0;
    public final static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    public void test(SimuData data) throws Exception {
        String basePath = config.getInPath() + File.separator + data.getInPath() + File.separator;
        ResultDto dto = new ResultDto(
                data.getInPath(),
                basePath + config.getTerrainFile(),
                basePath + config.getBuildingFile(),
                basePath + config.getWaterPath(),
                basePath + config.getFlowPath(),
                config.getInPath(),
                config.getOutPath(),
                data.getEpsg());
        LayerDto layer = new LayerDto(config.getVer(), data.getEpsg(), config.getSizes());
        process(dto, layer);
    }
    public void test(DataPo data) throws Exception {
        String basePath = config.getInPath() + File.separator + data.getInPath() + File.separator;
@@ -69,8 +86,8 @@
        try {
            copeTerrain(dto, layer);
            //copeBuilding(dto, layer);
            //List<BuildingDepthVo> buildings = copeWater(dto, layer);
            //copeFlow(dto, layer);
            List<BuildingDepthVo> buildings = copeWater(dto, layer);
            copeFlow(dto, layer);
            copeLayerJson(dto, layer);
            //copeRainFallJson(dto, layer);
            //copeBuildingDepthJson(dto, buildings);
@@ -85,12 +102,13 @@
    public void copeTerrain(ResultDto dto, LayerDto layer) {
        Dataset ds = null;
        try {
            ds = gdal.Open(dto.getTerrainFile(), gdalconst.GA_ReadOnly);
            // gdalconst,gdalconstConstants
            ds = gdal.Open(dto.getTerrainFile(), gdalconstConstants.GA_ReadOnly);
            if (null == ds || 0 == ds.getRasterCount()) return;
            setTerrainInfo(ds, layer);
            createTerrainPng(dto, ds, layer);
            setWaterInfo(dto, layer);
            createTerrainPng(dto, ds, layer);
        } finally {
            if (null != ds) ds.delete();
        }
@@ -130,7 +148,7 @@
    public void Terrain2Png(LayerDto layer, String tif, String png, int width, int height) {
        Dataset ds = null;
        try {
            ds = gdal.Open(tif, gdalconst.GA_ReadOnly);
            ds = gdal.Open(tif, gdalconstConstants.GA_ReadOnly);
            if (null == ds || 0 == ds.getRasterCount()) return;
            Band band = ds.GetRasterBand(1);
@@ -175,6 +193,19 @@
        setWaterHeight(layer, files);
    }
    public List<BuildingDepthVo> copeWater(ResultDto dto, LayerDto layer) {
        List<String> files = layer.getWaters().getFiles();
        if (files.size() == 0 || files.size() != layer.getWaters().getData().size()) return null;
        processWaters(dto, files, layer);
        if (new File(dto.getBuildingFile()).exists()) {
            return processBuilding(dto, files, layer);
        }
        return null;
    }
    public List<String> getFiles(String path, String suffix) {
        List<String> files = new ArrayList<>();
        ComHelper.getFiles(files, new File(path), suffix);
@@ -211,10 +242,10 @@
    }
    public void setWaterHeight(LayerDto layer, List<String> files) {
        files.parallelStream().forEach(file -> {
        /*files.parallelStream().forEach(file -> {
            Dataset ds = null;
            try {
                ds = gdal.Open(file, gdalconst.GA_ReadOnly);
                ds = gdal.Open(file, gdalconstConstants.GA_ReadOnly);
                if (null == ds || 0 == ds.getRasterCount()) return;
                double[] mm = new double[2];
@@ -223,8 +254,25 @@
            } finally {
                if (null != ds) ds.delete();
            }
        });
        layer.getExtension().setMaxHeight(layer.getExtension().getMaxHeight() + layer.getWaters().getMaxHeight());
        });*/
        int c = files.size(), step = files.size() / 10;
        if (step < 1) step = 1;
        for (int i = 0; i < c; i += step) {
            Dataset ds = null;
            try {
                ds = gdal.Open(files.get(i), gdalconstConstants.GA_ReadOnly);
                if (null == ds || 0 == ds.getRasterCount()) return;
                double[] mm = new double[2];
                ds.GetRasterBand(1).ComputeRasterMinMax(mm, 0);
                layer.getWaters().setHeight(mm[0], mm[1]);
            } finally {
                if (null != ds) ds.delete();
            }
        }
        layer.getExtension().setMaxHeight(layer.getExtension().getMaxHeight() + layer.getWaters().getMaxHeight() + 1);
        layer.getExtension().setMaxHeight(ComHelper.getMaxVal(layer.getExtension().getMaxHeight(), 1000000));
        layer.getExtension().setMinHeight(ComHelper.getMaxVal(layer.getExtension().getMinHeight(), 1000000));
        layer.getExtension().setDiffer();
@@ -234,13 +282,13 @@
        for (int i = 0, c = files.size(); i < c; i++) {
            Dataset ds = null;
            try {
                ds = gdal.Open(files.get(i), gdalconst.GA_ReadOnly);
                ds = gdal.Open(files.get(i), gdalconstConstants.GA_ReadOnly);
                if (null == ds || 0 == ds.getRasterCount()) return;
                if (null == ds.GetSpatialRef()) ds.SetSpatialRef(dto.getSpatialReference());
                createWaterPng(dto, ds, layer, layer.getWaters().getData().get(i));
                //if (config.getCopyTif()) copyWaterTif(dto, ds, layer.getWaters().getData().get(i));
                createVectors(dto, ds, layer, layer.getWaters().getData().get(i));
                ///createVectors(dto, ds, layer, layer.getWaters().getData().get(i));
            } finally {
                if (null != ds) ds.delete();
            }
@@ -255,7 +303,7 @@
        for (int[] sizes : layer.getTerrain().getSize()) {
            String fileName = ComHelper.getNameWithExt(ds.GetDescription()) + "_" + sizes[0] + "_" + sizes[1];
            String tif = dto.getTemp() + File.separator + fileName + ".tif";
            ComHelper.Resample(ds, tif, sizes[0], sizes[1], layer);
            ComHelper.Resample2(ds, tif, sizes[0], sizes[1], layer);
            if (!new File(tif).exists()) continue;
            String png = waterPath + File.separator + sizes[0] + "_" + sizes[1] + ".png";
@@ -266,13 +314,14 @@
    public void water2Png(ResultDto dto, LayerDto layer, String tif, String png, int width, int height) {
        Dataset ds = null;
        try {
            ds = gdal.Open(tif, gdalconst.GA_ReadOnly);
            ds = gdal.Open(tif, gdalconstConstants.GA_ReadOnly);
            if (null == ds || 0 == ds.getRasterCount()) return;
            Band band = ds.GetRasterBand(1);
            float[] buffer = new float[width * height];
            band.ReadRaster(0, 0, width, height, buffer);
            double[] transform = ds.GetGeoTransform();
            buffer = interpolateGrid(buffer, width);
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            //double differ = layer.getWaters().getMaxHeight() - layer.getWaters().getMinHeight(), minHeight = layer.getWaters().getMinHeight();
@@ -282,7 +331,7 @@
                for (int y = 0; y < height; y++) {
                    int offset = x + y * width;
                    //if (Float.isNaN(buffer[offset]) || buffer[offset] < -999 || buffer[offset] < minHeight) continue;
                    if (Float.isNaN(buffer[offset]) || buffer[offset] <= 0 || Float.isNaN(ts[offset])) continue;
                    if (Float.isNaN(buffer[offset]) || buffer[offset] < MIN_VAL || Float.isNaN(ts[offset])) continue;
                    //double X = transform[0] + x * transform[1] + y * transform[2];
                    //double Y = transform[3] + x * transform[4] + y * transform[5];
@@ -294,6 +343,7 @@
                        g = b = 255;
                    } else {
                        int val = (int) ((buffer[offset] + ts[offset] - minHeight) / differ * 65535);
                        //int val = (int) (buffer[offset] / differ * 65535);
                        g = val / 256;
                        b = val % 256;
                    }
@@ -308,11 +358,124 @@
        }
    }
    /**
     * 插值处理-四邻域
     */
    public float[] interpolateGrid(float[] buffer, int size) {
        float[] tempBuffer = new float[size * size];
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                int index = i * size + j;
                float current = buffer[index];
                if (current == 0) {
                    float sum = 0;
                    int count = 0;
                    // 检查上邻
                    if (i > 0) {
                        float neighbor = buffer[(i - 1) * size + j];
                        if (neighbor > MIN_VAL) {
                            sum += neighbor;
                            count++;
                        }
                    }
                    // 检查下邻
                    if (i < size - 1) {
                        float neighbor = buffer[(i + 1) * size + j];
                        if (neighbor > MIN_VAL) {
                            sum += neighbor;
                            count++;
                        }
                    }
                    // 检查左邻
                    if (j > 0) {
                        float neighbor = buffer[i * size + (j - 1)];
                        if (neighbor > MIN_VAL) {
                            sum += neighbor;
                            count++;
                        }
                    }
                    // 检查右邻
                    if (j < size - 1) {
                        float neighbor = buffer[i * size + (j + 1)];
                        if (neighbor > MIN_VAL) {
                            sum += neighbor;
                            count++;
                        }
                    }
                    // 计算新值
                    if (count > 0) {
                        tempBuffer[index] = (sum / count) * 0.5f;
                    } else {
                        tempBuffer[index] = 0;
                    }
                } else {
                    tempBuffer[index] = current;
                }
            }
        }
        // 将临时数组复制回原数组
        //System.arraycopy(tempBuffer, 0, buffer, 0, tempBuffer.length);
        return tempBuffer;
    }
    public List<BuildingDepthVo> processBuilding(ResultDto dto, List<String> files, LayerDto layer) {
        List<BuildingDepthVo> list = new CopyOnWriteArrayList<>();
        for (int i = 0, c = files.size(); i < c; i++) {
            Dataset ds = null;
            try {
                ds = gdal.Open(files.get(i), gdalconstConstants.GA_ReadOnly);
                if (null == ds || 0 == ds.getRasterCount()) continue;
                if (null == ds.GetSpatialRef()) ds.SetSpatialRef(dto.getSpatialReference());
                copeBuildingDepth(dto, ds, layer.getWaters().getData().get(i), list);
            } finally {
                if (null != ds) ds.delete();
            }
        }
        return list;
    }
    public void copeBuildingDepth(ResultDto dto, Dataset ds, long ticks, List<BuildingDepthVo> list) {
        double[] transform = ds.GetGeoTransform();
        int xSize = ds.getRasterXSize(), ySize = ds.getRasterYSize();
        double minX = transform[0], pixelWidth = transform[1], maxY = transform[3], pixelHeight = Math.abs(transform[5]);
        for (BuildingDto building : dto.getBuildingList()) {
            Double val = getValue(ds, building, xSize, ySize, minX, maxY, pixelWidth, pixelHeight);
            list.add(new BuildingDepthVo(building.getId(), ticks, val));
        }
    }
    public Double getValue(Dataset ds, BuildingDto building, int xSize, int ySize, double minX, double maxY, double pixelWidth, double pixelHeight) {
        double[] env = new double[4];
        building.getGeom().GetEnvelope(env);
        int startX = (int) Math.floor((env[0] - minX) / pixelWidth);
        int endX = (int) Math.floor((env[1] - minX) / pixelWidth);
        int startY = (int) Math.floor((maxY - env[3]) / Math.abs(pixelHeight));
        int endY = (int) Math.floor((maxY - env[2]) / Math.abs(pixelHeight));
        if (startX < 0) startX = 0;
        if (startY < 0) startY = 0;
        if (endX > ds.getRasterXSize()) endX = ds.getRasterXSize();
        if (endY > ds.getRasterYSize()) endY = ds.getRasterYSize();
        if (endX - startX < 1 || endY - startY < 1) return null;
        int width = endX - startX;
        int height = endY - startY;
        double[] pixelValues = new double[width * height];
        ds.GetRasterBand(1).ReadRaster(startX, startY, width, height, pixelValues);
        Double val = Arrays.stream(pixelValues).max().getAsDouble();
        return ComHelper.isValid(val) ? val : null;
    }
    public void createVectors(ResultDto dto, Dataset ds, LayerDto layer, Long ticks) {
        String filePath = dto.getOutPath() + File.separator + "waters" + File.separator + ticks + File.separator + "polygonize.geojson";
        ShpHelper.polygonize2Geojson(ds, filePath);
        List<Geometry> geometries = getGeometries(filePath);
        /*List<Geometry> geometries = getGeometries(filePath);
        if (CollectionUtils.isEmpty(geometries)) return;
        List<PondingPo> list = copePonding(dto, ds, layer, geometries);
@@ -323,7 +486,7 @@
            ComHelper.writeJson(filePath, JSON.toJSONString(list));
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        }*/
    }
    public List<Geometry> getGeometries(String filePath) {
@@ -401,13 +564,12 @@
    }
    public void copeFlow(ResultDto dto, LayerDto layer) {
        List<String> files = getFiles(dto.getFlowPath(), ".tif");
        if (null == files || files.size() != layer.getWaters().getData().size()) return;
        List<String> files = layer.getWaters().getFiles();
        if (null == files || files.isEmpty()) return;
        for (int i = 0, c = files.size(); i < c; i++) {
            Dataset ds = null;
            try {
                ds = gdal.Open(files.get(i), gdalconst.GA_ReadOnly);
                ds = gdal.Open(files.get(i), gdalconstConstants.GA_ReadOnly);
                if (null == ds || 0 == ds.getRasterCount()) return;
                if (null == ds.GetSpatialRef()) ds.SetSpatialRef(dto.getSpatialReference());
@@ -437,27 +599,79 @@
    public void vxyTif2Png(LayerDto layer, String tif, String png, int width, int height) {
        Dataset ds = null;
        try {
            ds = gdal.Open(tif, gdalconst.GA_ReadOnly);
            ds = gdal.Open(tif, gdalconstConstants.GA_ReadOnly);
            if (null == ds || 0 == ds.getRasterCount()) return;
            float[] depthBuffer = new float[width * height];
            float[] vxBuffer = new float[width * height];
            float[] vyBuffer = new float[width * height];
            ds.GetRasterBand(1).ReadRaster(0, 0, width, height, depthBuffer);
            ds.GetRasterBand(2).ReadRaster(0, 0, width, height, vxBuffer);
            ds.GetRasterBand(3).ReadRaster(0, 0, width, height, vyBuffer);
            createFlowPng(depthBuffer, vxBuffer, vyBuffer, png, width, height);
        } finally {
            if (null != ds) ds.delete();
        }
    }
    public void createFlowPng(float[] depthBuffer, float[] vxBuffer, float[] vyBuffer, String png, int width, int height) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int offset = x + y * width;
                float depth = ComHelper.getFloatValue(depthBuffer[offset]);
                float fx = ComHelper.getFloatValue(vxBuffer[offset]);
                float fy = ComHelper.getFloatValue(vyBuffer[offset]);
                if (Float.isNaN(fx) && Float.isNaN(fy) || (fx < MIN_VAL && fy < MIN_VAL)) continue;
                if (depth == 0) {
                    fx = 0f;
                    fy = 0f;
                } else {
                    fx = Float.isNaN(fx) ? 0 : fx / depth;
                    fy = Float.isNaN(fy) ? 0 : fy / depth;
                }
                double dr = Math.sqrt(Math.pow(fx, 2) + Math.pow(fy, 2));
                int r = (int) (dr / 4 * 255);
                int g = (int) ((fx / dr * 0.5 + 0.5) * 255);
                int b = (int) ((fy / dr * 0.5 + 0.5) * 255);
                Color color = new Color(ComHelper.getSafeValue(r), ComHelper.getSafeValue(g), ComHelper.getSafeValue(b), 127);
                image.setRGB(x, y, color.getRGB());
            }
        }
        ComHelper.savePng(image, png);
    }
/*
    public void vxyTif2Png(LayerDto layer, String tif, String png, int width, int height) {
        Dataset ds = null;
        try {
            ds = gdal.Open(tif, gdalconstConstants.GA_ReadOnly);
            if (null == ds || 0 == ds.getRasterCount()) return;
            float[] vxBuffer = new float[width * height], vyBuffer = new float[width * height];
            ds.GetRasterBand(1).ReadRaster(0, 0, width, height, vxBuffer);
            ds.GetRasterBand(2).ReadRaster(0, 0, width, height, vyBuffer);
            ds.GetRasterBand(2).ReadRaster(0, 0, width, height, vxBuffer);
            ds.GetRasterBand(3).ReadRaster(0, 0, width, height, vyBuffer);
            createFlowPng(vxBuffer, vyBuffer, png, width, height);
        } finally {
            if (null != ds) ds.delete();
        }
    }
*/
    public void createFlowPng(float[] vxBuffer, float[] vyBuffer, String png, int width, int height) {
    /*public void createFlowPng(float[] vxBuffer, float[] vyBuffer, String png, int width, int height) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int offset = x + y * width;
                float fx = ComHelper.getFloatValue(vxBuffer[offset]);
                float fy = ComHelper.getFloatValue(vyBuffer[offset]);
                if (Float.isNaN(fx) && Float.isNaN(fy) || (fx == 0 && fy == 0)) continue;
                if (Float.isNaN(fx) && Float.isNaN(fy) || (fx < MIN_VAL && fy < MIN_VAL)) continue;
                fx = Float.isNaN(fx) ? 0 : fx;
                fy = Float.isNaN(fy) ? 0 : fy;
@@ -472,13 +686,17 @@
            }
        }
        ComHelper.savePng(image, png);
    }
    }*/
    public void copeLayerJson(ResultDto dto, LayerDto layer) throws IOException {
        layer.getWaters().setFiles(null);
        layer.getTerrain().setEpsg(null);
        layer.getExtension().setDiffer(null);
        String path = dto.getOutPath().replace(config.getOutPath() + File.separator, "");
        layer.setWaterUrl("/hls/w" + path + ".m3u8");
        layer.setFlowUrl("/hls/f" + path + ".m3u8");
        String json = JSON.toJSONString(layer);
        // String json = JSONUtil.toJsonPrettyStr(layer);
        String filePath = dto.getOutPath() + File.separator + "layer.json";