001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.osm.visitor.paint;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.AlphaComposite;
007import java.awt.Color;
008import java.awt.Font;
009import java.awt.Graphics2D;
010import java.awt.GraphicsConfiguration;
011import java.awt.Image;
012import java.awt.Point;
013import java.awt.RenderingHints;
014import java.awt.Transparency;
015import java.awt.event.MouseEvent;
016import java.awt.image.BufferedImage;
017import java.util.ArrayList;
018import java.util.Collection;
019import java.util.Comparator;
020import java.util.IntSummaryStatistics;
021import java.util.List;
022import java.util.Map;
023import java.util.Objects;
024import java.util.Set;
025import java.util.function.Consumer;
026import java.util.stream.Collectors;
027
028import org.apache.commons.jcs3.access.CacheAccess;
029import org.openstreetmap.josm.data.Bounds;
030import org.openstreetmap.josm.data.coor.LatLon;
031import org.openstreetmap.josm.data.osm.OsmData;
032import org.openstreetmap.josm.data.projection.ProjectionRegistry;
033import org.openstreetmap.josm.gui.MainApplication;
034import org.openstreetmap.josm.gui.MapView;
035import org.openstreetmap.josm.gui.NavigatableComponent;
036import org.openstreetmap.josm.spi.preferences.Config;
037import org.openstreetmap.josm.tools.Logging;
038
039/**
040 * A styled render that does the rendering on a tile basis. Note: this is currently experimental!
041 * It may be extracted to an interface at a later date.
042 * @since 19176
043 */
044public final class StyledTiledMapRenderer extends StyledMapRenderer {
045    // Render to the surrounding tiles for continuity -- this probably needs to be tweaked
046    private static final int BUFFER_TILES = 2;
047    // The number of extra pixels to render per tile (avoids black lines in render result)
048    private static final int BUFFER_PIXELS = 16;
049    private CacheAccess<TileZXY, ImageCache> cache;
050    private int zoom;
051    private Consumer<TileZXY> notifier;
052
053    /**
054     * Constructs a new {@code StyledMapRenderer}.
055     *
056     * @param g              the graphics context. Must not be null.
057     * @param nc             the map viewport. Must not be null.
058     * @param isInactiveMode if true, the paint visitor shall render OSM objects such that they
059     *                       look inactive. Example: rendering of data in an inactive layer using light gray as color only.
060     * @throws IllegalArgumentException if {@code g} is null
061     * @throws IllegalArgumentException if {@code nc} is null
062     */
063    public StyledTiledMapRenderer(Graphics2D g, NavigatableComponent nc, boolean isInactiveMode) {
064        super(g, nc, isInactiveMode);
065    }
066
067    @Override
068    public void render(OsmData<?, ?, ?, ?> data, boolean renderVirtualNodes, Bounds bounds) {
069        // If there is no cache, fall back to old behavior
070        if (this.cache == null) {
071            super.render(data, renderVirtualNodes, bounds);
072            return;
073        }
074        final BufferedImage tempImage;
075        final Graphics2D tempG2d;
076        // I'd like to avoid two image copies, but there are some issues using the original g2d object
077        tempImage = createCompatibleImage(nc, this.nc.getWidth(), this.nc.getHeight());
078        tempG2d = tempImage.createGraphics();
079        tempG2d.setComposite(AlphaComposite.DstAtop); // Avoid tile lines in large areas
080
081        final List<TileZXY> toRender = TileZXY.boundsToTiles(bounds.getMinLat(), bounds.getMinLon(),
082                bounds.getMaxLat(), bounds.getMaxLon(), zoom).collect(Collectors.toList());
083        final Bounds box = new Bounds(bounds);
084        toRender.stream().map(TileZXY::tileToBounds).forEach(box::extend);
085        final int tileSize;
086        if (toRender.isEmpty()) {
087            tileSize = Config.getPref().getInt("mappaint.fast_render.tile_size", 256); // Mostly to keep the compiler happy
088        } else {
089            final TileZXY tile = toRender.get(0);
090            final Bounds box2 = TileZXY.tileToBounds(tile);
091            final Point min = this.nc.getPoint(box2.getMin());
092            final Point max = this.nc.getPoint(box2.getMax());
093            tileSize = max.x - min.x;
094        }
095
096        // Sort the tiles based off of proximity to the mouse pointer
097        if (nc instanceof MapView) { // Ideally this would either be an interface or a method in NavigableComponent
098            final MapView mv = (MapView) nc;
099            final MouseEvent mouseEvent = mv.lastMEvent;
100            final LatLon mousePosition = nc.getLatLon(mouseEvent.getX(), mouseEvent.getY());
101            final TileZXY mouseTile = TileZXY.latLonToTile(mousePosition.lat(), mousePosition.lon(), zoom);
102            toRender.sort(Comparator.comparingInt(tile -> {
103                final int x = tile.x() - mouseTile.x();
104                final int y = tile.y() - mouseTile.y();
105                return x * x + y * y;
106            }));
107        }
108
109        // We want to prioritize where the mouse is, but having some in the queue will reduce overall paint time
110        int submittedTile = 5;
111        int painted = 0;
112        for (TileZXY tile : toRender) {
113            final Image tileImage;
114            // Needed to avoid having tiles that aren't rendered properly
115            final ImageCache tImg = this.cache.get(tile);
116            final boolean wasDirty = tImg != null && tImg.isDirty();
117            if (tImg != null && !tImg.isDirty() && tImg.imageFuture() != null) {
118                submittedTile = 0; // Don't submit new tiles if there are futures already in the queue. Not perfect.
119            }
120            if (submittedTile > 0 && (tImg == null || tImg.isDirty())) {
121                // Ensure that we don't add a large number of render calls
122                if (tImg != null && tImg.imageFuture() != null) {
123                    tImg.imageFuture().cancel();
124                }
125                submittedTile--;
126                // Note that the paint code is *not* thread safe, so all tiles must be painted on the same thread.
127                // FIXME figure out how to make this thread safe? Probably not necessary, since UI isn't blocked, but it would be a nice to have
128                TileLoader loader = new TileLoader(data, tile, tileSize, new ArrayList<>());
129                MainApplication.worker.execute(loader);
130                if (tImg == null) {
131                    this.cache.put(tile, new ImageCache(null, loader, false));
132                } else {
133                    // This might cause some extra renders, but *probably* ok
134                    this.cache.put(tile, new ImageCache(tImg.image(), loader, true));
135                }
136                tileImage = tImg != null ? tImg.image() : null;
137            } else if (tImg != null) {
138                tileImage = tImg.image();
139            } else {
140                tileImage = null;
141            }
142            final Point point = this.nc.getPoint(tile);
143            if (tileImage != null) {
144                if ((wasDirty && Logging.isTraceEnabled()) || this.isInactiveMode) {
145                    tempG2d.setColor(Color.DARK_GRAY);
146                    tempG2d.fillRect(point.x, point.y, tileSize, tileSize);
147                } else {
148                    painted++;
149                }
150                // There seems to be an off-by-one error somewhere. Seems to be tied to sign of lat/lon
151                final int offset = (tile.lat() > 0 ? 1 : 0) + (tile.lon() >= 0 ? 1 : 0);
152                tempG2d.drawImage(tileImage, point.x + 1, point.y + offset, null, null);
153            } else {
154                Logging.trace("StyledMapRenderer did not paint tile {1}", tile);
155            }
156        }
157        // Force another render pass if there may be more tiles to render
158        if (submittedTile <= 0) {
159            MainApplication.worker.execute(nc::invalidate);
160        }
161        final double percentDrawn = 100 * painted / (double) toRender.size();
162        if (percentDrawn < 99.99) {
163            final int x = 0;
164            final int y = nc.getHeight() / 8;
165            final String message = tr("Rendering Status: {0}%", Math.floor(percentDrawn));
166            tempG2d.setComposite(AlphaComposite.SrcOver);
167            tempG2d.setFont(new Font("sansserif", Font.BOLD, 13));
168            tempG2d.setColor(Color.BLACK);
169            tempG2d.drawString(message, x + 1, y);
170            tempG2d.setColor(Color.LIGHT_GRAY);
171            tempG2d.drawString(message, x, y);
172        }
173        tempG2d.dispose();
174        g.drawImage(tempImage, 0, 0, null);
175    }
176
177    /**
178     * Set the cache for this painter. If not set, this acts like {@link StyledMapRenderer}.
179     * @param box The box we will be rendering -- any jobs for tiles outside of this box will be cancelled
180     * @param cache The cache to use
181     * @param zoom The zoom level to use for creating the tiles
182     * @param notifier The method to call when a tile has been updated. This may or may not be called in the EDT.
183     */
184    public void setCache(Bounds box, CacheAccess<TileZXY, ImageCache> cache, int zoom, Consumer<TileZXY> notifier) {
185        this.cache = cache;
186        this.zoom = zoom;
187        this.notifier = notifier != null ? notifier : tile -> { /* Do nothing */ };
188
189        Set<TileZXY> tiles = TileZXY.boundsToTiles(box.getMinLat(), box.getMinLon(), box.getMaxLat(), box.getMaxLon(), zoom)
190                .collect(Collectors.toSet());
191        cache.getMatching(".*").forEach((key, value) -> {
192            if (!tiles.contains(key)) {
193                cancelImageFuture(cache, key, value);
194            }
195        });
196    }
197
198    /**
199     * Cancel a job for a tile
200     * @param cache The cache with the job
201     * @param key The tile key
202     * @param value The {@link ImageCache} to remove and cancel
203     */
204    private static void cancelImageFuture(CacheAccess<TileZXY, ImageCache> cache, TileZXY key, ImageCache value) {
205        if (value.imageFuture() != null) {
206            value.imageFuture().cancel();
207            if (value.image() == null) {
208                cache.remove(key);
209            } else {
210                cache.put(key, new ImageCache(value.image(), null, value.isDirty()));
211            }
212        }
213    }
214
215    /**
216     * Generate tile images
217     * @param data The data to generate tiles from
218     * @param tiles The collection of tiles to generate (note: there is currently a bug with multiple tiles)
219     * @param tileSize The size of the tile image
220     * @return The image for the tiles passed in
221     */
222    private BufferedImage generateTiles(OsmData<?, ?, ?, ?> data, Collection<TileZXY> tiles, int tileSize) {
223        if (tiles.isEmpty()) {
224            throw new IllegalArgumentException("tiles cannot be empty");
225        }
226        // We need to know how large of an area we are rendering; we get the min x/y and max x/y in order to get the
227        // number of tiles in the x/y directions we are rendering.
228        final IntSummaryStatistics xStats = tiles.stream().mapToInt(TileZXY::x).distinct().summaryStatistics();
229        final IntSummaryStatistics yStats = tiles.stream().mapToInt(TileZXY::y).distinct().summaryStatistics();
230        final int xCount = xStats.getMax() - xStats.getMin() + 1; // inclusive
231        final int yCount = yStats.getMax() - yStats.getMin() + 1; // inclusive
232        final int width = tileSize * (2 * BUFFER_TILES + xCount);
233        final int height = tileSize * (2 * BUFFER_TILES + yCount);
234        // getWidth and getHeight are called in the constructor; Java 22 will let us call super after we set variables.
235        final NavigatableComponent temporaryView = new NavigatableComponent() {
236            @Override
237            public int getWidth() {
238                return width;
239            }
240
241            @Override
242            public int getHeight() {
243                return height;
244            }
245        };
246        // These bounds are used to set the render area; it includes the buffer area.
247        final Bounds bounds = generateRenderArea(tiles);
248
249        temporaryView.zoomTo(bounds.getCenter().getEastNorth(ProjectionRegistry.getProjection()), mapState.getScale());
250        BufferedImage bufferedImage = createCompatibleImage(nc, width, height);
251        Graphics2D g2d = bufferedImage.createGraphics();
252        try {
253            g2d.setRenderingHints(Map.of(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
254            final AbstractMapRenderer tilePainter = MapRendererFactory.getInstance().createActiveRenderer(g2d, temporaryView, false);
255            tilePainter.render(data, true, bounds);
256        } finally {
257            g2d.dispose();
258        }
259        final int bufferPixels = BUFFER_TILES * tileSize;
260        return bufferedImage.getSubimage(bufferPixels, bufferPixels,
261                width - 2 * bufferPixels + BUFFER_PIXELS, height - 2 * bufferPixels + BUFFER_PIXELS);
262    }
263
264    private static BufferedImage createCompatibleImage(NavigatableComponent nc, int width, int height) {
265        final GraphicsConfiguration gc = nc.getGraphicsConfiguration();
266        if (gc == null) {
267            return new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
268        }
269        return gc.createCompatibleImage(width, height, Transparency.TRANSLUCENT);
270    }
271
272    /**
273     * Generate the area for rendering
274     * @param tiles The tiles that we want to render
275     * @return The generated render area with {@link #BUFFER_TILES} on all sides.
276     */
277    private static Bounds generateRenderArea(Collection<TileZXY> tiles) {
278        Bounds bounds = null;
279        for (TileZXY tile : tiles) {
280            if (bounds == null) {
281                bounds = TileZXY.tileToBounds(tile);
282            }
283            bounds.extend(TileZXY.tileToBounds(new TileZXY(tile.zoom(), tile.x() - BUFFER_TILES, tile.y() - BUFFER_TILES)));
284            bounds.extend(TileZXY.tileToBounds(new TileZXY(tile.zoom(), tile.x() + BUFFER_TILES, tile.y() + BUFFER_TILES)));
285        }
286        return Objects.requireNonNull(bounds);
287    }
288
289    /**
290     * A loader for tiles
291     */
292    class TileLoader implements Runnable {
293        private final TileZXY tile;
294        private final int tileSize;
295        private final OsmData<?, ?, ?, ?> data;
296        private boolean cancel;
297        private final Collection<TileLoader> tileCollection;
298        private boolean done;
299
300        /**
301         * Create a new tile loader
302         * @param data The data to use for painting
303         * @param tile The tile this tile loader is for
304         * @param tileSize The expected size of this tile
305         * @param tileCollection The collection of tiles that this tile is being rendered with (for batching)
306         */
307        TileLoader(OsmData<?, ?, ?, ?> data, TileZXY tile, int tileSize, Collection<TileLoader> tileCollection) {
308            this.data = data;
309            this.tile = tile;
310            this.tileSize = tileSize;
311            this.tileCollection = tileCollection;
312            this.tileCollection.add(this);
313        }
314
315        @Override
316        public void run() {
317            if (!cancel) {
318                synchronized (tileCollection) {
319                    if (!done) {
320                        final BufferedImage tImage = generateTiles(data,
321                                tileCollection.stream().map(t -> t.tile).collect(Collectors.toList()), tileSize);
322                        final int minX = tileCollection.stream().map(t -> t.tile).mapToInt(TileZXY::x).min().orElse(this.tile.x());
323                        final int minY = tileCollection.stream().map(t -> t.tile).mapToInt(TileZXY::y).min().orElse(this.tile.y());
324                        for (TileLoader loader : tileCollection) {
325                            final TileZXY txy = loader.tile;
326                            final int x = (txy.x() - minX) * tileSize;
327                            final int y = (txy.y() - minY) * tileSize;
328                            final int wh = tileSize;
329
330                            final BufferedImage tileImage = tImage.getSubimage(x, y, wh + BUFFER_PIXELS, wh + BUFFER_PIXELS);
331                            loader.cacheTile(tileImage);
332                        }
333                    }
334                }
335            }
336        }
337
338        /**
339         * Finish a tile generation job
340         * @param tImage The tile image for this job
341         */
342        private void cacheTile(BufferedImage tImage) {
343            cache.put(tile, new ImageCache(tImage, null, false));
344            done = true;
345            notifier.accept(tile);
346        }
347
348        /**
349         * Cancel this job without causing a {@link java.util.concurrent.CancellationException}
350         */
351        void cancel() {
352            this.cancel = true;
353        }
354    }
355}