version as used after the move to new hardware in september 2022
[osmrrze.git] / scripts / osmbuildings-json-generator.pl
index 0d6c9d86f3eb0d28ed91421d7c10e95c86061b89..d0f5a986fb11289194f974420dd2b396b5305aff 100755 (executable)
@@ -18,6 +18,7 @@ $y2 = 49.58;
 use DBI;
 use POSIX qw(strftime mktime);
 use Pg::hstore;
+use JSON;
 
 # Par. 0: Level on which this gets printed
 # Par. 1: Text
@@ -51,16 +52,60 @@ sub fetchlastofhr($$@) {
   return $res;
 }
 
+# Helper functions for the CGI variant. Taken from the openstreetmap-Wiki,
+# which in turn is almost a direct copy of a GPL'd script included in (amongst
+# others) the mapnik sourcecode. -> GPL code
+use Math::Trig;
+sub Project($$$) {
+  my ($X, $Y, $Zoom) = @_;
+  my $Unit = 1 / (2 ** $Zoom);
+  my $relY1 = $Y * $Unit;
+  my $relY2 = $relY1 + $Unit;
+  my $LimitY = pi;
+  my $RangeY = 2 * $LimitY;
+  $relY1 = $LimitY - $RangeY * $relY1;
+  $relY2 = $LimitY - $RangeY * $relY2;
+  my $Lat1 = ProjectMercToLat($relY1);
+  my $Lat2 = ProjectMercToLat($relY2);
+  $Unit = 360 / (2 ** $Zoom);
+  my $Long1 = -180 + $X * $Unit;
+  return ($Lat2, $Long1, $Lat1, $Long1 + $Unit); # S,W,N,E
+}
+sub ProjectMercToLat($) {
+  return rad2deg(atan(sinh($_[0])));
+}
+sub ProjectF($) {
+  $Lat = deg2rad($_[0]);
+  return (log(tan($Lat) + sec($Lat)));
+}
+# ----- end of copied helper functions -----
+
+# print that drops whitespace when not in verbose mode.
+sub printwows($) {
+  my $res = $_[0];
+  if ($verblev > 0) {
+    print($res); return;
+  }
+  $res =~ s/^\s+//g;
+  $res =~ s/"\s*:\s*/":/g;
+  $res =~ s/[\r\n]//g;
+  print($res);
+}
+
 # ----------------------------------------------------------------------------
 # main()
 # ----------------------------------------------------------------------------
 
+$iscgi = 0;
+
 # Parse commandline
 foreach $a (@ARGV) {
   if ($a eq '-q') {
     $verblev--;
   } elsif ($a eq '-v') {
     $verblev++;
+  } elsif ($a eq '--cgi') {
+    $iscgi = 1;
   } else {
     print("Unknown parameter: $a\n");
     print("Syntax: $0 [-q] [-v]\n");
@@ -69,6 +114,25 @@ foreach $a (@ARGV) {
   }
 }
 
+if (defined($ENV{'REQUEST_URI'})) {
+  $iscgi = 1;
+  print("Content-type: application/json; charset=utf-8\n");
+  print("Access-Control-Allow-Origin: *\n");
+  print("Cache-Control: public, max-age=3600\n");
+  print("\n");
+  unless ($ENV{'REQUEST_URI'} =~ m!(\d+)/(\d+)/(\d+)\.json$!) {
+    print("{\n\"_comment\": \"Sorry, query parameters not understood.\"\n}\n");
+    exit(0);
+  }
+  my $cgiz = int($1); my $cgix = int($2); my $cgiy = int($3);
+  #print("DEBUG: z=$cgiz x=$cgix y=$cgiy\n");
+  if ($cgiz < 15) {
+    print("{\n\"_comment\": \"No data will be returned at this zoom level.\"\n}\n");
+  }
+  ($y1, $x1, $y2, $x2) = Project($cgix, $cgiy, $cgiz);
+  #print("DEBUG: mapped to ($x1 $y1) ($x2 $y2)\n");
+}
+
 unless ($dbh = DBI->connect("dbi:Pg:dbname=$dbname","","")) {
   print(STDERR "Failed to open database. Please try again later.\n"); exit(1);
 }
@@ -77,80 +141,167 @@ $tx1 = $dbh->selectrow_array("select ST_X(ST_transform(ST_GeomFromText('POINT($x
 $ty1 = $dbh->selectrow_array("select ST_Y(ST_transform(ST_GeomFromText('POINT($x1 $y1)', 4326), 900913))");
 $tx2 = $dbh->selectrow_array("select ST_X(ST_transform(ST_GeomFromText('POINT($x2 $y2)', 4326), 900913))");
 $ty2 = $dbh->selectrow_array("select ST_Y(ST_transform(ST_GeomFromText('POINT($x2 $y2)', 4326), 900913))");
+# Why do crappy perl libraries always insist on using an "Object Oriented" interface
+# for things where this does not make any sense at all?
+my $crappyjsonoo = JSON->new()->utf8(); # Note: This has to be latin1 instead of
+# utf8 for DBI::Pg modules with version <3, because in that case, the strings we
+# get from the DB are WTF8, but are not marked as such. Therefore, we must not
+# tell the JSON module to do utf8(), because otherwise it would encode the WTF8
+# twice.
+if ($verblev > 0) {
+  $crappyjsonoo = $crappyjsonoo->pretty();
+}
 my $cntr = 0;
-print("// Note: this file has been autogenerated by $0\n");
-print("var FAUGeoJSON = {\n");
-print("  \"type\": \"FeatureCollection\",\n");
-print("  \"features\": [\n");
-foreach $table ('planet_osm_line', 'planet_osm_polygon') {
+if ($iscgi == 0) {
+  print("// Note: this file has been autogenerated by $0\n");
+  printwows("var FAUGeoJSON = {\n");
+} else {
+  printwows("{\n");
+}
+printwows("  \"type\": \"FeatureCollection\",\n");
+printwows("  \"features\": [\n");
+foreach $xtable ('planet_osm_polygon1', 'planet_osm_polygon2', 'planet_osm_line') { # 'planet_osm_polygon', 'planet_osm_line'
+  my $querypart1 = " ((tags->'building:part') is not null)";
+  my $table = 'planet_osm_polygon'; 
+  if ($xtable eq 'planet_osm_polygon1') {
+    $querypart1 = " (building is not null)";
+  } elsif ($xtable eq 'planet_osm_line') {
+    $table = $xtable;
+  }
+  # Note: && in this case is the postgis operator for 'bounding box overlaps'.
   my $sth = $dbh->prepare("select osm_id, way, building, 'tower:type', name, tags"
-                        . " from $table where"
-                        . "   (building is not null or (tags->'building:part') is not null)"
-                        . "   and way && ST_MakeEnvelope($tx1, $ty1, $tx2, $ty2)");
+                        . " from $table where $querypart1"
+                        . "   and (way && ST_MakeEnvelope($tx1, $ty1, $tx2, $ty2))");
   unless ($sth->execute()) {
-    print(STDERR "Sorry, database query exploded.!\n");
+    print(STDERR "Sorry, database query blew up.!\n");
     exit(1);
   }
   my $sth2 = $dbh->prepare("select ST_X(points) as x, ST_Y(points) as y"
-                         . " from (select ST_astext((ST_dumppoints(ST_transform(?, 4326))).geom) as points) as points");
+                         . " from (select ST_astext((ST_dumppoints(ST_transform(geometry(?), 4326))).geom) as points) as points");
+  my $sth4 = $dbh->prepare("select (ST_dumprings(?)).geom as rings");
   while ($row = $sth->fetchrow_hashref()) {
+    if ($xtable eq 'planet_osm_polygon1') {
+      my $hassubparts = $dbh->selectrow_array("select count(*)"
+                                            . " from planet_osm_line"
+                                            . " where ((tags->'building:part') is not null)"
+                                            . " and (ST_Covers(" . $dbh->quote($row->{'way'}) . ", way) = true)");
+      # The subparts usually cover the whole building, so we do NOT draw the
+      # whole building but only the subparts.
+      if ($hassubparts > 0) { next; }
+    }
     my $hstoredec;
     if (defined($row->{'tags'})) {
       $hstoredec = Pg::hstore::decode($row->{'tags'});
     }
-    my $height = fetchlastofhr(1, $hstoredec, 'levels', 'building:levels');
-    $height = $height * 2.5;
-    $height = fetchlastofhr($height, $hstoredec, 'height', 'building:height');
-    $height = sprintf("%.1f", $height);
-    my $minheight = fetchlastofhr(0, $hstoredec, 'min_levels', 'building:min_levels');
-    $minheight = $minheight * 2.5;
-    $minheight = fetchlastofhr($minheight, $hstoredec, 'min_height', 'building:min_height');
-    $minheight = sprintf("%.1f", $minheight);
+    my $levels = fetchlastofhr(1, $hstoredec, 'levels', 'building:levels');
+    my $height = fetchlastofhr(undef, $hstoredec, 'height', 'building:height');
+    unless ((defined($height)) && ($height =~ m/^[0-9.]+$/)) {
+      undef($height);
+    }
+    my $minlevel = fetchlastofhr(0, $hstoredec,
+                                 'min_levels', 'building:min_levels', 'min_level', 'building:min_level');
+    my $minheight = fetchlastofhr(undef, $hstoredec, 'min_height', 'building:min_height');
+    unless ((defined($minheight)) && ($minheight =~ m/^[0-9.]+$/)) {
+      undef($minheight);
+    }
+    my $shape = fetchlastofhr(undef, $hstoredec, 'building:shape');
+    my $material = fetchlastofhr(undef, $hstoredec,
+                                 'building:material', 'building:facade:material', 'building:cladding');
     my $wallcolor = fetchlastofhr(undef, $hstoredec, 'building:color', 'building:colour');
     my $roofcolor = fetchlastofhr(undef, $hstoredec,
                                   'roof:color', 'roof:colour', 'building:roof:color', 'building:roof:colour');
     my $roofshape = fetchlastofhr(undef, $hstoredec, 'roof:shape', 'building:roof:shape');
     my $roofheight = fetchlastofhr(undef, $hstoredec, 'roof:height', 'building:roof:height');
+    unless ((defined($roofheight)) && ($roofheight =~ m/^[0-9.]+$/)) {
+      undef($roofheight);
+    }
+    my $roofmaterial = fetchlastofhr(undef, $hstoredec, 'roof:material', 'building:roof:material');
+    if ($cntr != 0) {
+      printwows(",\n");
+    }
     $cntr++;
-    print("  {\n");
-    print("    \"type\": \"Feature\",\n");
-    print("    \"id\": $cntr,\n");
-    print("    \"geometry\": {\n");
-    print("      \"type\": \"Polygon\",\n");
-    print("      \"coordinates\": [[\n");
-    unless ($sth2->execute($row->{'way'})) {
-      print(STDERR "Sorry, decoding the way data exploded.\n");
-      exit(1);
-    }
-    my ($onex, $oney);
-    while (($onex, $oney) = $sth2->fetchrow_array()) {
-      print("        [ $onex, $oney ],\n");
-    }
-    print("      ]]\n");
-    print("    },\n");
-    print("    \"properties\": {\n");
-    print("       \"height\": $height,\n");
-    print("       \"min_height\": $minheight,\n");
+    my $jso = { "type" => "Feature" };
+    $jso->{'id'} = (defined($row->{'osm_id'}) ? $row->{'osm_id'} : $cntr);
+    if (defined($row->{'name'})) {
+      $jso->{'name'} = $row->{'name'};
+    }
+    my @waystodecode = ();
+    {
+      local $sth4->{'PrintError'};  # We're fully aware that the execute can
+      local $sth4->{'PrintWarn'};   # fail, no need to spam about it.
+      if ($sth4->execute($row->{'way'})) {
+        while ((my $nxtway) = $sth4->fetchrow_array()) {
+          push(@waystodecode, $nxtway);
+        }
+      } else {
+        push(@waystodecode, $row->{'way'});
+      }
+    }
+    my @geomarr2 = ();
+    foreach my $nxtway (@waystodecode) {
+      unless ($sth2->execute($nxtway)) {
+        print(STDERR "Sorry, decoding the way data exploded.\n");
+        exit(1);
+      }
+      my ($onex, $oney);
+      my @geomarr1 = ();
+      while (($onex, $oney) = $sth2->fetchrow_array()) {
+        my @onecoord = ( sprintf("%.5f", $onex), sprintf("%.5f", $oney));
+        push (@geomarr1, \@onecoord);
+      }
+      push(@geomarr2, \@geomarr1);
+      $sth2->finish();
+    }
+    my $geomhsh = { "type" => "Polygon",
+                    "coordinates" => \@geomarr2 };
+    $jso->{'geometry'} = $geomhsh;
+    my $prophsh = { };
+    if (defined($height)) {
+      $prophsh->{'height'} = $height;
+    }
+    if (defined($minheight)) {
+      $prophsh->{'minHeight'} = $minheight;
+    }
+    if (defined($levels)) {
+      $prophsh->{'levels'} = $levels;
+    }
+    if (defined($minlevel)) {
+      $prophsh->{'minLevel'} = $minlevel;
+    }
+    if (defined($shape)) {
+      $prophsh->{'shape'} = $shape;
+    }
+    if (defined($material)) {
+      $prophsh->{'material'} = $material;
+    }
     if (defined($wallcolor)) {
-      print("       \"wallColor\": \"$wallcolor\",\n");
+      $prophsh->{'wallColor'} = $wallcolor;
     }
     if (defined($roofcolor)) {
-      print("       \"roofColor\": \"$roofcolor\",\n");
+      $prophsh->{'roofColor'} = $roofcolor;
     }
     if (defined($roofshape)) {
-      print("       \"roofShape\": \"$roofshape\",\n");
+      if ($roofshape eq 'pyramidal') { $roofshape = 'pyramid'; }
+      $prophsh->{'roofShape'} = $roofshape;
+    }
+    if (defined($roofmaterial)) {
+      $prophsh->{'roofMaterial'} = $roofmaterial;
     }
     if (defined($roofheight)) {
-      $roofheight = sprintf("%.1f", $roofheight);
-      print("       \"roofHeight\": \"$roofheight\",\n");
+      $prophsh->{'roofHeight'} = $roofheight;
     }
-    print("    }\n");
-    print("  },\n");
+    $jso->{'properties'} = $prophsh;
+    # Now dump it all.
+    print($crappyjsonoo->encode($jso));
   }
-  $sth2->finish();
-  undef($sth2);
+  $sth4->finish();
+  undef($sth4);
   $sth->finish();
   undef($sth);
 }
-print("  ]\n");
-print("};\n");
+printwows("\n  ]\n");
+if ($iscgi == 0) {
+  print("};\n");
+} else {
+  print("}\n");
+}
This page took 0.230123 seconds and 4 git commands to generate.