This is an automated email from the ASF dual-hosted git repository. asf-gitbox-commits pushed a commit to branch geoapi-4.0 in repository https://gitbox.apache.org/repos/asf/sis.git
commit fda63f630e112f4b6a3343d282f60151d23ed00b Author: jsorel <[email protected]> AuthorDate: Wed Nov 18 12:11:28 2026 +0100 refactor(Portrayal): move hillshading in common module --- .../sis/map/service/common/GroundSpacing.java | 133 ++++++++++ .../apache/sis/map/service/common/HillShader.java | 271 +++++++++++++++++++++ .../sis/map/service/common/package-info.java | 25 ++ .../sis/map/service/se1/RasterToScene2D.java | 18 +- .../apache/sis/map/service/se1/ReliefShading.java | 116 --------- .../sis/map/service/common/HillShaderTest.java | 125 ++++++++++ 6 files changed, 564 insertions(+), 124 deletions(-) diff --git a/incubator/src/org.apache.sis.portrayal.map/main/org/apache/sis/map/service/common/GroundSpacing.java b/incubator/src/org.apache.sis.portrayal.map/main/org/apache/sis/map/service/common/GroundSpacing.java new file mode 100644 index 0000000000..c0dc5114ec --- /dev/null +++ b/incubator/src/org.apache.sis.portrayal.map/main/org/apache/sis/map/service/common/GroundSpacing.java @@ -0,0 +1,133 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.sis.map.service.common; + +import java.util.Arrays; +import java.util.logging.Level; +import javax.measure.IncommensurableException; +import javax.measure.Unit; +import org.apache.sis.coverage.grid.GridExtent; +import org.apache.sis.coverage.grid.GridGeometry; +import org.apache.sis.coverage.grid.PixelInCell; +import org.apache.sis.geometry.GeneralDirectPosition; +import org.apache.sis.map.service.Scene2D; +import org.apache.sis.measure.Units; +import org.apache.sis.referencing.GeodeticCalculator; + +// Specific to the geoapi-3.1 and geoapi-4.0 branches: +import org.opengis.referencing.crs.CoordinateReferenceSystem; +import org.opengis.referencing.operation.MathTransform; +import org.opengis.referencing.operation.TransformException; + + +/** + * Ground distances in metres between the centers of neighbouring cells of a two-dimensional grid, for each row. + * The distances are measured at the middle column of each row: + * + * <ul> + * <li>with the axis unit if the axes are linear (projection distortions are ignored),</li> + * <li>as geodesic distances on the ellipsoid of the CRS otherwise.</li> + * </ul> + * + * If a distance cannot be computed, it is 1 (the values are then measured in cells). + * + * @author Johann Sorel (Geomatys) + */ +final class GroundSpacing { + /** + * Distance between the centers of horizontally adjacent cells, for each row. + */ + private final double[] columns; + + /** + * Distance between the centers of vertically adjacent cells, for each row. + */ + private final double[] rows; + + /** + * Computes the distances of the given grid. + * + * @param grid the two-dimensional grid. + */ + GroundSpacing(final GridGeometry grid) { + final GridExtent extent = grid.getExtent(); + final int height = Math.toIntExact(extent.getSize(1)); + columns = new double[height]; + rows = new double[height]; + try { + final CoordinateReferenceSystem crs = grid.getCoordinateReferenceSystem(); + final MathTransform gridToCRS = grid.getGridToCRS(PixelInCell.CELL_CENTER); + final Unit<?> unit = crs.getCoordinateSystem().getAxis(0).getUnit(); + final GeodeticCalculator calculator = Units.isLinear(unit) ? null : GeodeticCalculator.create(crs); + final double x = extent.getMedian(0); + for (int y=0; y<height; y++) { + final double gy = extent.getLow(1) + y; + final double[] points = {x, gy, x + 1, gy, x, gy + 1}; + gridToCRS.transform(points, 0, points, 0, 3); + if (calculator != null) { + columns[y] = geodesic(calculator, crs, points, 2); + rows[y] = geodesic(calculator, crs, points, 4); + } else { + final double toMetres = unit.getConverterToAny(Units.METRE).convert(1); + columns[y] = toMetres * Math.hypot(points[2] - points[0], points[3] - points[1]); + rows[y] = toMetres * Math.hypot(points[4] - points[0], points[5] - points[1]); + } + } + } catch (TransformException | IncommensurableException | RuntimeException e) { + Scene2D.LOGGER.log(Level.FINE, "Cannot compute the ground size of the cells.", e); + Arrays.fill(columns, 1); + Arrays.fill(rows, 1); + } + } + + /** + * Returns the geodesic distance in metres from the first point to the point at the given offset. + */ + private double geodesic(final GeodeticCalculator calculator, final CoordinateReferenceSystem crs, + final double[] points, final int offset) throws IncommensurableException + { + final GeneralDirectPosition start = new GeneralDirectPosition(crs); + final GeneralDirectPosition end = new GeneralDirectPosition(crs); + start.setCoordinate(0, points[0]); + start.setCoordinate(1, points[1]); + end.setCoordinate(0, points[offset]); + end.setCoordinate(1, points[offset + 1]); + calculator.setStartPoint(start); + calculator.setEndPoint(end); + return calculator.getDistanceUnit().getConverterToAny(Units.METRE).convert(calculator.getGeodesicDistance()); + } + + /** + * Returns the distance between the centers of horizontally adjacent cells. + * + * @param row the row index. + * @return the distance in metres. + */ + double column(final int row) { + return columns[row]; + } + + /** + * Returns the distance between the centers of vertically adjacent cells. + * + * @param row the row index. + * @return the distance in metres. + */ + double row(final int row) { + return rows[row]; + } +} diff --git a/incubator/src/org.apache.sis.portrayal.map/main/org/apache/sis/map/service/common/HillShader.java b/incubator/src/org.apache.sis.portrayal.map/main/org/apache/sis/map/service/common/HillShader.java new file mode 100644 index 0000000000..c4172409ec --- /dev/null +++ b/incubator/src/org.apache.sis.portrayal.map/main/org/apache/sis/map/service/common/HillShader.java @@ -0,0 +1,271 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.sis.map.service.common; + +import java.awt.image.BufferedImage; +import org.apache.sis.coverage.grid.GridGeometry; +import org.apache.sis.util.ArgumentChecks; + + +/** + * Hill shading (or relief shading) of an elevation grid, for a light coming from the sun. + * The shader is configured with builder methods, then computes the shade of each cell or an overlay image: + * + * {@snippet lang="java" : + * BufferedImage overlay = new HillShader(elevations, width, height) + * .setGrid(grid) + * .setFactor(55) + * .setSun(315, 45) + * .createOverlay(); + * } + * + * The terrain slopes are computed with the Horn algorithm (weighted differences over the 3×3 neighbourhood) + * divided by the ground distances between the cell centers. The shade is the cosine of the angle between the + * terrain normal and the direction of the sun. + * + * <ul> + * <li>The grid is assumed oriented with north up: rows go southward and columns eastward.</li> + * <li>The elevations and the ground distances are in metres. Without grid, the ground distances are 1.</li> + * <li>A neighbour without elevation, or outside the grid, is extrapolated from the other neighbours, + * so that the slopes of a plane are exact up to the borders of the data.</li> + * <li>A flat cell has the shade sin(sun elevation).</li> + * </ul> + * + * @see "OGC 18-067r4 section 10.2.2" + * @see org.apache.sis.style.se1.ShadedRelief + * + * @author Johann Sorel (Geomatys) + */ +public final class HillShader { + /** + * Default azimuth of the sun, in degrees clockwise from north. + * This is the north-west, the usual cartographic convention. + */ + public static final double DEFAULT_AZIMUTH = 315; + + /** + * Default elevation of the sun, in degrees above the ground. + */ + public static final double DEFAULT_ELEVATION = 45; + + /** + * Maximal alpha of the white pixels lightening the slopes facing the sun in the overlay. + * Lower than 1 for avoiding to wash out the colors. + */ + private static final double HIGHLIGHT = 0.5; + + /** + * Elevation of each cell in row-major order, NaN if none. + */ + private final double[] elevations; + + /** + * Number of cells in a row and number of rows. + */ + private final int width, height; + + /** + * Ground distances between the cell centers, or {@code null} for distances of 1. + */ + private GroundSpacing spacing; + + /** + * Exaggeration of the relief, multiplying the slopes. + */ + private double factor; + + /** + * Components of the unit vector toward the sun, in the grid space (x eastward, y southward, z up). + */ + private double sunX, sunY, sunZ; + + /** + * Creates a shader of the given elevations, with a factor of 1 and the default sun position. + * + * @param elevations elevation of each cell in metres, in row-major order, NaN if none. + * @param width number of cells in a row. + * @param height number of rows. + * @throws IllegalArgumentException if the length of the array is not {@code width} × {@code height}. + */ + public HillShader(final double[] elevations, final int width, final int height) { + ArgumentChecks.ensureNonNull("elevations", elevations); + ArgumentChecks.ensureStrictlyPositive("width", width); + ArgumentChecks.ensureStrictlyPositive("height", height); + if (elevations.length != width * height) { + throw new IllegalArgumentException("Expected " + width * height + " elevations but got " + elevations.length + '.'); + } + this.elevations = elevations; + this.width = width; + this.height = height; + factor = 1; + setSun(DEFAULT_AZIMUTH, DEFAULT_ELEVATION); + } + + /** + * Sets the grid of the elevations, for computing the ground distances between the cell centers. + * The distances are geodesic if the axes are not linear. + * + * @param grid the two-dimensional grid of the elevations. + * @return this shader. + */ + public HillShader setGrid(final GridGeometry grid) { + spacing = new GroundSpacing(grid); + return this; + } + + /** + * Sets the exaggeration of the relief. + * + * @param factor the factor multiplying the slopes. The default is 1. + * @return this shader. + * + * @see "OGC 18-067r4 section 10.2.2.1" + */ + public HillShader setFactor(final double factor) { + ArgumentChecks.ensureFinite("factor", factor); + this.factor = factor; + return this; + } + + /** + * Sets the position of the sun. + * + * @param azimuth direction of the sun in degrees clockwise from north. The default is 315°. + * @param elevation angle of the sun in degrees above the ground. The default is 45°. + * @return this shader. + * + * @see "OGC 18-067r4 section 10.2.2.2" + * @see "OGC 18-067r4 section 10.2.2.3" + */ + public HillShader setSun(final double azimuth, final double elevation) { + ArgumentChecks.ensureFinite("azimuth", azimuth); + ArgumentChecks.ensureFinite("elevation", elevation); + final double a = Math.toRadians(azimuth); + final double e = Math.toRadians(elevation); + sunX = Math.sin(a) * Math.cos(e); + sunY = -Math.cos(a) * Math.cos(e); + sunZ = Math.sin(e); + return this; + } + + /** + * Returns the shade of a cell. + * + * @param cell index of the cell in row-major order. + * @return the shade between 0 (full shade) and 1 (facing the sun), or NaN if the cell has no elevation. + */ + public double shade(final int cell) { + final double z = elevations[cell]; + if (Double.isNaN(z)) { + return Double.NaN; + } + final int x = cell % width; + final int y = cell / width; + final double a = neighbour(x, y, -1, -1, z), b = neighbour(x, y, 0, -1, z), c = neighbour(x, y, +1, -1, z); + final double d = neighbour(x, y, -1, 0, z), f = neighbour(x, y, +1, 0, z); + final double g = neighbour(x, y, -1, +1, z), h = neighbour(x, y, 0, +1, z), i = neighbour(x, y, +1, +1, z); + final double p = factor * ((c + 2*f + i) - (a + 2*d + g)) / (8 * distance(spacing != null ? spacing.column(y) : 1)); + final double q = factor * ((g + 2*h + i) - (a + 2*b + c)) / (8 * distance(spacing != null ? spacing.row(y) : 1)); + /* + * The terrain normal is (−p, −q, 1) before normalization, + * where p and q are the slopes along the x and y axes of the grid. + */ + final double shade = (sunZ - p*sunX - q*sunY) / Math.sqrt(p*p + q*q + 1); + return Math.max(0, Math.min(1, shade)); + } + + /** + * Computes an overlay to paint over the colors to shade. + * Flat cells and cells without elevation are fully transparent. + * Cells less lit than a flat cell are darkened by black pixels with an alpha proportional to the shadow, + * and cells more lit than a flat cell are lightened by white pixels with an alpha proportional to the extra light. + * Painting this overlay with the {@code SRC_OVER} rule multiplies the brightness of darkened colors + * by the ratio between the light received by the cell and the light received by a flat cell. + * + * @return the overlay of {@code width} × {@code height} pixels. + */ + public BufferedImage createOverlay() { + final double flat = Math.max(0, sunZ); + final int[] argb = new int[elevations.length]; + for (int cell = 0; cell < argb.length; cell++) { + final double shade = shade(cell); + if (Double.isNaN(shade)) { + continue; + } + if (shade < flat) { + argb[cell] = alpha(1 - shade / flat); // Black. + } else if (flat < 1) { + argb[cell] = alpha(HIGHLIGHT * (shade - flat) / (1 - flat)) | 0xFFFFFF; // White. + } + } + final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); + image.setRGB(0, 0, width, height, argb, 0, width); + return image; + } + + /** + * Returns the elevation of a neighbour of a cell. If the neighbour has no elevation or is outside the grid, + * the elevation is extrapolated linearly from the opposite neighbour. If the opposite neighbour is also missing, + * a diagonal neighbour is extrapolated from its two adjacent neighbours, and other neighbours take the center + * elevation. Those rules give the exact elevations on a plane. + * + * @param x column of the center cell. + * @param y row of the center cell. + * @param dx column offset of the neighbour. + * @param dy row offset of the neighbour. + * @param center elevation of the center cell. + * @return the elevation of the neighbour. + */ + private double neighbour(final int x, final int y, final int dx, final int dy, final double center) { + final double value = elevation(x + dx, y + dy); + if (!Double.isNaN(value)) { + return value; + } + final double opposite = elevation(x - dx, y - dy); + if (!Double.isNaN(opposite)) { + return 2*center - opposite; + } + if (dx != 0 && dy != 0) { + return neighbour(x, y, dx, 0, center) + neighbour(x, y, 0, dy, center) - center; + } + return center; + } + + /** + * Returns the elevation of the cell at the given position, or NaN if none or outside the grid. + */ + private double elevation(final int x, final int y) { + if (x < 0 || x >= width || y < 0 || y >= height) { + return Double.NaN; + } + return elevations[y * width + x]; + } + + /** + * Returns the given ground distance, or 1 if the distance is not positive. + */ + private double distance(final double value) { + return (value > 0) ? value : 1; + } + + /** + * Returns the given alpha value in [0 … 1] as the alpha bits of an ARGB value. + */ + private int alpha(final double alpha) { + return (int) Math.round(Math.max(0, Math.min(1, alpha)) * 255) << 24; + } +} diff --git a/incubator/src/org.apache.sis.portrayal.map/main/org/apache/sis/map/service/common/package-info.java b/incubator/src/org.apache.sis.portrayal.map/main/org/apache/sis/map/service/common/package-info.java new file mode 100644 index 0000000000..00d6ae4d07 --- /dev/null +++ b/incubator/src/org.apache.sis.portrayal.map/main/org/apache/sis/map/service/common/package-info.java @@ -0,0 +1,25 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Rendering support shared by the Symbology Encoding and the CartoSym painters. + * Classes of this package work on values which are already evaluated, such as elevations in metres + * or angles in degrees, and do not depend on the model of a style. + * + * @author Johann Sorel (Geomatys) + */ +package org.apache.sis.map.service.common; diff --git a/incubator/src/org.apache.sis.portrayal.map/main/org/apache/sis/map/service/se1/RasterToScene2D.java b/incubator/src/org.apache.sis.portrayal.map/main/org/apache/sis/map/service/se1/RasterToScene2D.java index aa17036ffb..484358f2a6 100644 --- a/incubator/src/org.apache.sis.portrayal.map/main/org/apache/sis/map/service/se1/RasterToScene2D.java +++ b/incubator/src/org.apache.sis.portrayal.map/main/org/apache/sis/map/service/se1/RasterToScene2D.java @@ -63,6 +63,7 @@ import org.apache.sis.map.Presentation; import org.apache.sis.map.SEPresentation; import org.apache.sis.map.service.Scene2D; import org.apache.sis.map.service.RenderingException; +import org.apache.sis.map.service.common.HillShader; import org.apache.sis.measure.Units; import org.apache.sis.storage.Aggregate; import org.apache.sis.storage.DataStoreException; @@ -105,7 +106,7 @@ import org.apache.sis.style.se1.Symbolizer; * of the coverages if all of them have a temporal extent, or to the rendering order otherwise.</li> * <li>ImageOutline: the footprint of each coverage is drawn with the given line or polygon symbolizer.</li> * <li>ShadedRelief: hill shading of the elevations given by the gray channel, the color map band or the first band, - * see {@link ReliefShading}. Elevations are multiplied by the relief factor, and converted to metres if their + * see {@link HillShader}. The relief factor multiplies the slopes, and elevations are converted to metres if their * unit is linear (metres are assumed otherwise). The colors of the raster are shaded, or if brightness only * is true, the raster colors are not painted and the shading is applied on the canvas painted so far.</li> * </ul> @@ -150,7 +151,7 @@ public final class RasterToScene2D extends SymbolizerToScene2D<RasterSymbolizer< colorize(rasters, feature); BufferedImage image = compose(rasters); if (reliefFactor > 0) { - image = shade(image, rasters, feature); + image = shade(image, rasters, feature, reliefFactor); } if (image != null) { final double opacity = StrokeStyle.clamp(evaluateNumber(feature, symbolizer.getOpacity(), 1.0)); @@ -247,7 +248,7 @@ public final class RasterToScene2D extends SymbolizerToScene2D<RasterSymbolizer< double[][] values; /** Non-zero for display pixels inside the footprint, or {@code null} if unknown. */ byte[] inside; - /** Elevations in metres multiplied by the relief factor, or {@code null} if no relief shading. */ + /** Elevations in metres, or {@code null} if no relief shading. */ double[] elevations; /** The colorized image of the display size, computed by {@code colorize(…)}. */ BufferedImage image; @@ -314,7 +315,7 @@ public final class RasterToScene2D extends SymbolizerToScene2D<RasterSymbolizer< processor.setInterpolation(Interpolation.BILINEAR); final RenderedImage image = processor.resample(converted, state.grid).render(null); final double[] z = samples(image, new int[] {bands[0]}, raster.inside)[0]; - final double scale = reliefFactor * toMetres(sampleDimensions.get(bands[0])); + final double scale = toMetres(sampleDimensions.get(bands[0])); for (int i = 0; i < z.length; i++) z[i] *= scale; raster.elevations = z; } @@ -708,10 +709,11 @@ public final class RasterToScene2D extends SymbolizerToScene2D<RasterSymbolizer< * Applies the relief shading on the colors of the given image. If the shading shall be applied * on the brightness of the canvas painted so far by other layers, returns the shading alone. * - * @param image the colorized rasters, or {@code null} if none. + * @param image the colorized rasters, or {@code null} if none. + * @param reliefFactor the relief shading exaggeration. * @return the image to paint, or {@code null} if none. */ - private BufferedImage shade(BufferedImage image, List<DisplayRaster> rasters, Feature feature) throws RenderingException { + private BufferedImage shade(BufferedImage image, List<DisplayRaster> rasters, Feature feature, double reliefFactor) { double[] elevations = null; for (DisplayRaster raster : rasters) { // Rasters painted later overwrite the previous ones. final double[] z = raster.elevations; @@ -726,8 +728,8 @@ public final class RasterToScene2D extends SymbolizerToScene2D<RasterSymbolizer< return image; } final GridExtent extent = state.grid.getExtent(); - final BufferedImage overlay = ReliefShading.overlay(elevations, (int) extent.getSize(0), (int) extent.getSize(1), - 1 / state.getPixelsPerUnit(Units.METRE)); + final BufferedImage overlay = new HillShader(elevations, (int) extent.getSize(0), (int) extent.getSize(1)) + .setGrid(state.grid).setFactor(reliefFactor).createOverlay(); if (evaluateBoolean(feature, symbolizer.getShadedRelief().get().isBrightnessOnly(), false)) { return overlay; } diff --git a/incubator/src/org.apache.sis.portrayal.map/main/org/apache/sis/map/service/se1/ReliefShading.java b/incubator/src/org.apache.sis.portrayal.map/main/org/apache/sis/map/service/se1/ReliefShading.java deleted file mode 100644 index dc044271c7..0000000000 --- a/incubator/src/org.apache.sis.portrayal.map/main/org/apache/sis/map/service/se1/ReliefShading.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.sis.map.service.se1; - -import java.awt.image.BufferedImage; - - -/** - * Relief shading (or “hill shading”) of an elevation model in display space. - * The shading is computed with the slopes given by the Horn algorithm (3×3 neighborhood) - * and a light coming from the upper-left corner of the display (azimuth 315°) at an altitude of 45°, - * which is the usual cartographic convention. - * - * <p>The result is an overlay image to paint over the colors to shade: flat areas are fully transparent, - * slopes facing away from the light are darkened by black pixels with an alpha proportional to the shadow, - * and slopes facing the light are lightened by white pixels with an alpha proportional to the extra light. - * Painting this overlay with the {@code SRC_OVER} rule multiplies the brightness of darkened colors - * by the ratio between the light received by the slope and the light received by a flat area.</p> - * - * @author Johann Sorel (Geomatys) - */ -final class ReliefShading { - - /** - * Components of the unit vector toward the light, in display space (x right, y down, z up). - * The light comes from azimuth 315° (north-west, upper-left of the display) at an altitude of 45°. - */ - private static final double LIGHT_X = -0.5, LIGHT_Y = -0.5, LIGHT_Z = Math.sqrt(0.5); - - /** - * Maximal alpha of the white pixels lightening the slopes facing the light. - * Lower than 1 for avoiding to wash out the colors. - */ - private static final double HIGHLIGHT = 0.5; - - private ReliefShading() { - } - - /** - * Computes the shading overlay of the given elevations. - * - * @param elevations elevations in metres, already multiplied by the relief factor, - * in row-major order. NaN values are not shaded. - * @param width number of display pixels in a row. - * @param height number of display pixels in a column. - * @param cellSize ground size of a display pixel, in metres. - * @return the overlay to paint over the colors to shade. - */ - static BufferedImage overlay(final double[] elevations, final int width, final int height, final double cellSize) { - final int[] argb = new int[width * height]; - for (int y = 0; y < height; y++) { - final int row0 = Math.max(y - 1, 0) * width; - final int row1 = y * width; - final int row2 = Math.min(y + 1, height - 1) * width; - final int spanY = (row2 - row0) / width; - for (int x = 0; x < width; x++) { - final double e = elevations[row1 + x]; - if (Double.isNaN(e)) continue; - final int x0 = Math.max(x - 1, 0); - final int x2 = Math.min(x + 1, width - 1); - final double a = at(elevations, row0 + x0, e), b = at(elevations, row0 + x, e), c = at(elevations, row0 + x2, e); - final double d = at(elevations, row1 + x0, e), f = at(elevations, row1 + x2, e); - final double g = at(elevations, row2 + x0, e), h = at(elevations, row2 + x, e), i = at(elevations, row2 + x2, e); - /* - * Horn algorithm: weighted differences over the 3×3 neighborhood. The spans are 2 pixels, - * except on the image borders where the neighborhood is truncated. - */ - final int spanX = x2 - x0; - final double p = (spanX == 0) ? 0 : ((c + 2*f + i) - (a + 2*d + g)) / (4 * spanX * cellSize); // ∂z/∂x - final double q = (spanY == 0) ? 0 : ((g + 2*h + i) - (a + 2*b + c)) / (4 * spanY * cellSize); // ∂z/∂y - /* - * The surface normal is (−p, −q, 1) before normalization. - * The shade is the cosine of the angle between the normal and the light direction. - */ - final double shade = Math.max(0, (LIGHT_Z - p*LIGHT_X - q*LIGHT_Y) / Math.sqrt(p*p + q*q + 1)); - if (shade < LIGHT_Z) { - argb[row1 + x] = alpha(1 - shade / LIGHT_Z); // Black. - } else { - argb[row1 + x] = alpha(HIGHLIGHT * (shade - LIGHT_Z) / (1 - LIGHT_Z)) | 0xFFFFFF; // White. - } - } - } - final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - image.setRGB(0, 0, width, height, argb, 0, width); - return image; - } - - /** - * Returns the elevation at the given index, or the given fallback if the elevation is missing. - */ - private static double at(final double[] elevations, final int index, final double fallback) { - final double value = elevations[index]; - return Double.isNaN(value) ? fallback : value; - } - - /** - * Returns the given alpha value in [0 … 1] as the alpha bits of an ARGB value. - */ - private static int alpha(final double alpha) { - return (int) Math.round(Math.max(0, Math.min(1, alpha)) * 255) << 24; - } -} diff --git a/incubator/src/org.apache.sis.portrayal.map/test/org/apache/sis/map/service/common/HillShaderTest.java b/incubator/src/org.apache.sis.portrayal.map/test/org/apache/sis/map/service/common/HillShaderTest.java new file mode 100644 index 0000000000..ab00ef3b58 --- /dev/null +++ b/incubator/src/org.apache.sis.portrayal.map/test/org/apache/sis/map/service/common/HillShaderTest.java @@ -0,0 +1,125 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.sis.map.service.common; + +import java.awt.image.BufferedImage; +import org.apache.sis.coverage.grid.GridExtent; +import org.apache.sis.coverage.grid.GridGeometry; +import org.apache.sis.coverage.grid.GridOrientation; +import org.apache.sis.geometry.Envelope2D; +import org.apache.sis.referencing.CommonCRS; + +// Test dependencies +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + + +/** + * Tests {@link HillShader}. + * + * @author Johann Sorel (Geomatys) + */ +public final class HillShaderTest { + /** + * Length of one degree of longitude at the equator on the WGS84 ellipsoid, in metres. + */ + private static final double DEGREE = 111319.49079327357; + + /** + * Creates a new test case. + */ + public HillShaderTest() { + } + + /** + * Returns the elevations of a plane of 5×5 cells with the given slopes, in metres per cell. + */ + private static double[] plane(final double east, final double south) { + final double[] z = new double[25]; + for (int i = 0; i < z.length; i++) { + z[i] = 1000 + (i % 5) * east + (i / 5) * south; + } + return z; + } + + /** + * Tests the shade of flat and sloping terrains with the default sun in the north-west. + */ + @Test + public void testShade() { + final double flat = Math.sin(Math.toRadians(HillShader.DEFAULT_ELEVATION)); + assertEquals(flat, new HillShader(plane(0, 0), 5, 5).shade(12), 1E-12, "Flat terrain."); + + final double facingWest = new HillShader(plane(1, 0), 5, 5).shade(12); + final double facingEast = new HillShader(plane(-1, 0), 5, 5).shade(12); + assertEquals((flat + 0.5) / Math.sqrt(2), facingWest, 1E-12, "Slope of 1 facing west."); + assertEquals((flat - 0.5) / Math.sqrt(2), facingEast, 1E-12, "Slope of 1 facing east."); + + assertEquals(facingWest, new HillShader(plane(1, 0), 5, 5).shade(0), 1E-12, "Corner cell of a plane."); + assertEquals(new HillShader(plane(1, 2), 5, 5).shade(12), new HillShader(plane(1, 2), 5, 5).shade(24), 1E-12, + "Corner cell of an oblique plane."); + assertEquals(flat, new HillShader(plane(1, 0), 5, 5).setFactor(0).shade(12), 1E-12, "No relief exaggeration."); + assertEquals(facingEast, new HillShader(plane(1, 0), 5, 5).setSun(45, 45).shade(12), 1E-12, "Sun in the north-east."); + assertEquals(new HillShader(plane(2, 0), 5, 5).shade(12), new HillShader(plane(1, 0), 5, 5).setFactor(2).shade(12), + 1E-12, "The factor multiplies the slopes."); + } + + /** + * Tests the extrapolation of neighbours without elevation. + */ + @Test + public void testMissingElevations() { + final double[] z = plane(1, 2); + final double expected = new HillShader(z, 5, 5).shade(12); + z[11] = Double.NaN; // West neighbour of the center. + z[6] = Double.NaN; // North-west neighbour of the center. + assertEquals(expected, new HillShader(z, 5, 5).shade(12), 1E-12, "The plane shall be extrapolated."); + assertTrue(Double.isNaN(new HillShader(z, 5, 5).shade(11)), "Cell without elevation."); + assertThrows(IllegalArgumentException.class, () -> new HillShader(z, 4, 5)); + } + + /** + * Tests the ground distances computed from a geographic grid. + */ + @Test + public void testGeographicGrid() { + final GridGeometry grid = new GridGeometry(new GridExtent(3, 3), + new Envelope2D(CommonCRS.WGS84.normalizedGeographic(), -1.5, -1.5, 3, 3), GridOrientation.REFLECTION_Y); + final double[] z = new double[9]; + for (int i = 0; i < z.length; i++) { + z[i] = (i % 3) * DEGREE; // Slope of 1 eastward at the equator. + } + final double flat = Math.sin(Math.toRadians(HillShader.DEFAULT_ELEVATION)); + assertEquals((flat + 0.5) / Math.sqrt(2), new HillShader(z, 3, 3).setGrid(grid).shade(4), 1E-6); + } + + /** + * Tests the overlay image: transparent on flat terrain, black on shadows and white on lit slopes. + */ + @Test + public void testOverlay() { + assertEquals(0, new HillShader(plane(0, 0), 5, 5).createOverlay().getRGB(2, 2) >>> 24, "Flat terrain is transparent."); + + final BufferedImage lit = new HillShader(plane(1, 0), 5, 5).createOverlay(); + assertEquals(0xFFFFFF, lit.getRGB(2, 2) & 0xFFFFFF, "White highlight."); + assertTrue((lit.getRGB(2, 2) >>> 24) > 0); + + final BufferedImage shadowed = new HillShader(plane(-1, 0), 5, 5).createOverlay(); + assertEquals(0, shadowed.getRGB(2, 2) & 0xFFFFFF, "Black shadow."); + assertTrue((shadowed.getRGB(2, 2) >>> 24) > 0); + } +}
