WebGL polygons fill with libtess.js

kraje

Update 1.6.2015: geojson-vt seems to do great job in tiling and simplifying polygons. Check this post.

Update 18.1.2015: Vladimir Agafonkin from MapBox released earcut.js – very fast and reliable triangulation library. Worth to check. Video available here:

 

 

Original post:

Brendan Kenny from Google showed  here how he made polygons using libtess.js on Google Maps, so I have tried that too with single large enough polygon on Leaflet with CZ districts.  libtess.js is port from C code . Neither plntri.js (update: see also comments for plntri v2.0 details)  nor PolyK.js were able to triangulate large set  of points as libtess.js.

Update:  I looked on poly2tri.js  too with following results:

I could run 2256 polygons (all together > 3M vertexes)  with poly2tri  16 701 ms  vs 127 834 ms (libtess), however I  had to dirty fix  other various errors from poly2tri (null triangles or “FLIP failed due to missing triangle…so some polygons were wrong..), while  libtess was fine for the  same data.

Here is  a test :  3 M vertexes with 1 M triangles have been by generated by libtess in 127s . poly2tri took 16s.  Drawing is still fine but it is ‘just enough’ for WebGL too.

 

 

key part is listed below:


tessy.gluTessNormal(0, 0, 1);
tessy.gluTessBeginPolygon(verts);

tessy.gluTessBeginContour();

//--see blog comment below on using Array.map</span></strong>
data.features[0].geometry.coordinates[0].map(function (d, i) {
pixel = LatLongToPixelXY(d[1], d[0],0);
var coords = [pixel.x, pixel.y, 0];
tessy.gluTessVertex(coords, coords);
});

tessy.gluTessEndContour();
// finish polygon (and time triangulation process)
tessy.gluTessEndPolygon();

code available here: http://bl.ocks.org/sumbera/01cbd44a77b4283e6dcd

 

There is also EMSCRIPTEN version of the tesslib.c available on github, and I was curious whether this version would increase speed of  computation. I could run it but for large polygons (cca 120 verts of CZ boundary) I had to increase module memory to 64 MB for FireFox.  Tessellata 120T verts in  FF-30 took 21s, IE-11, Ch-36: failed  reporting out of stack memory :(

Getting back to version from Brendan  (no emscripten) I quickly measured same data on browsers: IE-11 21s, Ch-36: 31s,  FF-30: 27s .

Update Oct/2014: Polyline tessellation blog here

Modern data visualization on map

hxgn14 For this year HxGN14  conference  I have prepared a web app  of modern data vizualisation, I have got  inspired by great ideas from Victor Bret and his research and talks for general concept (high interactivity, visualization ) of this app.

It is exciting to see what is possible to do today inside browser and interactivity provided by various open source projects (e.g. leaflet,d3  and its plugins)  and WebGL technology .

iKatastr.cz 2014 – co je nového

Co je od letošního roku na iKatastr.cz nového:

– OpenLayers knihovna dělala problémy ve verzi 2.9 (dlaždice se uplně rozjížděly a neseděly v IE), OL byla povýšena na 2.12, protože ve verzi 2.13 je scrollování myší (zoom in/out)  špatné.

– iKatastr přešel z původního OLON formátu použivaném v MapShake na jednodušší konfiguraci, více propojenou s OL.

– tyto dvě výše uvedené modifikace byly důvodem toho, že jsem povypínal iKatastr v souřadném systému   JTSK  a UTM  – původní formát OLON tohle umožňoval, ale na druhou stranu to přineslo zbytečnou komplexnost kódu a nevím jestli to někdo vůbec používal (asi ne, nikdo neprotestoval) . Pokud by se měly tyto souřadné systémy do iKatastru vrátit, bude to dělané formou separátní stranky, tak jako “Ptačí pohled”

“Ptačí pohled” je k dispozici při velkém zoom – objeví se odkaz , po jehož kliknutí se načte nová stránka s krásnými šikmými snímky od Seznamu (Mapy.cz) . Ne všechny mapové podklady umí hlubší zoom, takže např. u Bing map (Microsoft)  se tohle tlačítko neobjeví.

Update 30.7.2014  Ukončeno na  žádost Seznam.cz. Puvodni funkce zachycena na tomto videu.

– Bing podklady byly přidány jako náhražka Google street – jsou rychlé a nemusí se používat Google ‘wrapper’ – Bing dlaždice lze přímo legálně konzumovat. Nicméně skvělé satelitní snímky od Googlu jsou k dispozici také.

-Udělal jsem zjednodušení legendy – uživatel nemusí překlikávat do inverzního katastru, pokud má letecké snímky – automaticky se to přehodí.

– ČÚZK spustil GetFeature info službu – takže pokud se trefíte klikem na definiční bod budovy nebo parcely objeví se základní informace.

– Experimentálně byl přidán odkaz na strážce katastru vpravo nahoře – služba umožňuje hlídání změn v katastru nemovitostí.

– IE 8,9 to je samostatná kapitola, ale vše by mělo fungovat i na těchto už exotických verzích.

 

Nakonec  za 6 měsíců ikatastr.cz hostil : 372.000 návštěv od 174,233 uživatelů, kteří shlédli celkem 488,397 stránek, strávili tam sumárně víc než 1 rok (388 dnů) a naklikali tolik dotazů, že se to nevleze na stránku

Děkuji věrným uživatelům aplikace iKatastr.cz, kteří mi dali důvod udělat upgrade aplikace !

MapBox GL – vector map open source project

Open Source OpenGL vector map rendering called MapBox GL, introduced here.  Quick  test run on iPad Air was successful and is available here :

Quotes from the site:

“Mapbox GL is based on the same vector tile format that powers Mapbox Streets. This means that you can use our global basemap, fully or in part, as well as create your own vector tiles to interleave data from different sources. Much like in TileMill, our open source map design studio, you can create a custom map by composing the various roads, parks, water areas, buildings, and more from lines, points, and polygons, then style them flexibly.”

“We built Mapbox GL in C++11 using OpenGL ES 2.0, a subset of OpenGL that is available on mobile devices and that can also run on desktop hardware with very minor changes. We use protocol buffers via pbf.hpp to implement a lazy vector tile parser, plus we’ve implemented custom code for text display and layout.

Mapbox GL is open source under a permissive BSD license, so you can check out all of the code right now. It currently runs on iOS, OS X, and Linux.”

Leaflet WebGL many points rendering

WebGL is funny – programming in very low level style in JavaScript. This sample plots 86T points using this technology.  .

 

 

 

The code is very straightforward, the only thing is to how points are initially loaded and scaled (instead of reloading each time when map moves).

All points are initially transformed to tile size of 256 x 256 pixels at zoom level 0  and then re-scaled/re-shifted based on the current position of the map. drawingOnCanvas is called from L.CanvasOverlay each time map needs to be drawn (move, zoom)

 


function drawingOnCanvas(canvasOverlay, params) {
  gl.clear(gl.COLOR_BUFFER_BIT);
  // -- set base matrix to translate canvas pixel coordinates -> webgl coordinates
 mapMatrix.set(pixelsToWebGLMatrix);
  var bounds = leafletMap.getBounds();
  var topLeft = new L.LatLng(bounds.getNorth(), bounds.getWest());
  var offset = LatLongToPixelXY(topLeft.lat, topLeft.lng);
  // -- Scale to current zoom
  var scale = Math.pow(2, leafletMap.getZoom());
 scaleMatrix(mapMatrix, scale, scale);
 translateMatrix(mapMatrix, -offset.x, -offset.y);
  // -- attach matrix value to 'mapMatrix' uniform in shader
  gl.uniformMatrix4fv(u_matLoc, false, mapMatrix);
 gl.drawArrays(gl.POINTS, 0, numPoints);
}

More information and insipiration I took from this site

demo here: http://bl.ocks.org/sumbera/c6fed35c377a46ff74c3

For polygons rendering check here and for polyline rendering here

Some good intros to WebGL that might help you to understand the code: http://aerotwist.com/presentations/custom-filters/#/6

There is a nice intro book to WebGL  WebGL Programming Guide by Kouchi Matsuda and Rodger Lea

To illustrate how variables are passed from JavaScript to shaders used in above example, here are two figures from the book-  figure 5.7 on p. 149, and figure 5.3 on p.144.

strideoffset
Stride and Offset

This figure shows single buffer (interleaved)that is used fro both coordinates and size. In similar way single buffer is constructed in the example here:

 

 

 

var vertBuffer = gl.createBuffer();
var vertArray = new Float32Array(verts);
var fsize = vertArray.BYTES_PER_ELEMENT;

gl.bindBuffer(gl.ARRAY_BUFFER, vertBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertArray, gl.STATIC_DRAW);
gl.vertexAttribPointer(vertLoc, 2, gl.FLOAT, false,fsize*5,0);
gl.enableVertexAttribArray(vertLoc);
// -- offset for color buffer
gl.vertexAttribPointer(colorLoc, 3, gl.FLOAT, false, fsize*5, fsize*2);
gl.enableVertexAttribArray(colorLoc);

 

shadervariables2
behavior of a varying variable

Windows Phone development saga

Update 10.10.2017. The saga, Windows Phone, ends – nice review of the years here

Great article in Czech Language by Martin Suchan on Windows Phone 8.1 development     two great pictures (most likely he made)  I am reposting here showing fragmentation of Windows Phone development. Universal apps introduced in Build 2014 conference  means something totally different of what I have used to work with on iOS.

 

dd8_evolucewp

 

631_wp81diagram

source : http://smartmania.cz/clanky/podrobny-prehled-novinek-ve-windows-phone-81-pro-vyvojare-1-dil-7403

WMS overlay on Windows 8.1 and Windows Phone 8.1

wp_ss_20140523_0001I agree with this blog “Learning how to use Maps in the .Net world is a never ending business. There are major API-differences between WPF, Silverlight, Windows 8 Store apps and Windows Phone and even between WP7 and WP8. Windows Phone 8.1 makes no differ and there are many breaking changes here”

my tests of previous WMS overlays are listed here:

Silverlight : http://blog.sumbera.com/2010/02/25/overlay-wms-on-silverlight-bing/
Windows Phone 7: http://blog.sumbera.com/2011/02/18/windows-phone-7-wms-test/
Windows Phone 8: http://blog.sumbera.com/2013/03/10/tiled-wms-overlay-in-windows-phone-8/

I have put together Visual studio 2013, Update2 Solution that does WMS overlay in Windows 8.1 and Windows Phone 8.1 called WMSonWin81 – here on github

Video of Windows Phone 8.1 below, used “Project My Screen App” to project the app on desktop and record.

WMSonWin81
WMSonWin81using universal app for Windows Store and Windows Phone Store apps Both apps do not share same namespace for map nor component. Windows Store is using Bing Map while Windows Phone is using map control as part of the WP8.1 framework located in Windows.UI.Xaml.Controls.Maps

there are main 2 projects:

WMSOnWin.Windows
Sample code of using WMS source on Windows Store Apps using Bing Maps:

MapTileLayer mapTileLayer = new MapTileLayer();
     mapTileLayer.GetTileUri += delegate(object sender, GetTileUriEventArgs e) {
     Rect mercBounds = GlobalMercator.TileBounds(new Tile(e.X, e.Y), e.LevelOfDetail);
     e.Uri = new Uri(string.Format(_wmsUrl, mercBounds.Left, 
           Math.Abs(mercBounds.Bottom), mercBounds.Right, Math.Abs(mercBounds.Top)));
 };

_bingMap.TileLayers.Add(mapTileLayer);
WMSOnWin.WindowsPhone

Sample code of using WMS on Windows Phone Store App using Windows.UI.Xaml.Controls.Maps; core class to look is HttpMapTileDataSource

    HttpMapTileDataSource dataSource = new HttpMapTileDataSource();
         dataSource.UriRequested += 
 new TypedEventHandler<HttpMapTileDataSource, MapTileUriRequestedEventArgs>(
 (source, args) => {
    Rect mercBounds = GlobalMercator.TileBounds(
                           new Tile(args.X, args.Y), args.ZoomLevel);
    args.Request.Uri = new Uri(string.Format(_wmsUrl, mercBounds.Left,
    Math.Abs(mercBounds.Bottom), mercBounds.Right, Math.Abs(mercBounds.Top))); ;
 });
  _map.TileSources.Add(new MapTileSource(dataSource));

Tested on Windows 8.1 64bit, and Lumia 810, Windows Phone 8.1

enjoy.

Credits: got help here to repair problems with USB connection to my Lumia 810 (had to uninstall USB driver for the phone in device manager)  and here to get WP8.1 on Lumia 810

WMS on MapKit with iOS7

Updated WMS over MapKit sample code for iOS7 , available on github  I have added cadastral maps of Czech Republic, used camera API to set the view and tested, check also WMS on Google  Maps SDK on iOS mentioned here

iOS7 introduced new class MKTileOverlay sample derives from this class WMSTileOverlay

Key method to custom tile loading (and cache control) is loadTileAtPath:result

- (void)loadTileAtPath:(MKTileOverlayPath)path result:(void (^)(NSData *tileData, NSError *error))  result

this method is called by MapKit (or better by MKTileOverlayRenderer ) when it needs to draw a tile . It asks for NSData (and error) from x,y,z tile coordinates. In this method you can  load NSData either from local cache or from NSURLConnection and pass resulting NSData (when ready)  back to MapKit, for example like this (reading from cache)

result ([NSData dataWithContentsOfFile:filePath], nil);

if you do not need to use cache and you do not provide loadTileAtPath method , you can use another hook (callback) that is provided by MKTileOverlay, URLForTilePath:path

- (NSURL *)URLForTilePath:(MKTileOverlayPath)path

this method enables to custom format URL required to load tile, thus you can use WMS HTTP-GET parameters, for example :

NSString * resolvedUrl = [NSString stringWithFormat:@"%@&BBOX=%f,%f,%f,%f",self.url,left,bottom,right,top];

if there is neither method in the derived class, then you probably do not need to derive at all from MKTileOverlay and directly use it with initWithUrlTemplate (not case for WMS, but for any other x,y,z  sources)

IMG_0021

Bad news is that  MapKit on iOS7 doesn’t support   tilt/pinch in Satellite/Hybrid mode in MapKit on iOS7

Data Visualisation with d3.js Cookbook

datavisbookbought this great book on  d3.js (Data-Driven documents), written by  Nick Qi Zhu

D3 can plot map in various projections, however do not expect to get same set of (overlapping) functionality as Leaflet or OpenLayers. D3 can extend these mapping frameworks. For OL3 simple  example is here for Leaflet, my favourite is  hexbins or check my own experiment here.

While D3 is kind of ‘base’ charting library (lot of utility functions, helpers) , there is upper , high level library too  that can provide lot of ‘boilerplate’ for common charts. Here comes great news:

Nick Qi Zhu   is also author of the open source javascript  lib dc.js   (Dimensional Charting) library  that is using crossfilter (Fast Multidimensional Filtering for Coordinated Views) . Part of the dc.js lib is set of most common charts and one of them is choropleth map .

Other resources:

D3 Animation : http://blog.visual.ly/creating-animations-and-transitions-with-d3-js/

Design selections: http://www.awwwards.com/fresh-ui-inspiration-in-the-era-of-google-material-and-design-patterns.html