8206aefe252ae5e049203bd2fd94d85f5be8e7d7
[potlatch2.git] / net / systemeD / halcyon / MapPaint.as
1 package net.systemeD.halcyon {
2
3         import flash.display.Sprite;
4         import flash.display.DisplayObject;
5         import net.systemeD.halcyon.NodeUI;
6         import net.systemeD.halcyon.WayUI;
7         import net.systemeD.halcyon.connection.*;
8         import net.systemeD.halcyon.connection.actions.CreatePOIAction;
9         import net.systemeD.halcyon.styleparser.RuleSet;
10
11         /** Manages the drawing of map entities, allocating their sprites etc. */
12         public class MapPaint extends Sprite {
13                 
14                 /** Parent Map - required for finding out bounds and scale */
15                 public var map:Map;
16
17                 /** Source data for this MapPaint layer */
18                 public var connection:Connection;
19
20                 /** Lowest OSM layer that can be displayed */
21                 public var minlayer:int;
22                 /** Highest OSM layer that can be displayed */
23                 public var maxlayer:int;
24                 /** The MapCSS rules used for drawing entities. */
25                 public var ruleset:RuleSet;                                             
26                 /** WayUI objects attached to Way entities that are currently visible. */
27                 private var wayuis:Object=new Object();
28                 /** NodeUI objects attached to POI/tagged node entities that are currently visible. */
29                 private var nodeuis:Object=new Object();
30                 /** MarkerUI objects attached to Marker entities that are currently visible. */
31         private var markeruis:Object=new Object();
32         /** Is this a background layer or the core paint object? */
33                 public var isBackground:Boolean = true;
34                 /** Hash of index->position */
35                 public var sublayerIndex:Object={};
36
37         /** The url of the style in use */
38         public var style:String = '';
39
40                 private const VERYBIG:Number=Math.pow(2,16);
41                 private static const NO_LAYER:int=-99999;               // same as NodeUI
42
43                 // Set up layering
44
45                 /** Creates paint sprites and hit sprites for all layers in range. This object ends up with a series of child sprites
46                  * as follows: p0,p1,p2..px, h0,h1,h2..hx where p are "paint sprites" and "h" are "hit sprites". There is one of each type for each layer.
47                  * <p>Each paint sprite has 4 child sprites (fill, casing, stroke, names). Each hit sprite has 2 child sprites (way hit tests, node hit tests).</p>  
48                  * <p>Thus if layers range from -5 to +5, there will be 11 top level paint sprites followed by 11 top level hit sprites.</p>
49                  * 
50                  * @param map The Map this is attached to. (Required for finding out bounds and scale.)
51                  * @param connection The Connection containing the data for this layer.
52                  * @param minlayer The lowest OSM layer to display.
53                  * @param maxlayer The highest OSM layer to display.
54                  * */ 
55                 public function MapPaint(map:Map, connection:Connection, styleurl:String, minlayer:int, maxlayer:int) {
56                         mouseEnabled=false;
57
58                         this.map=map;
59                         this.connection=connection;
60                         this.minlayer=minlayer;
61                         this.maxlayer=maxlayer;
62                         sublayerIndex[1]=0;
63                         var s:Sprite, l:int;
64
65                         // Set up stylesheet
66                         setStyle(styleurl);
67
68                         // Listen for changes on this Connection
69             connection.addEventListener(Connection.NEW_WAY, newWayCreatedListener);
70             connection.addEventListener(Connection.NEW_POI, newPOICreatedListener);
71             connection.addEventListener(Connection.WAY_RENUMBERED, wayRenumberedListener);
72             connection.addEventListener(Connection.NODE_RENUMBERED, nodeRenumberedListener);
73             connection.addEventListener(Connection.NEW_MARKER, newMarkerCreatedListener);
74
75                         // Add paint sprites
76                         for (l=minlayer; l<=maxlayer; l++) {                    // each layer (10 is +5, 0 is -5)
77                                 s = getPaintSprite();                                           //      |
78                                 var q:Sprite = getPaintSprite();                        //      | 0 fill
79                                 q.addChild(getPaintSprite());                           //      |  | sublayer
80                                 s.addChild(q);                                                          //  |  |
81                                 s.addChild(getPaintSprite());                           //      | 1 casing
82                                 var t:Sprite = getPaintSprite();                        //      | 2 stroke
83                                 t.addChild(getPaintSprite());                           //      |  | sublayer
84                                 s.addChild(t);                                                          //      |  |
85                                 s.addChild(getPaintSprite());                           //      | 3 names
86                                 addChild(s);                                                            //      |
87                         }
88                         
89                         // Add hit sprites
90                         for (l=minlayer; l<=maxlayer; l++) {                    // each layer (21 is +5, 11 is -5)
91                                 s = getHitSprite();                                                     //      |
92                                 s.addChild(getHitSprite());                                     //      | 0 way hit tests
93                                 s.addChild(getHitSprite());                                     //      | 1 node hit tests
94                                 addChild(s);
95                         }
96                 }
97                 
98                 /** Returns the paint surface for the given layer. */
99                 public function getPaintSpriteAt(l:int):Sprite {
100                         return getChildAt(l-minlayer) as Sprite;
101                 }
102
103                 /** Returns the hit sprite for the given layer. */
104                 public function getHitSpriteAt(l:int):Sprite {
105                         return getChildAt((l-minlayer) + (maxlayer-minlayer+1)) as Sprite;
106                 }
107                 
108                 /** Is ruleset loaded? */
109                 public function get ready():Boolean {
110                         if (!ruleset) { return false; }
111                         if (!ruleset.loaded) { return false; }
112                         return true;
113                 }
114
115                 public function sublayer(layer:int,spritetype:uint,sublayer:Number):Sprite {
116                         var l:DisplayObject;
117                         var o:DisplayObject;
118                         var index:String, ix:Number;
119                         if (!sublayerIndex.hasOwnProperty(sublayer)) {
120                                 // work out which position to add at
121                                 var lowestAbove:Number=VERYBIG;
122                                 var lowestAbovePos:int=-1;
123                                 var indexLength:uint=0;
124                                 for (index in sublayerIndex) {
125                                         ix=Number(index);
126                                         if (ix>sublayer && ix<lowestAbove) {
127                                                 lowestAbove=ix;
128                                                 lowestAbovePos=sublayerIndex[index];
129                                         }
130                                         indexLength++;
131                                 }
132                                 if (lowestAbovePos==-1) { lowestAbovePos=indexLength; }
133                         
134                                 // add sprites
135                                 for (var i:int=minlayer; i<=maxlayer; i++) {
136                                         l=getChildAt(i-minlayer);
137                                         o=(l as Sprite).getChildAt(0); (o as Sprite).addChildAt(getPaintSprite(),lowestAbovePos);       // fillsprite
138                                         o=(l as Sprite).getChildAt(2); (o as Sprite).addChildAt(getPaintSprite(),lowestAbovePos);       // strokesprite
139                                 }
140                         
141                                 // update index
142                                 // (we do it in this rather indirect way because if you alter sublayerIndex directly
143                                 //      within the loop, it confuses the iterator)
144                                 var toUpdate:Array=[];
145                                 for (index in sublayerIndex) {
146                                         ix=Number(index);
147                                         if (ix>sublayer) { toUpdate.push(index); }
148                                 }
149                                 for each (index in toUpdate) { sublayerIndex[index]++; }
150                                 sublayerIndex[sublayer]=lowestAbovePos;
151                         }
152
153                         l=getChildAt(layer-minlayer);
154                         o=(l as Sprite).getChildAt(spritetype);
155                         return ((o as Sprite).getChildAt(sublayerIndex[sublayer]) as Sprite);
156                 }
157
158         /**
159         * Update, and if necessary, create / remove UIs for the current viewport.
160         * Flags control redrawing existing entities and removing UIs from entities no longer in view.
161         *
162         * @param redraw If true, all UIs for entities on "inside" lists will be redrawn
163         * @param remove If true, all UIs for entites on "outside" lists will be removed. The purgable flag on UIs
164                         can override this, for example for selected objects.
165         * fixme? add smarter behaviour for way nodes - remove NodeUIs from way nodes off screen, create them for ones
166         * that scroll onto screen (for highlights etc)
167         */
168                 public function updateEntityUIs(redraw:Boolean, remove:Boolean):void {
169                         var way:Way, poi:Node, marker:Marker;
170                         var o:Object = connection.getObjectsByBbox(map.edge_l,map.edge_r,map.edge_t,map.edge_b);
171
172                         for each (way in o.waysInside) {
173                                 if (!wayuis[way.id]) { createWayUI(way); }
174                                 else if (redraw) { wayuis[way.id].recalculate(); wayuis[way.id].redraw(); }
175                                 else wayuis[way.id].updateHighlights();//dubious
176                         }
177
178                         if (remove) {
179                                 for each (way in o.waysOutside) {
180                                         if (wayuis[way.id] && !wayuis[way.id].purgable) {
181                                                 if (redraw) { wayuis[way.id].recalculate(); wayuis[way.id].redraw(); }
182                                         } else {
183                                                 deleteWayUI(way);
184                                         }
185                                 }
186                         }
187
188                         for each (poi in o.poisInside) {
189                                 if (!nodeuis[poi.id]) { createNodeUI(poi); }
190                                 else if (redraw) { nodeuis[poi.id].redraw(); }
191                         }
192
193                         if (remove) {
194                                 for each (poi in o.poisOutside) { 
195                                         if (nodeuis[poi.id] && !nodeuis[poi.id].purgable) {
196                                                 if (redraw) { nodeuis[poi.id].redraw(); }
197                                         } else {
198                                                 deleteNodeUI(poi);
199                                         }
200                                 }
201                         }
202
203             for each (marker in o.markersInside) {
204                 if (!markeruis[marker.id]) { createMarkerUI(marker); }
205                 else if (redraw) { markeruis[marker.id].redraw(); }
206             }
207
208             if (remove) {
209                 for each (marker in o.markersOutside) {
210                     if (markeruis[marker.id] && !markeruis[marker.id].purgable) {
211                         if (redraw) { markeruis[marker.id].redraw(); }
212                     } else {
213                         deleteMarkerUI(marker);
214                     }
215                 }
216             }
217                 }
218
219                 /** Make a UI object representing a way. */
220                 public function createWayUI(way:Way):WayUI {
221                         if (!wayuis[way.id]) {
222                                 wayuis[way.id]=new WayUI(way,this);
223                                 way.addEventListener(Connection.WAY_DELETED, wayDeleted);
224                         } else {
225                                 wayuis[way.id].redraw();
226                         }
227                         return wayuis[way.id];
228                 }
229
230                 /** Respond to event by removing the WayUI. */
231                 public function wayDeleted(event:EntityEvent):void {
232                         deleteWayUI(event.entity as Way);
233                 }
234
235                 /** Remove a way's UI object. */
236                 public function deleteWayUI(way:Way):void {
237                         way.removeEventListener(Connection.WAY_DELETED, wayDeleted);
238                         if (wayuis[way.id]) {
239                                 wayuis[way.id].redrawMultis();
240                                 wayuis[way.id].removeSprites();
241                                 wayuis[way.id].removeEventListeners();
242                                 wayuis[way.id].removeListenSprite();
243                                 delete wayuis[way.id];
244                         }
245                         for (var i:uint=0; i<way.length; i++) {
246                                 var node:Node=way.getNode(i);
247                                 if (nodeuis[node.id]) { deleteNodeUI(node); }
248                         }
249                 }
250
251                 /** Make a UI object representing a node. */
252                 public function createNodeUI(node:Node,rotation:Number=0,layer:int=NO_LAYER,stateClasses:Object=null):NodeUI {
253                         if (!nodeuis[node.id]) {
254                                 nodeuis[node.id]=new NodeUI(node,this,rotation,layer,stateClasses);
255                                 node.addEventListener(Connection.NODE_DELETED, nodeDeleted);
256                         } else {
257                                 for (var state:String in stateClasses) {
258                                         nodeuis[node.id].setStateClass(state,stateClasses[state]);
259                                 }
260                                 nodeuis[node.id].redraw();
261                         }
262                         return nodeuis[node.id];
263                 }
264
265                 /** Respond to event by deleting NodeUI. */
266                 public function nodeDeleted(event:EntityEvent):void {
267                         deleteNodeUI(event.entity as Node);
268                 }
269
270                 /** Remove a node's UI object. */
271                 public function deleteNodeUI(node:Node):void {
272                         node.removeEventListener(Connection.NODE_DELETED, nodeDeleted);
273                         if (!nodeuis[node.id]) { return; }
274                         nodeuis[node.id].removeSprites();
275                         nodeuis[node.id].removeEventListeners();
276                         nodeuis[node.id].removeListenSprite();
277                         delete nodeuis[node.id];
278                 }
279
280         /** Make a UI object representing a marker. */
281         public function createMarkerUI(marker:Marker,rotation:Number=0,layer:int=NO_LAYER,stateClasses:Object=null):MarkerUI {
282             if (!markeruis[marker.id]) {
283                 markeruis[marker.id]=new MarkerUI(marker,this,rotation,layer,stateClasses);
284                 marker.addEventListener(Connection.NODE_DELETED, markerDeleted);
285             } else {
286                 for (var state:String in stateClasses) {
287                     markeruis[marker.id].setStateClass(state,stateClasses[state]);
288                 }
289                 markeruis[marker.id].redraw();
290             }
291             return markeruis[marker.id];
292         }
293
294         /** Respond to event by deleting MarkerUI. */
295         public function markerDeleted(event:EntityEvent):void {
296             deleteMarkerUI(event.entity as Marker);
297         }
298
299         /** Remove a marker's UI object. */
300         public function deleteMarkerUI(marker:Marker):void {
301             marker.removeEventListener(Connection.NODE_DELETED, markerDeleted);
302             if (!markeruis[marker.id]) { return; }
303             markeruis[marker.id].removeSprites();
304             markeruis[marker.id].removeEventListeners();
305             markeruis[marker.id].removeListenSprite();
306             delete markeruis[marker.id];
307         }
308                 
309                 public function renumberWayUI(way:Way,oldID:Number):void {
310                         if (!wayuis[oldID]) { return; }
311                         wayuis[way.id]=wayuis[oldID];
312                         delete wayuis[oldID];
313                 }
314
315                 public function renumberNodeUI(node:Node,oldID:Number):void {
316                         if (!nodeuis[oldID]) { return; }
317                         nodeuis[node.id]=nodeuis[oldID];
318                         delete nodeuis[oldID];
319                 }
320
321                 /** Make a new sprite for painting on */
322                 private function getPaintSprite():Sprite {
323                         var s:Sprite = new Sprite();
324                         s.mouseEnabled = false;
325                         s.mouseChildren = false;
326                         return s;
327                 }
328
329                 private function getHitSprite():Sprite {
330                         var s:Sprite = new Sprite();
331                         return s;
332                 }
333
334                 /** Redraw all entities */
335                 public function redraw():void {
336                         for each (var w:WayUI in wayuis) { w.recalculate(); w.invalidateStyleList(); w.redraw(); }
337                         /* sometimes (e.g. in Map.setStyle) Mappaint.redrawPOIs() is called immediately afterwards anyway. FIXME? */
338                         for each (var p:NodeUI in nodeuis) { p.invalidateStyleList(); p.redraw(); }
339             for each (var m:MarkerUI in markeruis) { m.invalidateStyleList(); m.redraw(); }
340                 }
341
342                 /** Redraw nodes and markers only */
343                 public function redrawPOIs():void {
344                         for each (var p:NodeUI in nodeuis) { p.invalidateStyleList(); p.redraw(); }
345             for each (var m:MarkerUI in markeruis) { m.invalidateStyleList(); m.redraw(); }
346                 }
347                 
348                 /** Redraw a single entity if it exists */
349                 public function redrawEntity(e:Entity):Boolean {
350                         if      (e is Way    && wayuis[e.id]) wayuis[e.id].redraw();
351                         else if (e is Node   && nodeuis[e.id]) nodeuis[e.id].redraw();
352                         else if (e is Marker && markeruis[e.id]) markeruis[e.id].redraw();
353                         else return false;
354                         return true;
355                 }
356                 
357                 /** Switch to new MapCSS. */
358                 public function setStyle(url:String):void {
359             style = url;
360                         ruleset=new RuleSet(map.MINSCALE,map.MAXSCALE,redraw,redrawPOIs);
361                         ruleset.loadFromCSS(url);
362         }
363
364                 // ==================== Start of code moved from Map.as
365
366                 // Listeners for Connection events
367
368         private function newWayCreatedListener(event:EntityEvent):void {
369             var way:Way = event.entity as Way;
370                         if (!way.loaded || !way.within(map.edge_l, map.edge_r, map.edge_t, map.edge_b)) { return; }
371                         createWayUI(way);
372         }
373
374         private function newPOICreatedListener(event:EntityEvent):void {
375             var node:Node = event.entity as Node;
376                         if (!node.within(map.edge_l, map.edge_r, map.edge_t, map.edge_b)) { return; }
377                         createNodeUI(node);
378         }
379
380         private function newMarkerCreatedListener(event:EntityEvent):void {
381             var marker:Marker = event.entity as Marker;
382             if (!marker.within(map.edge_l, map.edge_r, map.edge_t, map.edge_b)) { return; }
383             createMarkerUI(marker);
384         }
385
386                 private function wayRenumberedListener(event:EntityRenumberedEvent):void {
387             var way:Way = event.entity as Way;
388                         renumberWayUI(way,event.oldID);
389                 }
390
391                 private function nodeRenumberedListener(event:EntityRenumberedEvent):void {
392             var node:Node = event.entity as Node;
393                         renumberNodeUI(node,event.oldID);
394                 }
395
396         /** Visually mark an entity as highlighted. */
397         public function setHighlight(entity:Entity, settings:Object):void {
398                         if      ( entity is Way  && wayuis[entity.id] ) { wayuis[entity.id].setHighlight(settings);  }
399                         else if ( entity is Node && nodeuis[entity.id]) { nodeuis[entity.id].setHighlight(settings); }
400         }
401
402         public function setHighlightOnNodes(way:Way, settings:Object):void {
403                         if (wayuis[way.id]) wayuis[way.id].setHighlightOnNodes(settings);
404         }
405
406                 public function protectWay(way:Way):void {
407                         if (wayuis[way.id]) wayuis[way.id].protectSprites();
408                 }
409
410                 public function unprotectWay(way:Way):void {
411                         if (wayuis[way.id]) wayuis[way.id].unprotectSprites();
412                 }
413                 
414                 public function limitWayDrawing(way:Way,except:Number=NaN,only:Number=NaN):void {
415                         if (!wayuis[way.id]) return;
416                         wayuis[way.id].drawExcept=except;
417                         wayuis[way.id].drawOnly  =only;
418                         wayuis[way.id].redraw();
419                 }
420
421                 /** Protect Entities and EntityUIs against purging. This prevents the currently selected items
422                    from being purged even though they're off-screen. */
423
424                 public function setPurgable(entities:Array, purgable:Boolean):void {
425                         for each (var entity:Entity in entities) {
426                                 entity.locked=!purgable;
427                                 if ( entity is Way  ) {
428                                         var way:Way=entity as Way;
429                                         if (wayuis[way.id]) { wayuis[way.id].purgable=purgable; }
430                                         for (var i:uint=0; i<way.length; i++) {
431                                                 var node:Node=way.getNode(i)
432                                                 node.locked=!purgable;
433                                                 if (nodeuis[node.id]) { nodeuis[node.id].purgable=purgable; }
434                                         }
435                                 } else if ( entity is Node && nodeuis[entity.id]) { 
436                                         nodeuis[entity.id].purgable=purgable;
437                                 }
438                         }
439                 }
440
441                 // ==================== End of code moved from Map.as
442
443                 /** Find all ways whose WayUI passes a given screen co-ordinate. */
444                 
445                 public function findWaysAtPoint(x:Number, y:Number, ignore:Way=null):Array {
446                         var ways:Array=[]; var w:Way;
447                         for each (var wayui:WayUI in wayuis) {
448                                 w=wayui.hitTest(x,y);
449                                 if (w && w!=ignore) { ways.push(w); }
450                         }
451                         return ways;
452                 }
453
454         /**
455         * Transfers an entity from this layer into another layer
456         * @param entity The entity from this layer that you want to transfer.
457         * @param target The layer to transfer to
458         *
459         * @return either the newly created entity, or null
460         */
461         public function pullThrough(entity:Entity, target:MapPaint):Entity {
462             // TODO - check the entity actually resides in this layer.
463
464             var action:CompositeUndoableAction = new CompositeUndoableAction("pull through");
465             if (entity is Way) {
466                 // copy way through to main layer
467                 var oldWay:Way=Way(entity);
468                 var nodemap:Object={};
469                 var nodes:Array=[];
470                 var oldNode:Node, newNode:Node;
471                 for (var i:uint=0; i<oldWay.length; i++) {
472                     oldNode = oldWay.getNode(i);
473                     if (nodemap[oldNode.id])
474                         newNode=nodemap[oldNode.id];
475                     else if (target.connection.identicalNode(oldNode))
476                         newNode=target.connection.identicalNode(oldNode);
477                     else
478                         newNode = target.connection.createNode(oldNode.getTagsCopy(), oldNode.lat, oldNode.lon, action.push);
479                     nodes.push(newNode);
480                     nodemap[oldNode.id]=newNode;
481                 }
482                 oldWay.remove(action.push);
483                 var newWay:Way=target.connection.createWay(oldWay.getTagsCopy(), nodes, action.push);
484                 MainUndoStack.getGlobalStack().addAction(action);
485                 return newWay;
486
487             } else if (entity is Node && !entity.hasParentWays) {
488
489                 oldNode=Node(entity);
490
491                 var newPoiAction:CreatePOIAction = new CreatePOIAction(
492                     target.connection, oldNode.getTagsCopy(), oldNode.lat, oldNode.lon);
493                 action.push(newPoiAction);
494
495                 oldNode.remove(action.push);
496
497                 MainUndoStack.getGlobalStack().addAction(action);
498                 return newPoiAction.getNode();
499             }
500             return null;
501         }
502
503         }
504 }