1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package org.microemu.device.impl;
28
29 import junit.framework.TestCase;
30
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33
34
35
36
37
38 public class PolygonTest extends TestCase {
39
40 private static final boolean debug = false;
41
42 Pattern rx = Pattern.compile("(?:(\\d+)\\s?[,]\\s?(\\d+)(?:\\s?[;]\\s?)?)");
43
44 private void verify(String polygon, String points, boolean expected) {
45 Polygon pl = new Polygon();
46
47 java.awt.Polygon awt = new java.awt.Polygon();
48
49
50 Matcher mp = rx.matcher(polygon);
51 while (mp.find()) {
52 int px = Integer.parseInt(mp.group(1));
53 int py = Integer.parseInt(mp.group(2));
54 pl.addPoint(px, py);
55 awt.addPoint(px, py);
56 }
57 Matcher mxy = rx.matcher(points);
58 while (mxy.find()) {
59 int x = Integer.parseInt(mxy.group(1));
60 int y = Integer.parseInt(mxy.group(2));
61 String xy = "[" + x + ", " + y + "]";
62 assertEquals("awt " + polygon + " contains " + xy, expected, awt.contains(x, y));
63
64 if (debug && expected != pl.contains(x, y)) {
65 System.out.println("error impl " + polygon + " contains " + xy + "? expected:" + expected);
66 pl.contains(x, y);
67 awt.contains(x, y);
68 } else if (debug) {
69 System.out.println("OK impl " + polygon + " contains " + xy + "? expected:" + expected);
70 }
71 assertEquals("impl " + polygon + " contains " + xy, expected, pl.contains(x, y));
72 }
73
74
75 int x = pl.getBounds().x - 2;
76 int y= pl.getBounds().y - 2;
77 int w = pl.getBounds().width + 4;
78 int h = pl.getBounds().height + 4;
79 for(int xx = x ; xx <= w; xx ++) {
80 for(int yy = y ; yy <= h; yy ++) {
81 int xt = x + xx;
82 int yt = y + yy;
83 boolean exp = awt.contains(xt, yt);
84 String xy = "[" + xt + ", " + yt + "]";
85 assertEquals("impl " + polygon + " contains " + xy, exp, pl.contains(xt, yt));
86 }
87 }
88 }
89
90
91 public void testTriangleContains() {
92 String triangle = "4,10; 10,5; 12,14";
93 String pointIn = "9,9; 9,7; 10,11; 11,12; 7,11";
94 String pointOut = "6,6; 10,4; 13,7; 13,15; 10,14; 5,12";
95 verify(triangle, pointIn , true);
96 verify(triangle, pointOut , false);
97
98 String triangleBack = "4,10; 12,14; 10,5;";
99 verify(triangleBack, pointIn , true);
100 verify(triangleBack, pointOut , false);
101
102 String triangleBack2 = "12,14; 10,5; 4,10; ";
103 verify(triangleBack2, pointIn , true);
104 verify(triangleBack2, pointOut , false);
105 }
106
107 public void testComplexContains() {
108 verify("4,10; 10,5; 17,3; 19,6; 14,8; 12,14; 7,12", "", true);
109 verify("4,10; 10,5; 17,3; 19,6; 17,12; 12,14; 7,12", "", true);
110 verify("7,12; 12,14; 17,12; 19,6; 17,3; 10,5; 4,10;", "", true);
111 }
112
113 }