source: josm/trunk/test/functional/org/openstreetmap/josm/gui/mappaint/MapCSSRendererTest.java@ 12465

Last change on this file since 12465 was 12465, checked in by bastiK, 7 years ago

see #15006 - new MapCSSRendererTest test case for text along way

  • Property svn:eol-style set to native
File size: 12.1 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.mappaint;
3
4import static org.junit.Assert.assertEquals;
5import static org.junit.Assert.fail;
6
7import java.awt.Graphics2D;
8import java.awt.GraphicsEnvironment;
9import java.awt.Point;
10import java.awt.RenderingHints;
11import java.awt.image.BufferedImage;
12import java.io.File;
13import java.io.FileInputStream;
14import java.io.FileNotFoundException;
15import java.io.IOException;
16import java.text.MessageFormat;
17import java.util.ArrayList;
18import java.util.Arrays;
19import java.util.Collection;
20import java.util.List;
21import java.util.stream.Collectors;
22import java.util.stream.Stream;
23
24import javax.imageio.ImageIO;
25
26import org.junit.Assume;
27import org.junit.Before;
28import org.junit.Rule;
29import org.junit.Test;
30import org.junit.runner.RunWith;
31import org.junit.runners.Parameterized;
32import org.junit.runners.Parameterized.Parameters;
33import org.openstreetmap.josm.TestUtils;
34import org.openstreetmap.josm.data.Bounds;
35import org.openstreetmap.josm.data.osm.DataSet;
36import org.openstreetmap.josm.data.osm.OsmPrimitive;
37import org.openstreetmap.josm.data.osm.visitor.paint.StyledMapRenderer;
38import org.openstreetmap.josm.gui.NavigatableComponent;
39import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
40import org.openstreetmap.josm.gui.preferences.SourceEntry;
41import org.openstreetmap.josm.io.IllegalDataException;
42import org.openstreetmap.josm.io.OsmReader;
43import org.openstreetmap.josm.testutils.JOSMTestRules;
44
45import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
46
47/**
48 * Test cases for {@link StyledMapRenderer} and the MapCSS classes.
49 * <p>
50 * This test uses the data and reference files stored in the test data directory {@value #TEST_DATA_BASE}
51 * @author Michael Zangl
52 */
53@RunWith(Parameterized.class)
54public class MapCSSRendererTest {
55 private static final String TEST_DATA_BASE = "/renderer/";
56 /**
57 * lat = 0..1, lon = 0..1
58 */
59 private static final Bounds AREA_DEFAULT = new Bounds(0, 0, 1, 1);
60 private static final int IMAGE_SIZE = 256;
61
62 /**
63 * Minimal test rules required
64 */
65 @Rule
66 @SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
67 public JOSMTestRules test = new JOSMTestRules().preferences().projection();
68
69 private TestConfig testConfig;
70
71 /**
72 * The different configurations of this test.
73 *
74 * @return The parameters.
75 */
76 @Parameters(name = "{1}")
77 public static Collection<Object[]> runs() {
78 return Stream.of(
79 /** Tests for StyledMapRenderer#drawNodeSymbol */
80 new TestConfig("node-shapes", AREA_DEFAULT),
81
82 /** Text for nodes */
83 new TestConfig("node-text", AREA_DEFAULT).usesFont("DejaVu Sans"),
84
85 /** Tests that StyledMapRenderer#drawWay respects width */
86 new TestConfig("way-width", AREA_DEFAULT),
87
88 /** Tests the way color property, including alpha */
89 new TestConfig("way-color", AREA_DEFAULT),
90
91 /** Tests dashed ways. */
92 new TestConfig("way-dashes", AREA_DEFAULT),
93
94 /** Tests dashed way clamping algorithm */
95 new TestConfig("way-dashes-clamp", AREA_DEFAULT),
96
97 /** Tests fill-color property */
98 new TestConfig("area-fill-color", AREA_DEFAULT),
99
100 /** Tests the fill-image property. */
101 new TestConfig("area-fill-image", AREA_DEFAULT),
102
103 /** Tests area label drawing/placement */
104 new TestConfig("area-text", AREA_DEFAULT),
105
106 /** Tests area icon drawing/placement */
107 new TestConfig("area-icon", AREA_DEFAULT),
108
109 /** Tests if all styles are sorted correctly. Tests {@link StyleRecord#compareTo(StyleRecord)} */
110 new TestConfig("order", AREA_DEFAULT),
111
112 /** Tests repeat-image feature for ways */
113 new TestConfig("way-repeat-image", AREA_DEFAULT),
114 /** Tests the clamping for repeat-images and repeat-image-phase */
115 new TestConfig("way-repeat-image-clamp", AREA_DEFAULT),
116
117 /** Tests text along a way */
118 new TestConfig("way-text", AREA_DEFAULT)
119 ).map(e -> new Object[] {e, e.testDirectory})
120 .collect(Collectors.toList());
121 }
122
123 /**
124 * @param testConfig The config to use for this test.
125 * @param ignored The name to print it nicely
126 */
127 public MapCSSRendererTest(TestConfig testConfig, String ignored) {
128 this.testConfig = testConfig;
129 }
130
131 /**
132 * This test only runs on OpenJDK.
133 * It is ignored for other Java versions since they differ slightly in their rendering engine.
134 * @since 11691
135 */
136 @Before
137 public void forOpenJDK() {
138 String javaHome = System.getProperty("java.home");
139 Assume.assumeTrue("Test requires openJDK", javaHome != null && javaHome.contains("openjdk"));
140
141 List<String> fonts = Arrays.asList(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames());
142 for (String font : testConfig.fonts) {
143 Assume.assumeTrue("Test requires font: " + font, fonts.contains(font));
144 }
145 }
146
147 /**
148 * Run the test using {@link #testConfig}
149 * @throws Exception if an error occurs
150 */
151 @Test
152 public void testRender() throws Exception {
153 // Force reset of preferences
154 StyledMapRenderer.PREFERENCE_ANTIALIASING_USE.put(true);
155 StyledMapRenderer.PREFERENCE_TEXT_ANTIALIASING.put("gasp");
156
157 // load the data
158 DataSet dataSet = testConfig.getOsmDataSet();
159
160 // load the style
161 MapCSSStyleSource.STYLE_SOURCE_LOCK.writeLock().lock();
162 try {
163 MapPaintStyles.getStyles().clear();
164
165 MapCSSStyleSource source = new MapCSSStyleSource(testConfig.getStyleSourceEntry());
166 source.loadStyleSource();
167 if (!source.getErrors().isEmpty()) {
168 fail("Failed to load style file. Errors: " + source.getErrors());
169 }
170 MapPaintStyles.getStyles().setStyleSources(Arrays.asList(source));
171 MapPaintStyles.fireMapPaintSylesUpdated();
172 MapPaintStyles.getStyles().clearCached();
173
174 } finally {
175 MapCSSStyleSource.STYLE_SOURCE_LOCK.writeLock().unlock();
176 }
177
178 // create the renderer
179 BufferedImage image = new BufferedImage(IMAGE_SIZE, IMAGE_SIZE, BufferedImage.TYPE_INT_ARGB);
180 NavigatableComponent nc = new NavigatableComponent() {
181 {
182 setBounds(0, 0, IMAGE_SIZE, IMAGE_SIZE);
183 updateLocationState();
184 }
185
186 @Override
187 protected boolean isVisibleOnScreen() {
188 return true;
189 }
190
191 @Override
192 public Point getLocationOnScreen() {
193 return new Point(0, 0);
194 }
195 };
196 nc.zoomTo(testConfig.testArea);
197 dataSet.allPrimitives().stream().forEach(this::loadPrimitiveStyle);
198 dataSet.setSelected(dataSet.allPrimitives().stream().filter(n -> n.isKeyTrue("selected")).collect(Collectors.toList()));
199
200 Graphics2D g = image.createGraphics();
201 // Force all render hints to be defaults - do not use platform values
202 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
203 g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
204 g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
205 g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
206 g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
207 g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
208 g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
209 g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
210 g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
211 new StyledMapRenderer(g, nc, false).render(dataSet, false, testConfig.testArea);
212
213 BufferedImage reference = testConfig.getReference();
214
215 // now compute differences:
216 assertEquals(IMAGE_SIZE, reference.getWidth());
217 assertEquals(IMAGE_SIZE, reference.getHeight());
218
219 StringBuilder differences = new StringBuilder();
220 ArrayList<Point> differencePoints = new ArrayList<>();
221
222 for (int y = 0; y < reference.getHeight(); y++) {
223 for (int x = 0; x < reference.getWidth(); x++) {
224 int expected = reference.getRGB(x, y);
225 int result = image.getRGB(x, y);
226 if (!colorsAreSame(expected, result)) {
227 differencePoints.add(new Point(x, y));
228 if (differences.length() < 500) {
229 differences.append("\nDifference at ")
230 .append(x)
231 .append(",")
232 .append(y)
233 .append(": Expected ")
234 .append(Integer.toHexString(expected))
235 .append(" but got ")
236 .append(Integer.toHexString(result));
237 }
238 }
239 }
240 }
241
242 if (differencePoints.size() > 0) {
243 // You can use this to debug:
244 ImageIO.write(image, "png", new File(testConfig.getTestDirectory() + "/test-output.png"));
245
246 // Add a nice image that highlights the differences:
247 BufferedImage diffImage = new BufferedImage(IMAGE_SIZE, IMAGE_SIZE, BufferedImage.TYPE_INT_ARGB);
248 for (Point p : differencePoints) {
249 diffImage.setRGB(p.x, p.y, 0xffff0000);
250 }
251 ImageIO.write(diffImage, "png", new File(testConfig.getTestDirectory() + "/test-differences.png"));
252
253 fail(MessageFormat.format("Images for test {0} differ at {1} points: {2}",
254 testConfig.testDirectory, differencePoints.size(), differences.toString()));
255 }
256 }
257
258 private void loadPrimitiveStyle(OsmPrimitive n) {
259 n.setHighlighted(n.isKeyTrue("highlight"));
260 if (n.isKeyTrue("disabled")) {
261 n.setDisabledState(false);
262 }
263 }
264
265 /**
266 * Check if two colors differ
267 * @param expected The expected color
268 * @param actual The actual color
269 * @return <code>true</code> if they differ.
270 */
271 private boolean colorsAreSame(int expected, int actual) {
272 int expectedAlpha = expected >> 24;
273 if (expectedAlpha == 0) {
274 return actual >> 24 == 0;
275 } else {
276 return expected == actual;
277 }
278 }
279
280 private static class TestConfig {
281 private final String testDirectory;
282 private final Bounds testArea;
283 private final ArrayList<String> fonts = new ArrayList<>();
284
285 TestConfig(String testDirectory, Bounds testArea) {
286 this.testDirectory = testDirectory;
287 this.testArea = testArea;
288 }
289
290 public TestConfig usesFont(String string) {
291 this.fonts.add(string);
292 return this;
293 }
294
295 public BufferedImage getReference() throws IOException {
296 return ImageIO.read(new File(getTestDirectory() + "/reference.png"));
297 }
298
299 private String getTestDirectory() {
300 return TestUtils.getTestDataRoot() + TEST_DATA_BASE + testDirectory;
301 }
302
303 public SourceEntry getStyleSourceEntry() {
304 return new SourceEntry(getTestDirectory() + "/style.mapcss",
305 "test style", "a test style", true // active
306 );
307 }
308
309 public DataSet getOsmDataSet() throws FileNotFoundException, IllegalDataException {
310 return OsmReader.parseDataSet(new FileInputStream(getTestDirectory() + "/data.osm"), null);
311 }
312
313 @Override
314 public String toString() {
315 return "TestConfig [testDirectory=" + testDirectory + ", testArea=" + testArea + ']';
316 }
317 }
318}
Note: See TracBrowser for help on using the repository browser.