Skip to main content

Tessellating shapes on top of Bing Maps in a WP7 app - part 2

In my previous post I showed how to tessellate polygons over Bing Maps control. This was a demonstration of how to achieving tessellation over the map control for a WP7 app. The problem is this is a sub-optimal solution from a UI perspective. This post shows how I've changed to code to use an asynchronous pattern for creating the polygons. The code is available for download.

The primary problem with the solution is not the actual calculation but 'where' the calculation was being performed. All the work was done on the main UI (Dispatcher) thread. Simply this means the app would freeze whilst calculating the required the polygons for the currently visible map area.

The secondary problem was overloading the UI thread with rendering requests. Obviously all the visible polygons need rendering to the screen, but if you chuck a lot of work at the UI thread nothing else in your app is going to be able to do any UI work until all those requests have been processed. This means at best you'll get a jerk response or at worst you'll app will freeze.

And finally there isn't any caching for already calculated polygons for a geo-location, why would we want to repeat the same work over and over again.

The first approach to address these issues is the introduction of a service interface exposing the polygon methods asynchronously:

public interface ICreatePolygons
{
    ISettings Settings { get; }

    Polygon Polygon(GeoCoordinate location, int sides, double diameter, double offset, double offsetBearing, double startAngle);

    IObservable<Polygon> Square(GeoCoordinate centre, double size);
    IObservable<Polygon> AdjacentSquares(Polygon polygon);
    IObservable<Polygon> TessellateVisibleSquares(LocationRect visibleRectangle, IList<Polygon> existingPolygons, double size);

    IObservable<Polygon> Hexagon(GeoCoordinate centre, double size);
    IObservable<Polygon> AdjacentHexagons(Polygon polygon);
    IObservable<Polygon> TessellateVisibleHexagons(LocationRect visibleRectangle, IList<Polygon> visiblePolygons, double size);

    IObservable<Polygon> Triangle(GeoCoordinate centre, double size);
    IObservable<Polygon> AdjacentTriangles(Polygon polygon);
    IObservable<Polygon> TessellateVisibleTriangles(LocationRect visibleRectangle, IList<Polygon> visiblePolygons, double size);
}

As you can see all the methods apart from the Polygon method all return the polygons using the Rx (Reactive extensions) approach. This allows the actual work of calculating the polygons to be done on a background worker thread and solve the primary problem with the previous solution - freezing of the UI.

Shown below is the Hexagon method, what you can see is how I schedule the work onto the thread pool using Rx:

public IObservable<Polygon> Hexagon(GeoCoordinate centre, double size)
{
    try
    {
        this.ValidateDatum();

        return Observable.Create<Polygon>(obs =>
        {
            var disposable = new BooleanDisposable();
            Scheduler.ThreadPool.Schedule(o =>
            {
                var polygon = CreateHexagonImpl(centre, size);

                if (disposable.IsDisposed)
                {
                    return;
                }

                obs.OnNext(polygon);
                obs.OnCompleted();
            });

            return disposable;
        });
    }
    catch (Exception exn)
    {
        this.log.Write(FailedHexagon, exn);
        throw new ServiceException(FailedHexagon, exn);
    }
}

The secondary problem is solved easily with the primary change in place. The addition of a pause to the thread calculating the adjacent  polygons when tessellating the polygons for the map control.

Shown below is the recursive method used to calculate the visible adjacent polygons, what you'll see is the 'Thread.SpinWait' added every time an adjacent polygon is found and notified to any subscribers of the observer. This allows the background thread to cease work for a fixed amount of time (default is 66 ms) without causing a context switch. I found using a delay of 66 ms was enough to allow other threads\controls enough time to do their stuff, in my case this was allow the map control to render & download tiles and allow the use interact with the UI.

private void AddVisibleAdjacentPolygons(LocationRect visibleRectangle,
                                        Polygon polygon, ICollection<Polygon> newPolygons,
                                        Func<Polygon, IList<Polygon>> adjacentPolygonFunc,
                                        IObserver<Polygon> observer,
                                        BooleanDisposable disposable)
{
    foreach (var adjacentPolygon in adjacentPolygonFunc(polygon))
    {
        if (disposable.IsDisposed)
        {
            return;
        }

        if (!visibleRectangle.Intersects(adjacentPolygon.TileBoundingRectangle))
        {
            continue;
        }

        if (newPolygons.Contains(adjacentPolygon))
        {
            continue;
        }

        newPolygons.Add(adjacentPolygon);
        observer.OnNext(adjacentPolygon);

        Thread.SpinWait(this.settings.Throttle);

        this.AddVisibleAdjacentPolygons(visibleRectangle, adjacentPolygon, newPolygons, adjacentPolygonFunc, observer, disposable);
    }
}

The final problem is address by a standard pattern - caching. For this I'm using the WP7Contrib caching assembly. Before I show how I use the cache provider lets look at the generation times for different polygon tessellations.

Shown below is with no caching for the initial tessellation generation for 1 mile squares (on a device not in the emulator). As you can see the duration is 8247 ms:



When I move the map around in the local vicinity you can see the durations are about half of the start-up time when caching is not enabled:



When caching for adjacent polygons is enabled we get similar result for the initial start-up:



But when you compare the subsequent requests for the local vicinity you can see the time for generating the adjacent polygons has been reduced:



This demo makes use of the WP7Contrib in memory cache provider. The code for this demo app is available on SkyDrive.

Comments

Popular posts from this blog

Implementing a busy indicator using a visual overlay in MVVM

This is a technique we use at work to lock the UI whilst some long running process is happening - preventing the user clicking on stuff whilst it's retrieving or rendering data. Now we could have done this by launching a child dialog window but that feels rather out of date and clumsy, we wanted a more modern pattern similar to the way <div> overlays are done on the web. Imagine we have the following simple WPF app and when 'Click' is pressed a busy waiting overlay is shown for the duration entered into the text box. What I'm interested in here is not the actual UI element of the busy indicator but how I go about getting this to show & hide from when using MVVM. The actual UI elements are the standard Busy Indicator coming from the WPF Toolkit : The XAML behind this window is very simple, the important part is the ViewHost. As you can see the ViewHost uses a ContentPresenter element which is bound to the view model, IMainViewModel, it contains 3 child v...

Showing a message box from a ViewModel in MVVM

I was doing a code review with a client last week for a WPF app using MVVM and they asked ' How can I show a message from the ViewModel? '. What follows is how I would (and have) solved the problem in the past. When I hear the words ' show a message... ' I instantly think you mean show a transient modal message box that requires the user input before continuing ' with something else ' - once the user has interacted with the message box it will disappear. The following solution only applies to this scenario. The first solution is the easiest but is very wrong from a separation perspective. It violates the ideas behind the Model-View-Controller pattern because it places View concerns inside the ViewModel - the ViewModel now knows about the type of the View and specifically it knows how to show a message box window: The second approach addresses this concern by introducing the idea of messaging\events between the ViewModel and the View. In the example ...

WPF tips & tricks: Dispatcher thread performance

Not blogged for an age, and I received an email last week which provoked me back to life. It was a job spec for a WPF contract where they want help sorting out the performance of their app especially around grids and tabular data. I thought I'd shared some tips & tricks I've picked up along the way, these aren't probably going to solve any issues you might be having directly, but they might point you in the right direction when trying to find and resolve performance issues with a WPF app. First off, performance is something you shouldn't try and improve without evidence, and this means having evidence proving you've improved the performance - before & after metrics for example. Without this you're basically pissing into the wind, which can be fun from a developer point of view but bad for a project :) So, what do I mean by ' Dispatcher thread performance '? The 'dispatcher thread' or the 'UI thread' is probably the most ...