FIX way splitting: P shaped ways are now handled correctly. Had to modify SplitWayAct...
[potlatch2.git] / net / systemeD / halcyon / connection / Way.as
1 package net.systemeD.halcyon.connection {
2     import flash.geom.Point;
3     
4     import net.systemeD.halcyon.connection.actions.*;
5
6     public class Way extends Entity {
7         private var nodes:Array;
8                 private var edge_l:Number;
9                 private var edge_r:Number;
10                 private var edge_t:Number;
11                 private var edge_b:Number;
12                 public static var entity_type:String = 'way';
13
14         public function Way(id:Number, version:uint, tags:Object, loaded:Boolean, nodes:Array, uid:Number = NaN, timestamp:String = null) {
15             super(id, version, tags, loaded, uid, timestamp);
16             this.nodes = nodes;
17                         for each (var node:Node in nodes) { node.addParent(this); }
18                         calculateBbox();
19         }
20
21                 public function update(version:uint, tags:Object, loaded:Boolean, parentsLoaded:Boolean, nodes:Array, uid:Number = NaN, timestamp:String = null):void {
22                         var node:Node;
23                         for each (node in this.nodes) { node.removeParent(this); }
24                         updateEntityProperties(version,tags,loaded,parentsLoaded,uid,timestamp); this.nodes=nodes;
25                         for each (node in nodes) { node.addParent(this); }
26                         calculateBbox();
27                 }
28                 
29         public function get length():uint {
30             return nodes.length;
31         }
32
33                 private function calculateBbox():void {
34                         edge_l=999999; edge_r=-999999;
35                         edge_b=999999; edge_t=-999999;
36                         for each (var node:Node in nodes) { expandBbox(node); }
37                 }
38
39                 public function expandBbox(node:Node):void {
40                         edge_l=Math.min(edge_l,node.lon);
41                         edge_r=Math.max(edge_r,node.lon);
42                         edge_b=Math.min(edge_b,node.lat);
43                         edge_t=Math.max(edge_t,node.lat);
44                 }
45                 
46                 public override function within(left:Number,right:Number,top:Number,bottom:Number):Boolean {
47                         if (!edge_l ||
48                                 (edge_l<left   && edge_r<left  ) ||
49                             (edge_l>right  && edge_r>right ) ||
50                             (edge_b<bottom && edge_t<bottom) ||
51                             (edge_b>top    && edge_b>top   ) || deleted) { return false; }
52                         return true;
53                 }
54         
55         public function getNode(index:uint):Node {
56             return nodes[index];
57         }
58
59         public function getFirstNode():Node {
60             return nodes[0];
61         }
62
63                 public function getLastNode():Node {
64                         return nodes[nodes.length-1];
65                 }
66                 
67                 /** Given one node, return the next in sequence, cycling around a loop if necessary. */
68                 // TODO make behave correctly for P-shaped topologies?
69                 public function getNextNode(node:Node):Node {
70                         // If the last node in a loop is selected, this behaves correctly.
71                     var i:uint = indexOfNode(node);
72                     if(i < length-1)
73                     return nodes[i+1];
74                 return null;
75                 // What should happen for very short lengths?      
76                 }
77         
78         // TODO make behave correctly for P-shaped topologies?
79         /** Given one node, return the previous, cycling around a loop if necessary. */
80         public function getPrevNode(node:Node):Node {
81             var i:uint = indexOfNode(node);
82             if(i > 0)
83                 return nodes[i-1];
84             if(i == 0 && isArea() )
85                 return nodes[nodes.length - 2]
86             return null;
87             // What should happen for very short lengths?      
88         }
89
90         public function insertNode(index:uint, node:Node, performAction:Function):void {
91                         performAction(new AddNodeToWayAction(this, node, nodes, index));
92         }
93
94         public function appendNode(node:Node, performAction:Function):uint {
95                         performAction(new AddNodeToWayAction(this, node, nodes, -1));
96             return nodes.length + 1;
97         }
98         
99         public function prependNode(node:Node, performAction:Function):uint {
100                         performAction(new AddNodeToWayAction(this, node, nodes, 0));
101             return nodes.length + 1;
102         }
103         
104         // return the index of the Node, or -1 if not found
105         public function indexOfNode(node:Node):int {
106             return nodes.indexOf(node);
107         }
108
109                 public function hasOnceOnly(node:Node):Boolean {
110                         return nodes.indexOf(node)==nodes.lastIndexOf(node);
111                 }
112                 
113                 public function hasLockedNodes():Boolean {
114                         for each (var node:Node in nodes) {
115                                 if (node.locked) { return true; }
116                         }
117                         return false;
118                 }
119
120                 public function removeNode(node:Node, performAction:Function):void {
121                         performAction(new RemoveNodeFromWayAction(this, node, nodes));
122                 }
123
124         public function removeNodeByIndex(index:uint, performAction:Function, fireEvent:Boolean=true):void {
125             performAction(new RemoveNodeByIndexAction(this, nodes, index, fireEvent));
126         }
127
128                 public function sliceNodes(start:int,end:int):Array {
129                         return nodes.slice(start,end);
130                 }
131
132         public function deleteNodesFrom(start:int, performAction:Function):void {
133             for (var i:int=nodes.length-1; i>=start; i--) {
134               performAction(new RemoveNodeByIndexAction(this, nodes, i));
135             }
136             markDirty();
137         }
138
139                 public function mergeWith(way:Way,topos:int,frompos:int, performAction:Function):void {
140                         performAction(new MergeWaysAction(this, way, topos, frompos));
141                 }
142                 
143                 public function addToEnd(topos:int,node:Node, performAction:Function):void {
144                         if (topos==0) {
145                                 if (nodes[0]==node) { return; }
146                                 prependNode(node, performAction);
147                         } else {
148                                 if (nodes[nodes.length-1]==node) { return; }
149                                 appendNode(node, performAction);
150                         }
151                 }
152
153         public function reverseNodes(performAction:Function):void {
154             performAction(new ReverseNodesAction(this, nodes));
155         }
156
157         /**
158          * Finds the 1st way segment which intersects the projected
159          * coordinate and adds the node to that segment. If snap is
160          * specified then the node is moved to exactly bisect the
161          * segment.
162          */
163         public function insertNodeAtClosestPosition(newNode:Node, isSnap:Boolean, performAction:Function):int {
164             var closestProportion:Number = 1;
165             var newIndex:uint = 0;
166             var nP:Point = new Point(newNode.lon, newNode.latp);
167             var snapped:Point = null;
168             
169             for ( var i:uint; i < length - 1; i++ ) {
170                 var node1:Node = getNode(i);
171                 var node2:Node = getNode(i+1);
172                 var p1:Point = new Point(node1.lon, node1.latp);
173                 var p2:Point = new Point(node2.lon, node2.latp);
174                 
175                 var directDist:Number = Point.distance(p1, p2);
176                 var viaNewDist:Number = Point.distance(p1, nP) + Point.distance(nP, p2);
177                         
178                 var proportion:Number = Math.abs(viaNewDist/directDist - 1);
179                 if ( proportion < closestProportion ) {
180                     newIndex = i+1;
181                     closestProportion = proportion;
182                     snapped = calculateSnappedPoint(p1, p2, nP);
183                 }
184             }
185             
186             // splice in new node
187             if ( isSnap ) {
188                 newNode.setLonLatp(snapped.x, snapped.y, performAction);
189             }
190             insertNode(newIndex, newNode, performAction);
191             return newIndex;
192         }
193         
194         private function calculateSnappedPoint(p1:Point, p2:Point, nP:Point):Point {
195             var w:Number = p2.x - p1.x;
196             var h:Number = p2.y - p1.y;
197             var u:Number = ((nP.x-p1.x) * w + (nP.y-p1.y) * h) / (w*w + h*h);
198             return new Point(p1.x + u*w, p1.y+u*h);
199         }
200         
201         public override function toString():String {
202             return "Way("+id+"@"+version+"): "+getTagList()+
203                      " "+nodes.map(function(item:Node,index:int, arr:Array):String {return item.id.toString();}).join(",");
204         }
205
206                 public function isArea():Boolean {
207                         if (nodes.length==0) { return false; }
208                         return (nodes[0].id==nodes[nodes.length-1].id && nodes.length>2);
209                 }
210                 
211                 public function endsWith(node:Node):Boolean {
212                         return (nodes[0]==node || nodes[nodes.length-1]==node);
213                 }
214                 
215                 public override function remove(performAction:Function):void {
216                         performAction(new DeleteWayAction(this, setDeletedState, nodes));
217                 }
218
219                 public override function nullify():void {
220                         nullifyEntity();
221                         nodes=[];
222                         edge_l=edge_r=edge_t=edge_b=NaN;
223                 }
224                 
225                 public function get clockwise():Boolean {
226                         var lowest:uint=0;
227                         var xmin:Number=-999999; var ymin:Number=-999999;
228                         for (var i:uint=0; i<nodes.length; i++) {
229                                 if      (nodes[i].latp> ymin) { lowest=i; xmin=nodes[i].lon; ymin=nodes[i].latp; }
230                                 else if (nodes[i].latp==ymin
231                                           && nodes[i].lon > xmin) { lowest=i; xmin=nodes[i].lon; ymin=nodes[i].latp; }
232                         }
233                         return (this.onLeft(lowest)>0);
234                 }
235                 
236                 private function onLeft(j:uint):Number {
237                         var left:Number=0;
238                         var i:int, k:int;
239                         if (nodes.length>=3) {
240                                 i=j-1; if (i==-1) { i=nodes.length-2; }
241                                 k=j+1; if (k==nodes.length) { k=1; }
242                                 left=((nodes[j].lon-nodes[i].lon) * (nodes[k].latp-nodes[i].latp) -
243                                           (nodes[k].lon-nodes[i].lon) * (nodes[j].latp-nodes[i].latp));
244                         }
245                         return left;
246                 }
247
248         public function get angle():Number {
249             var dx:Number = nodes[nodes.length-1].lon - nodes[0].lon;
250             var dy:Number = nodes[nodes.length-1].latp - nodes[0].latp;
251             if (dx != 0 || dy != 0) {
252                 return Math.atan2(dx,dy)*(180/Math.PI);
253             } else {
254                 return 0;
255             }
256         }
257
258                 internal override function isEmpty():Boolean {
259                         return (deleted || (nodes.length==0));
260                 }
261
262                 public override function getType():String {
263                         return 'way';
264                 }
265                 
266                 public override function isType(str:String):Boolean {
267                         if (str=='way') return true;
268                         if (str=='line' && !isArea()) return true;
269                         if (str=='area' &&  isArea()) return true;
270                         return false;
271                 }
272                 
273                 /** Whether the way has a loop that joins back midway along its length */
274                 public function isPShape():Boolean {
275                         return getFirstNode() != getLastNode() && (!hasOnceOnly(getFirstNode()) || !hasOnceOnly(getLastNode()) );
276                 }
277                 
278                 /** Given a P-shaped way, return the index of midway node that one end connects back to. */
279                 public function getPJunctionNodeIndex():uint {
280                         if (isPShape()) {
281                             if (hasOnceOnly(getFirstNode())) {
282                                 // nodes[0] is the free end
283                                 return nodes.indexOf(getLastNode());
284                             } else {
285                                 // nodes[0] is in the loop
286                                 return nodes.lastIndexOf(getFirstNode());
287                             }
288                         }
289                         return null;
290                 }
291     }
292 }