Search in sources :

Example 1 with ColorInterpolator

use of org.hortonmachine.gears.utils.colors.ColorInterpolator in project hortonmachine by TheHortonMachine.

the class RasterizedSpatialiteLasLayer method makeLevels.

private static LevelSet makeLevels(String title, Integer tileSize, boolean transparentBackground, ASpatialDb db, boolean doIntensity) throws Exception {
    String plus = doIntensity ? INTENSITY : ELEVATION;
    String cacheRelativePath = "rasterized_spatialites/" + title + "_" + plus + "-tiles";
    File cacheRoot = CacheUtils.getCacheRoot();
    final File cacheFolder = new File(cacheRoot, cacheRelativePath);
    if (!cacheFolder.exists()) {
        cacheFolder.mkdirs();
    }
    CacheUtils.clearCacheBySourceName(cacheRelativePath);
    AVList params = new AVListImpl();
    if (tileSize == null || tileSize < 256) {
        tileSize = TILESIZE;
    }
    int finalTileSize = tileSize;
    GeometryColumn spatialiteGeometryColumns = db.getGeometryColumnsForTable(LasCellsTable.TABLENAME);
    CoordinateReferenceSystem dataCrs = CRS.decode("EPSG:" + spatialiteGeometryColumns.srid);
    CoordinateReferenceSystem nwwCRS = DefaultGeographicCRS.WGS84;
    List<LasSource> lasSources = LasSourcesTable.getLasSources(db);
    double min = Double.POSITIVE_INFINITY;
    double max = Double.NEGATIVE_INFINITY;
    List<Polygon> polList = new ArrayList<>();
    ColorInterpolator colorInterp;
    int lasLevels = 0;
    if (!doIntensity) {
        for (LasSource lasSource : lasSources) {
            lasLevels = lasSource.levels;
            polList.add(lasSource.polygon);
            min = Math.min(min, lasSource.minElev);
            max = Math.max(max, lasSource.maxElev);
        }
        colorInterp = new ColorInterpolator(EColorTables.elev.name(), min, max, null);
    } else {
        for (LasSource lasSource : lasSources) {
            lasLevels = lasSource.levels;
            polList.add(lasSource.polygon);
            min = Math.min(min, lasSource.minIntens);
            max = Math.max(max, lasSource.maxIntens);
        }
        colorInterp = new ColorInterpolator(EColorTables.rainbow.name(), 0, 255, null);
    }
    final int _lasLevels = lasLevels;
    Geometry sourcesUnionData = CascadedPolygonUnion.union(polList);
    PreparedGeometry preparedCoverage = PreparedGeometryFactory.prepare(sourcesUnionData);
    MathTransform nww2DataTransform = CRS.findMathTransform(nwwCRS, dataCrs);
    MathTransform data2NwwTransform = CRS.findMathTransform(dataCrs, nwwCRS);
    // String urlString = folderFile.toURI().toURL().toExternalForm();
    // params.setValue(AVKey.URL, urlString);
    params.setValue(AVKey.TILE_WIDTH, finalTileSize);
    params.setValue(AVKey.TILE_HEIGHT, finalTileSize);
    params.setValue(AVKey.DATA_CACHE_NAME, cacheRelativePath);
    params.setValue(AVKey.SERVICE, "*");
    params.setValue(AVKey.DATASET_NAME, "*");
    params.setValue(AVKey.FORMAT_SUFFIX, ".png");
    params.setValue(AVKey.NUM_LEVELS, 22);
    params.setValue(AVKey.NUM_EMPTY_LEVELS, 8);
    params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, new LatLon(Angle.fromDegrees(22.5d), Angle.fromDegrees(45d)));
    params.setValue(AVKey.SECTOR, new MercatorSector(-1.0, 1.0, Angle.NEG180, Angle.POS180));
    params.setValue(AVKey.TILE_URL_BUILDER, new TileUrlBuilder() {

        public URL getURL(Tile tile, String altImageFormat) throws MalformedURLException {
            try {
                int zoom = tile.getLevelNumber() + 3;
                Sector sector = tile.getSector();
                double north = sector.getMaxLatitude().degrees;
                double south = sector.getMinLatitude().degrees;
                double east = sector.getMaxLongitude().degrees;
                double west = sector.getMinLongitude().degrees;
                double centerX = west + (east - west) / 2.0;
                double centerY = south + (north - south) / 2.0;
                int[] tileNumber = NwwUtilities.getTileNumber(centerY, centerX, zoom);
                int x = tileNumber[0];
                int y = tileNumber[1];
                Rectangle imageBounds = new Rectangle(0, 0, finalTileSize, finalTileSize);
                ReferencedEnvelope tileEnvNww = new ReferencedEnvelope(west, east, south, north, DefaultGeographicCRS.WGS84);
                AffineTransform worldToPixel = TransformationUtils.getWorldToPixel(tileEnvNww, imageBounds);
                PointTransformation pointTransformation = new PointTransformation() {

                    @Override
                    public void transform(Coordinate src, Point2D dest) {
                        worldToPixel.transform(new Point2D.Double(src.x, src.y), dest);
                    }
                };
                Polygon polygonNww = GeometryUtilities.createPolygonFromEnvelope(tileEnvNww);
                Geometry polygonData = JTS.transform(polygonNww, nww2DataTransform);
                int imgType;
                Color backgroundColor;
                boolean intersects = preparedCoverage.intersects(polygonData);
                if (transparentBackground || !intersects) {
                    imgType = BufferedImage.TYPE_INT_ARGB;
                    backgroundColor = new Color(Color.WHITE.getRed(), Color.WHITE.getGreen(), Color.WHITE.getBlue(), 0);
                } else {
                    imgType = BufferedImage.TYPE_INT_RGB;
                    backgroundColor = Color.WHITE;
                }
                BufferedImage image = new BufferedImage(imageBounds.width, imageBounds.height, imgType);
                Graphics2D gr = image.createGraphics();
                gr.setPaint(backgroundColor);
                gr.fill(imageBounds);
                if (zoom < 12) {
                    Geometry sourcesUnionNww = JTS.transform(sourcesUnionData, data2NwwTransform);
                    drawSources(db, pointTransformation, sourcesUnionNww, gr, finalTileSize);
                } else if (zoom < 14) {
                    drawLevels(db, colorInterp, pointTransformation, polygonData, gr, _lasLevels, data2NwwTransform, doIntensity, finalTileSize);
                } else if (zoom < 15 && _lasLevels - 1 > 0) {
                    drawLevels(db, colorInterp, pointTransformation, polygonData, gr, _lasLevels - 1, data2NwwTransform, doIntensity, finalTileSize);
                } else if (zoom < 17 && _lasLevels - 2 > 0) {
                    drawLevels(db, colorInterp, pointTransformation, polygonData, gr, _lasLevels - 2, data2NwwTransform, doIntensity, finalTileSize);
                } else if (zoom > 18) {
                    drawPoints(db, colorInterp, pointTransformation, polygonData, gr, data2NwwTransform, doIntensity, finalTileSize);
                } else {
                    drawCells(db, colorInterp, pointTransformation, polygonData, gr, data2NwwTransform, doIntensity, finalTileSize);
                }
                File tileImageFolderFile = new File(cacheFolder, zoom + File.separator + x);
                if (!tileImageFolderFile.exists()) {
                    tileImageFolderFile.mkdirs();
                }
                File imgFile = new File(tileImageFolderFile, y + ".png");
                if (!imgFile.exists()) {
                    ImageIO.write(image, "png", imgFile);
                }
                return imgFile.toURI().toURL();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    });
    return new LevelSet(params);
}
Also used : MalformedURLException(java.net.MalformedURLException) MathTransform(org.opengis.referencing.operation.MathTransform) ArrayList(java.util.ArrayList) Rectangle(java.awt.Rectangle) URL(java.net.URL) BufferedImage(java.awt.image.BufferedImage) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) LevelSet(gov.nasa.worldwind.util.LevelSet) Point2D(java.awt.geom.Point2D) MercatorSector(gov.nasa.worldwind.layers.mercator.MercatorSector) GeometryColumn(org.hortonmachine.dbs.compat.GeometryColumn) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) Polygon(org.locationtech.jts.geom.Polygon) TileUrlBuilder(gov.nasa.worldwind.util.TileUrlBuilder) AVListImpl(gov.nasa.worldwind.avlist.AVListImpl) MercatorSector(gov.nasa.worldwind.layers.mercator.MercatorSector) Sector(gov.nasa.worldwind.geom.Sector) Color(java.awt.Color) PointTransformation(org.locationtech.jts.awt.PointTransformation) Tile(gov.nasa.worldwind.util.Tile) ColorInterpolator(org.hortonmachine.gears.utils.colors.ColorInterpolator) MalformedURLException(java.net.MalformedURLException) Graphics2D(java.awt.Graphics2D) PreparedGeometry(org.locationtech.jts.geom.prep.PreparedGeometry) Geometry(org.locationtech.jts.geom.Geometry) LatLon(gov.nasa.worldwind.geom.LatLon) PreparedGeometry(org.locationtech.jts.geom.prep.PreparedGeometry) Coordinate(org.locationtech.jts.geom.Coordinate) AVList(gov.nasa.worldwind.avlist.AVList) AffineTransform(java.awt.geom.AffineTransform) File(java.io.File) LasSource(org.hortonmachine.gears.io.las.databases.LasSource)

Example 2 with ColorInterpolator

use of org.hortonmachine.gears.utils.colors.ColorInterpolator in project hortonmachine by TheHortonMachine.

the class MainController method createMenuActions.

private void createMenuActions(JPopupMenu popupMenu) {
    boolean isRaster = false;
    if (currentLayer instanceof RasterLayer) {
        isRaster = true;
    }
    if (currentSelectedSW != null && !isRaster) {
        // add featureStyle
        AbstractAction action = new AbstractAction("Add new FeatureTypeStyle") {

            @Override
            public void actionPerformed(ActionEvent e) {
                FeatureTypeStyle featureTypeStyle = StyleUtilities.sf.createFeatureTypeStyle();
                FeatureTypeStyleWrapper ftsw = new FeatureTypeStyleWrapper(featureTypeStyle, currentSelectedSW);
                String tmpName = "New Group";
                tmpName = WrapperUtilities.checkSameNameFeatureTypeStyle(styleWrapper.getFeatureTypeStylesWrapperList(), tmpName);
                ftsw.setName(tmpName);
                styleWrapper.addFeatureTypeStyle(ftsw);
                reloadGroupsAndRules();
            }
        };
        JMenuItem item = new JMenuItem(action);
        popupMenu.add(item);
        item.setHorizontalTextPosition(JMenuItem.RIGHT);
    } else if (currentSelectedFSW != null && !isRaster) {
        // add rule
        AbstractAction action = new AbstractAction("Add new Rule") {

            @Override
            public void actionPerformed(ActionEvent e) {
                Rule rule = StyleUtilities.sf.createRule();
                RuleWrapper rw = new RuleWrapper(rule, currentSelectedFSW);
                currentSelectedFSW.addRule(rw);
                String tmpName = "New Rule";
                tmpName = WrapperUtilities.checkSameNameRule(currentSelectedFSW.getRulesWrapperList(), tmpName);
                rw.setName(tmpName);
                reloadGroupsAndRules();
            }
        };
        JMenuItem item = new JMenuItem(action);
        popupMenu.add(item);
        item.setHorizontalTextPosition(JMenuItem.RIGHT);
        action = new AbstractAction("Remove all Rules") {

            @Override
            public void actionPerformed(ActionEvent e) {
                currentSelectedFSW.clear();
                reloadGroupsAndRules();
            }
        };
        item = new JMenuItem(action);
        popupMenu.add(item);
        item.setHorizontalTextPosition(JMenuItem.RIGHT);
        List<FeatureTypeStyleWrapper> featureTypeStylesWrapperList = styleWrapper.getFeatureTypeStylesWrapperList();
        int ftIndex = featureTypeStylesWrapperList.indexOf(currentSelectedFSW);
        int ftSize = featureTypeStylesWrapperList.size();
        if (ftSize > 1 && ftIndex > 0) {
            action = new AbstractAction("Move up") {

                @Override
                public void actionPerformed(ActionEvent e) {
                    int from = ftIndex;
                    int to = ftIndex - 1;
                    if (to >= 0) {
                        styleWrapper.swap(from, to);
                        reloadGroupsAndRules();
                    }
                }
            };
            item = new JMenuItem(action);
            popupMenu.add(item);
            item.setHorizontalTextPosition(JMenuItem.RIGHT);
        }
        popupMenu.add(new JSeparator());
        // remove featureStyle
        action = new AbstractAction("Remove selected FeatureTypeStyle") {

            @Override
            public void actionPerformed(ActionEvent e) {
                StyleWrapper p = currentSelectedFSW.getParent();
                p.removeFeatureTypeStyle(currentSelectedFSW);
                reloadGroupsAndRules();
            }
        };
        item = new JMenuItem(action);
        popupMenu.add(item);
        item.setHorizontalTextPosition(JMenuItem.RIGHT);
    } else if (currentSelectedRW != null && !isRaster) {
        // add rule
        AbstractAction action;
        JMenuItem item;
        if (currentSelectedRW.getGeometrySymbolizersWrapper() == null) {
            action = new AbstractAction("Add Geometry Symbolizer") {

                @Override
                public void actionPerformed(ActionEvent e) {
                    EGeometryType type = EGeometryType.forGeometryDescriptor(geometryDescriptor);
                    switch(type) {
                        case POINT:
                        case MULTIPOINT:
                            currentSelectedRW.addSymbolizer(null, PointSymbolizerWrapper.class);
                            break;
                        case LINESTRING:
                        case MULTILINESTRING:
                            currentSelectedRW.addSymbolizer(null, LineSymbolizerWrapper.class);
                            break;
                        case POLYGON:
                        case MULTIPOLYGON:
                            currentSelectedRW.addSymbolizer(null, PolygonSymbolizerWrapper.class);
                            break;
                        default:
                            break;
                    }
                    reloadGroupsAndRules();
                }
            };
            item = new JMenuItem(action);
            popupMenu.add(item);
            item.setHorizontalTextPosition(JMenuItem.RIGHT);
        }
        if (currentSelectedRW.getTextSymbolizersWrapper() == null && currentSelectedRW.getGeometrySymbolizersWrapper() != null) {
            action = new AbstractAction("Add Text Symbolizer") {

                @Override
                public void actionPerformed(ActionEvent e) {
                    currentSelectedRW.addSymbolizer(null, TextSymbolizerWrapper.class);
                    reloadGroupsAndRules();
                }
            };
            item = new JMenuItem(action);
            popupMenu.add(item);
            item.setHorizontalTextPosition(JMenuItem.RIGHT);
        }
        popupMenu.add(new JSeparator());
        // remove featureStyle
        action = new AbstractAction("Remove selected Rule") {

            @Override
            public void actionPerformed(ActionEvent e) {
                FeatureTypeStyleWrapper f = currentSelectedRW.getParent();
                f.removeRule(currentSelectedRW);
                reloadGroupsAndRules();
            }
        };
        item = new JMenuItem(action);
        popupMenu.add(item);
        item.setHorizontalTextPosition(JMenuItem.RIGHT);
    } else if (currentSelectedSymW != null && !isRaster) {
        // remove featureStyle
        AbstractAction action = new AbstractAction("Remove selected Symbolizer") {

            @Override
            public void actionPerformed(ActionEvent e) {
                RuleWrapper rw = currentSelectedSymW.getParent();
                rw.removeSymbolizerWrapper(currentSelectedSymW);
                reloadGroupsAndRules();
            }
        };
        JMenuItem item = new JMenuItem(action);
        popupMenu.add(item);
        item.setHorizontalTextPosition(JMenuItem.RIGHT);
    } else if (currentSelectedFeatureAttributeNode != null && !isRaster) {
        AbstractAction action1 = new AbstractAction("View field stats") {

            @Override
            public void actionPerformed(ActionEvent e) {
                String fieldName = currentSelectedFeatureAttributeNode.getFieldName();
                String geomName = geometryDescriptor.getLocalName();
                String[][] dataMatrix = null;
                if (geomName.equals(fieldName)) {
                    int count = 0;
                    double length = 0;
                    double area = 0;
                    for (SimpleFeature simpleFeature : currentFeaturesList) {
                        Geometry geom = (Geometry) simpleFeature.getDefaultGeometry();
                        length += geom.getLength();
                        area += geom.getArea();
                        count++;
                    }
                    SimpleFeatureCollection fl3857FC = new ReprojectingFeatureCollection(currentFeatureCollection, CrsUtilities.getCrsFromSrid(3857));
                    List<SimpleFeature> fl3857List = FeatureUtilities.featureCollectionToList(fl3857FC);
                    double length3857 = 0;
                    double area3857 = 0;
                    for (SimpleFeature simpleFeature : fl3857List) {
                        Geometry geom = (Geometry) simpleFeature.getDefaultGeometry();
                        length3857 += geom.getLength();
                        area3857 += geom.getArea();
                    }
                    DecimalFormat f = new DecimalFormat("0.0");
                    DecimalFormat fd = new DecimalFormat("0.000000");
                    dataMatrix = new String[5][2];
                    dataMatrix[0][0] = "Features count";
                    dataMatrix[0][1] = "" + count;
                    dataMatrix[1][0] = "Length (data CRS/units)";
                    dataMatrix[1][1] = fd.format(length);
                    dataMatrix[2][0] = "Area (data CRS/units)";
                    dataMatrix[2][1] = fd.format(area);
                    dataMatrix[3][0] = "Length (3857 CRS)";
                    dataMatrix[3][1] = f.format(length3857) + "m";
                    dataMatrix[4][0] = "Area (3857)";
                    dataMatrix[4][1] = f.format(area3857) + "m";
                    Dimension dimension = new Dimension(400, 200);
                    boolean modal = true;
                    String title = "Geometry stats";
                    String[] columnNames = new String[] { "", "" };
                    GuiUtilities.openDialogWithTable(title, dataMatrix, columnNames, dimension, modal);
                } else {
                    TreeMap<String, Integer> map = new TreeMap<>();
                    for (SimpleFeature simpleFeature : currentFeaturesList) {
                        Object attribute = simpleFeature.getAttribute(fieldName);
                        if (attribute != null) {
                            String attrStr = attribute.toString();
                            Integer count = map.get(attrStr);
                            if (count == null) {
                                count = 1;
                            } else {
                                count = count + 1;
                            }
                            map.put(attrStr, count);
                        }
                    }
                    int row = 0;
                    dataMatrix = new String[map.size()][2];
                    for (Entry<String, Integer> entry : map.entrySet()) {
                        String name = entry.getKey();
                        String count = String.valueOf(entry.getValue());
                        dataMatrix[row][0] = name;
                        dataMatrix[row][1] = count;
                        row++;
                    }
                    Dimension dimension = new Dimension(400, 600);
                    boolean modal = true;
                    String title = "Field stats";
                    String[] columnNames = new String[] { "value", "count" };
                    GuiUtilities.openDialogWithTable(title, dataMatrix, columnNames, dimension, modal);
                }
            }
        };
        JMenuItem item1 = new JMenuItem(action1);
        popupMenu.add(item1);
        item1.setHorizontalTextPosition(JMenuItem.RIGHT);
        AbstractAction action2 = new AbstractAction("Create unique rules based on this attribute") {

            @Override
            public void actionPerformed(ActionEvent e) {
                FeatureTypeStyleWrapper fsw = currentSelectedFSW;
                if (fsw == null) {
                    // use the first available
                    List<FeatureTypeStyleWrapper> featureTypeStylesWrapperList = styleWrapper.getFeatureTypeStylesWrapperList();
                    fsw = featureTypeStylesWrapperList.get(0);
                }
                String fieldName = currentSelectedFeatureAttributeNode.getFieldName();
                TreeSet<String> set = new TreeSet<>();
                boolean isStringAttr = false;
                for (SimpleFeature simpleFeature : currentFeaturesList) {
                    Object attribute = simpleFeature.getAttribute(fieldName);
                    if (attribute != null) {
                        String attrStr = attribute.toString();
                        set.add(attrStr);
                    }
                    if (attribute instanceof String) {
                        isStringAttr = true;
                    }
                }
                int fillAlpha = 100;
                float fillAlphaf = fillAlpha / 255f;
                ColorInterpolator interpFill = new ColorInterpolator(EColorTables.rainbow.name(), 0, set.size(), null);
                ColorInterpolator interpStroke = new ColorInterpolator(EColorTables.rainbow.name(), 0, set.size(), null);
                EGeometryType type = EGeometryType.forGeometryDescriptor(geometryDescriptor);
                // create new rules for each attribute value
                int index = 0;
                for (String value : set) {
                    try {
                        Rule rule = StyleUtilities.sf.createRule();
                        RuleWrapper rw = new RuleWrapper(rule, fsw);
                        fsw.addRule(rw);
                        String tmpName = fieldName + " == " + value;
                        tmpName = WrapperUtilities.checkSameNameRule(fsw.getRulesWrapperList(), tmpName);
                        rw.setName(tmpName);
                        String escapedValue = value.replaceAll("'", "''");
                        String filterValue = escapedValue;
                        if (isStringAttr) {
                            filterValue = "'" + escapedValue + "'";
                        }
                        Filter filter = FilterUtilities.getCQLFilter(fieldName + "=" + filterValue);
                        rule.setFilter(filter);
                        Color fill = interpFill.getColorFor(index);
                        Color stroke = interpStroke.getColorFor(index);
                        String fillHex = ColorUtilities.asHex(fill);
                        String strokeHex = ColorUtilities.asHex(stroke);
                        switch(type) {
                            case POINT:
                            case MULTIPOINT:
                                PointSymbolizerWrapper pointSW = rw.addSymbolizer(null, PointSymbolizerWrapper.class);
                                pointSW.setFillColor(fillHex);
                                pointSW.setFillOpacity(fillAlphaf + "", false);
                                pointSW.setStrokeColor(strokeHex);
                                break;
                            case LINESTRING:
                            case MULTILINESTRING:
                                LineSymbolizerWrapper lineSW = rw.addSymbolizer(null, LineSymbolizerWrapper.class);
                                lineSW.setStrokeColor(strokeHex, false);
                                break;
                            case POLYGON:
                            case MULTIPOLYGON:
                                PolygonSymbolizerWrapper polygonSW = rw.addSymbolizer(null, PolygonSymbolizerWrapper.class);
                                polygonSW.setFillColor(fillHex, false);
                                polygonSW.setFillOpacity(fillAlphaf + "", false);
                                polygonSW.setStrokeColor(strokeHex, false);
                                break;
                            default:
                                break;
                        }
                        index++;
                    } catch (Exception e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
                reloadGroupsAndRules();
                applyStyle();
            }
        };
        JMenuItem item2 = new JMenuItem(action2);
        popupMenu.add(item2);
        item2.setHorizontalTextPosition(JMenuItem.RIGHT);
    }
}
Also used : LineSymbolizerWrapper(org.hortonmachine.gears.utils.style.LineSymbolizerWrapper) ActionEvent(java.awt.event.ActionEvent) DecimalFormat(java.text.DecimalFormat) FeatureTypeStyleWrapper(org.hortonmachine.gears.utils.style.FeatureTypeStyleWrapper) RuleWrapper(org.hortonmachine.gears.utils.style.RuleWrapper) JSeparator(javax.swing.JSeparator) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) List(java.util.List) JMenuItem(javax.swing.JMenuItem) AbstractAction(javax.swing.AbstractAction) PointSymbolizerWrapper(org.hortonmachine.gears.utils.style.PointSymbolizerWrapper) RasterLayer(org.geotools.map.RasterLayer) PolygonSymbolizerWrapper(org.hortonmachine.gears.utils.style.PolygonSymbolizerWrapper) Color(java.awt.Color) Dimension(java.awt.Dimension) TreeMap(java.util.TreeMap) ColorInterpolator(org.hortonmachine.gears.utils.colors.ColorInterpolator) SimpleFeature(org.opengis.feature.simple.SimpleFeature) IOException(java.io.IOException) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) Geometry(org.locationtech.jts.geom.Geometry) TextSymbolizerWrapper(org.hortonmachine.gears.utils.style.TextSymbolizerWrapper) FeatureTypeStyleWrapper(org.hortonmachine.gears.utils.style.FeatureTypeStyleWrapper) StyleWrapper(org.hortonmachine.gears.utils.style.StyleWrapper) FileFilter(javax.swing.filechooser.FileFilter) Filter(org.opengis.filter.Filter) FeatureTypeStyle(org.geotools.styling.FeatureTypeStyle) Rule(org.geotools.styling.Rule) ReprojectingFeatureCollection(org.geotools.data.store.ReprojectingFeatureCollection) EGeometryType(org.hortonmachine.gears.utils.geometry.EGeometryType)

Example 3 with ColorInterpolator

use of org.hortonmachine.gears.utils.colors.ColorInterpolator in project hortonmachine by TheHortonMachine.

the class LasInfoController method drawPreview.

private void drawPreview(List<LasRecord> pointsToDraw) {
    try {
        ColorInterpolator colorInterp = null;
        boolean useIntensity = _intensityRadio.isSelected();
        boolean useClass = _classRadio.isSelected();
        boolean useImpulse = _impulseRadio.isSelected();
        boolean useRGB = _ownColorRadio.isSelected();
        if (!useRGB) {
            if (useIntensity) {
                colorInterp = constraints.getIntensityColorInterpolator();
            } else if (useClass) {
                colorInterp = constraints.getClassificationColorInterpolator();
            } else if (useImpulse) {
                colorInterp = constraints.getImpulseColorInterpolator();
            } else {
                colorInterp = constraints.getElevationColorInterpolator();
            }
        }
        String text = _elevHigherThanField.getText();
        double elevHigherThan = Double.NaN;
        try {
            elevHigherThan = Double.parseDouble(text.trim());
        } catch (Exception e) {
        // ignore
        }
        boolean showElevHigherThan = !Double.isNaN(elevHigherThan);
        double felevHigherThan = elevHigherThan;
        text = _intensityHigherThanField.getText();
        double intensityHigherThan = Double.NaN;
        try {
            intensityHigherThan = Double.parseDouble(text.trim());
        } catch (Exception e) {
        // ignore
        }
        boolean showIntensityHigherThan = !Double.isNaN(intensityHigherThan);
        double fintensityHigherThan = intensityHigherThan;
        text = _pointSizeField.getText();
        int pointSize = 1;
        try {
            pointSize = Integer.parseInt(text.trim());
        } catch (Exception e) {
        // ignore
        }
        int fpointSize = pointSize;
        int labelWidth = _previewImageLabel.getWidth();
        int labelHeight = _previewImageLabel.getHeight();
        int imageWidth = 500;
        int imageHeight = 500;
        if (labelWidth > 0 && labelHeight > 0) {
            imageWidth = labelWidth;
            imageHeight = labelHeight;
        }
        if (imageWidth == 0)
            imageWidth = 10;
        if (imageHeight == 0)
            imageHeight = 10;
        Envelope filteredEnvelope = constraints.getFilteredEnvelope();
        Envelope fittingEnvelope = TransformationUtils.expandToFitRatio(filteredEnvelope, imageWidth, imageHeight);
        BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = (Graphics2D) image.getGraphics();
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, imageWidth, imageHeight);
        g2d.setColor(Color.RED);
        Rectangle pixelRectangle = new Rectangle(0, 0, imageWidth, imageHeight);
        worldToPixel = TransformationUtils.getWorldToPixel(fittingEnvelope, pixelRectangle);
        pixelToWorld = TransformationUtils.getPixelToWorld(pixelRectangle, fittingEnvelope);
        ColorInterpolator fcolorInterp = colorInterp;
        Point2D toPoint = new Point2D.Double();
        Point2D fromPoint = new Point2D.Double();
        BitMatrix bm = new BitMatrix(imageWidth, imageHeight);
        List<int[]> elevHigherThanList = new ArrayList<>();
        List<int[]> intensityHigherThanList = new ArrayList<>();
        pointsToDraw.stream().forEach(lr -> {
            fromPoint.setLocation(lr.x, lr.y);
            worldToPixel.transform(fromPoint, toPoint);
            int xPix = (int) toPoint.getX();
            int yPix = (int) toPoint.getY();
            double theZ = Double.isNaN(lr.groundElevation) ? lr.z : lr.groundElevation;
            if (showElevHigherThan && theZ > felevHigherThan) {
                elevHigherThanList.add(new int[] { xPix, yPix });
            }
            if (showIntensityHigherThan && lr.intensity > fintensityHigherThan) {
                intensityHigherThanList.add(new int[] { xPix, yPix });
            }
            if (!bm.isMarked(xPix, yPix)) {
                Color c;
                if (useRGB) {
                    try {
                        c = new Color(lr.color[0], lr.color[1], lr.color[2]);
                    } catch (Exception e) {
                        c = Color.RED;
                    }
                } else {
                    if (useClass) {
                        c = fcolorInterp.getColorFor(lr.classification);
                    } else if (useIntensity) {
                        c = fcolorInterp.getColorFor(lr.intensity);
                    } else if (useImpulse) {
                        c = fcolorInterp.getColorFor(lr.returnNumber);
                    } else {
                        c = fcolorInterp.getColorFor(theZ);
                    }
                }
                g2d.setColor(c);
                if (fpointSize == 1) {
                    g2d.drawLine(xPix, yPix, xPix, yPix);
                } else {
                    g2d.fillOval(xPix - fpointSize / 2, yPix - fpointSize / 2, fpointSize, fpointSize);
                }
            }
            bm.mark(xPix, yPix);
        });
        g2d.setColor(Color.black);
        int delta = 5;
        for (int[] xy : elevHigherThanList) {
            g2d.drawLine(xy[0] - delta, xy[1], xy[0] + delta, xy[1]);
            g2d.drawLine(xy[0], xy[1] - delta, xy[0], xy[1] + delta);
        }
        g2d.setColor(Color.red);
        for (int[] xy : intensityHigherThanList) {
            g2d.drawLine(xy[0] - delta, xy[1], xy[0] + delta, xy[1]);
            g2d.drawLine(xy[0], xy[1] - delta, xy[0], xy[1] + delta);
        }
        g2d.dispose();
        lastDrawnImage = new BufferedImage(labelWidth, labelHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2dLabel = (Graphics2D) lastDrawnImage.getGraphics();
        int x = labelWidth / 2 - imageWidth / 2;
        int y = labelHeight / 2 - imageHeight / 2;
        g2dLabel.setColor(Color.WHITE);
        g2dLabel.fillRect(0, 0, labelWidth, labelHeight);
        g2dLabel.drawImage(image, x, y, null);
        g2dLabel.dispose();
        drawWithMouseBounds();
        double[] stats = constraints.getStats();
        Envelope fenv = constraints.getFilteredEnvelope();
        StringBuilder toolTip = new StringBuilder("<html>");
        int i = 0;
        toolTip.append("Filtered data stats ").append("<br>");
        toolTip.append("Points count: ").append(pointsToDraw.size()).append("<br>");
        toolTip.append("Min Elevation: ").append(stats[i++]).append("<br>");
        toolTip.append("Max Elevation: ").append(stats[i++]).append("<br>");
        toolTip.append("Min Intensity: ").append(stats[i++]).append("<br>");
        toolTip.append("Max Intensity: ").append(stats[i++]).append("<br>");
        toolTip.append("Min Classification: ").append(stats[i++]).append("<br>");
        toolTip.append("Max Classification: ").append(stats[i++]).append("<br>");
        toolTip.append("Min Impulse: ").append(stats[i++]).append("<br>");
        toolTip.append("Max Impulse: ").append(stats[i++]).append("<br>");
        double maxGroundHeight = stats[i++];
        if (!Double.isInfinite(maxGroundHeight)) {
            toolTip.append("Min ground height: ").append(maxGroundHeight).append("<br>");
            toolTip.append("Max ground height: ").append(stats[i++]).append("<br>");
        }
        toolTip.append("West: ").append(fenv.getMinX()).append("<br>");
        toolTip.append("East: ").append(fenv.getMaxX()).append("<br>");
        toolTip.append("South: ").append(fenv.getMinY()).append("<br>");
        toolTip.append("North: ").append(fenv.getMaxY()).append("<br>");
        toolTip.append("Width: ").append(fenv.getWidth()).append("<br>");
        toolTip.append("Height: ").append(fenv.getHeight()).append("<br>");
        toolTip.append("</html>");
        _previewImageLabel.setToolTipText(toolTip.toString());
    } catch (Exception e1) {
        GuiUtilities.handleError(_boundsLoadButton, e1);
    }
}
Also used : Color(java.awt.Color) Rectangle(java.awt.Rectangle) ArrayList(java.util.ArrayList) BitMatrix(org.hortonmachine.gears.utils.BitMatrix) ColorInterpolator(org.hortonmachine.gears.utils.colors.ColorInterpolator) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) Envelope(org.locationtech.jts.geom.Envelope) IOException(java.io.IOException) Point(org.locationtech.jts.geom.Point) BufferedImage(java.awt.image.BufferedImage) Graphics2D(java.awt.Graphics2D) Point2D(java.awt.geom.Point2D)

Aggregations

Color (java.awt.Color)3 ArrayList (java.util.ArrayList)3 ColorInterpolator (org.hortonmachine.gears.utils.colors.ColorInterpolator)3 Graphics2D (java.awt.Graphics2D)2 Rectangle (java.awt.Rectangle)2 Point2D (java.awt.geom.Point2D)2 BufferedImage (java.awt.image.BufferedImage)2 IOException (java.io.IOException)2 ReferencedEnvelope (org.geotools.geometry.jts.ReferencedEnvelope)2 Geometry (org.locationtech.jts.geom.Geometry)2 AVList (gov.nasa.worldwind.avlist.AVList)1 AVListImpl (gov.nasa.worldwind.avlist.AVListImpl)1 LatLon (gov.nasa.worldwind.geom.LatLon)1 Sector (gov.nasa.worldwind.geom.Sector)1 MercatorSector (gov.nasa.worldwind.layers.mercator.MercatorSector)1 LevelSet (gov.nasa.worldwind.util.LevelSet)1 Tile (gov.nasa.worldwind.util.Tile)1 TileUrlBuilder (gov.nasa.worldwind.util.TileUrlBuilder)1 Dimension (java.awt.Dimension)1 ActionEvent (java.awt.event.ActionEvent)1