]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.district.maps/src/org/simantics/maps/sg/MapScaleNode.java
Add location & zoom node for network diagram - also OSM attribution
[simantics/district.git] / org.simantics.district.maps / src / org / simantics / maps / sg / MapScaleNode.java
1 package org.simantics.maps.sg;
2
3 import java.awt.AlphaComposite;
4 import java.awt.BasicStroke;
5 import java.awt.Color;
6 import java.awt.Font;
7 import java.awt.FontMetrics;
8 import java.awt.Graphics2D;
9 import java.awt.geom.AffineTransform;
10 import java.awt.geom.Point2D;
11 import java.awt.geom.Rectangle2D;
12 import java.util.Locale;
13
14 import org.geotools.referencing.CRS;
15 import org.geotools.referencing.GeodeticCalculator;
16 import org.opengis.referencing.FactoryException;
17 import org.opengis.referencing.crs.CoordinateReferenceSystem;
18 import org.simantics.scenegraph.g2d.G2DNode;
19 import org.simantics.scenegraph.utils.GridUtils;
20
21 public class MapScaleNode extends G2DNode {
22
23     private static final long serialVersionUID = -2738682328944298290L;
24     
25     private static final Color GRAY              = new Color(100, 100, 100);
26
27     protected Boolean          enabled           = true;
28
29     protected double           gridSize          = 1.0;
30
31     @Override
32     public void render(Graphics2D g) {
33         if (!enabled)
34             return;
35
36         AffineTransform ot = g.getTransform();
37         g.transform(transform);
38         
39         AffineTransform tr = g.getTransform();
40         double scaleX = Math.abs(tr.getScaleX());
41         double scaleY = Math.abs(tr.getScaleY());
42         if (scaleX <= 0 || scaleY <= 0) {
43             // Make sure that we don't end up in an eternal loop below.
44             return;
45         }
46         double offsetX = tr.getTranslateX();
47         double offsetY = tr.getTranslateY();
48         g.setTransform(new AffineTransform());
49
50         Font rulerFont = new Font("Tahoma", Font.PLAIN, 9);
51
52         //g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
53         g.setStroke(new BasicStroke(1));
54         g.setColor(new Color(0.9f, 0.9f, 0.9f, 0.75f));
55
56         Rectangle2D bounds = g.getClipBounds();
57         if(bounds == null) return; // FIXME
58
59         double previousText = -100;
60         
61         double minY = bounds.getMaxY() - 40;
62         
63         double scaleRight = bounds.getMaxX() - 20;
64         
65         double meterPerPixel = getMeterPerPixel(scaleRight - offsetX, minY - offsetY, scaleX, scaleY);
66         
67         double pixels = 0;
68         double value = 0;
69         for (int i = 0; i < SCALE_VALUES.length; i++) {
70             value = SCALE_VALUES[i];
71             pixels = value / meterPerPixel;
72             if (pixels > 100) {
73                 break;
74             }
75         }
76         
77         
78         double newScaleLeft = scaleRight - pixels;
79         g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f));
80         Rectangle2D vertical = new Rectangle2D.Double(newScaleLeft, bounds.getMaxY() - 40, pixels, 20);
81         g.fill(vertical);
82         
83         g.setColor(GRAY);
84         g.setFont(rulerFont);
85         
86         
87         // stepX and stepY should be something between 50 and 100
88         double stepX = 50;
89
90         stepX = GridUtils.limitedEvenGridSpacing(stepX, scaleX, 100, gridSize, true);
91         //while(stepX * scaleX > 100) stepX /= 2;
92         //while(stepY * scaleY > 100) stepY /= 2;
93
94         while(stepX * scaleX < 50) stepX *= 2;
95
96         stepX *= scaleX;
97         
98         double gap = scaleRight -newScaleLeft;
99         
100         stepX = gap / 2 - 0.00001;
101         
102         // Horizontal ruler
103         double label = 0;
104         FontMetrics fm = g.getFontMetrics();
105         for(double x = newScaleLeft; x < scaleRight; x += stepX) {
106             String str = formatValue(label * meterPerPixel);
107             Rectangle2D r = fm.getStringBounds(str, g);
108             if((x - r.getWidth() / 2) > previousText) {
109                 g.setColor(Color.BLACK);
110                 g.drawString(str, (int)(x-r.getWidth()/2), (int)(minY+1+r.getHeight()));
111                 previousText = x+r.getWidth()/2+stepX/4;
112             }
113
114             g.setColor(GRAY);
115             g.drawLine((int)x, (int)minY+12, (int)x, (int)minY+19);
116             if (x + 0.1 < scaleRight) {
117                 if(stepX/5 > 2) {
118                     for(double x2 = x+stepX/5; x2 < x+stepX; x2+=stepX/5) {
119                         if(x2 > 20) {
120                             g.drawLine((int)x2, (int)minY+15, (int)x2, (int)minY+19);
121                         }
122                     }
123                     for(double x2 = x+stepX/10; x2 < x+stepX; x2+=stepX/5) {
124                         if(x2 > 20) {
125                             g.drawLine((int)x2, (int)minY+17, (int)x2, (int)minY+19);
126                         }
127                     }
128                 }
129             }
130             label += stepX;
131         }
132
133         g.setTransform(ot);
134     }
135
136     @Override
137     public Rectangle2D getBoundsInLocal() {
138         return null;
139     }
140     
141     private static final transient int    MAX_DIGITS = 0;
142     private static final transient double EPSILON    = 0.01;
143     private static final transient double TRIM_THRESHOLD_MAX_VALUE = Math.pow(10, 2);
144     private static final transient String[] SI_UNIT_LARGE_PREFIXES = { "m", "km" };
145     
146     private static final transient double[] SCALE_VALUES = { 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000, 500000, 1000000, 2000000, 50000000 };
147     
148     public static String formatValue(double value) {
149         int magnitude = (int) Math.round(Math.log10(value));
150         //System.out.println("magnitude: " + magnitude + ", " + value);
151         int allowedDecimals = MAX_DIGITS;
152         allowedDecimals -= Math.abs(magnitude);
153         if (allowedDecimals < 0)
154             allowedDecimals = 0;
155
156         String valueStr = String.format(Locale.US, "%." + allowedDecimals + "f", value);
157         if (allowedDecimals > 0) {
158             for (int trunc = valueStr.length() - 1; trunc > 0; --trunc) {
159                 char ch = valueStr.charAt(trunc);
160                 if (ch == '.') {
161                     valueStr = valueStr.substring(0, trunc);
162                     break;
163                 }
164                 if (valueStr.charAt(trunc) != '0') {
165                     valueStr = valueStr.substring(0, trunc + 1);
166                     break;
167                 }
168             }
169             if (Math.abs(value) + EPSILON > TRIM_THRESHOLD_MAX_VALUE) {
170                 // Cut anything beyond a possible decimal dot out since they
171                 // should not show anyway. This is a complete hack that tries to
172                 // circumvent floating-point inaccuracy problems.
173                 int dotIndex = valueStr.lastIndexOf('.');
174                 if (dotIndex > -1) {
175                     valueStr = valueStr.substring(0, dotIndex);
176                 }
177             }
178         }
179
180         if (valueStr.equals("-0"))
181             valueStr = "0";
182         
183 //        if (!valueStr.equals("0")) {
184 //            double trimValue = value;
185 //            for (int i = 0; i < SI_UNIT_LARGE_PREFIXES.length; i++) {
186 //                double trim = trimValue / 1000;
187 //                if (Math.abs(trim)-EPSILON < TRIM_THRESHOLD_MAX_VALUE) {
188 //                    valueStr = valueStr.substring(0, valueStr.length() - (i + 1) * 3);
189 //                    valueStr += SI_UNIT_LARGE_PREFIXES[i];
190 //                    break;
191 //                }
192 //                trimValue = trim;
193 //            }
194 //        }
195
196         return valueStr;
197     }
198
199     public void setEnabled(boolean enabled) {
200         this.enabled = enabled;
201     }
202
203     @Override
204     public void init() {
205         try {
206             EPSG4326 = CRS.decode("EPSG:4326");
207             calculator = new GeodeticCalculator(EPSG4326);
208         } catch (FactoryException e) {
209             e.printStackTrace();
210         }
211         super.init();
212     }
213     
214     GeodeticCalculator calculator; 
215     CoordinateReferenceSystem EPSG4326;
216     
217     public Point2D scaleLeftmostPoint(double startLon, double startLat, double distance, double azimuth) {
218         GeodeticCalculator calculator = new GeodeticCalculator();
219         calculator.setStartingGeographicPoint(startLon, startLat);
220         calculator.setDirection(azimuth, distance);
221         return calculator.getDestinationGeographicPoint();
222     }
223     
224     public double getMeterPerPixel(double screenX, double screenY, double scaleX, double scaleY) {
225         double startLon = (screenX / scaleX);
226         double val = (screenY / scaleY);
227         val = Math.toDegrees(Math.atan(Math.sinh(Math.toRadians(val))));
228         double startLat = val;
229         double endLon = ((screenX + 1) / scaleX);
230         double endLat = val;
231         
232         calculator.setStartingGeographicPoint(startLon, startLat);
233         calculator.setDestinationGeographicPoint(endLon, endLat);
234         double distance = calculator.getOrthodromicDistance();
235         
236         return distance;
237     }
238
239 }