Use x,y,level vector tile to produce imagery for newX,newY,newLevel
495272
function overzoomGeometry(rings, nativeTile, newExtent, newTile) {
  var diffZ = newTile.level - nativeTile.level;
  if (diffZ === 0) {
    return rings;
  } else {
    var newRings = [];
    // (offsetX, offsetY) is the (0,0) of the new tile
    var offsetX = newExtent * (newTile.x - (nativeTile.x << diffZ));
    var offsetY = newExtent * (newTile.y - (nativeTile.y << diffZ));
    for (var i = 0; i < rings.length; i++) {
      var ring = [];
      for (var i2 = 0; i2 < rings[i].length; i2++) {
        ring.push(rings[i][i2].sub(new Point(offsetX, offsetY)));
      }
      newRings.push(ring);
    }
    return newRings;
  }
}
45106
function (renderer, dx, dy, tmxTile) {

            // check if any transformation is required
            if (tmxTile.flipped) {
                renderer.save();
                // apply the tile current transform
                renderer.translate(dx, dy);
                renderer.transform(tmxTile.currentTransform);
                // reset both values as managed through transform();
                dx = dy = 0;
            }

            // check if the tile has an associated image
            if (this.isCollection === true) {
                // draw the tile
                renderer.drawImage(
                    this.imageCollection[tmxTile.tileId],
                    0, 0,
                    tmxTile.width, tmxTile.height,
                    dx, dy,
                    tmxTile.width, tmxTile.height
                );
            } else {
                // use the tileset texture
                var offset = this.atlas[this.getViewTileId(tmxTile.tileId)].offset;
                // draw the tile
                renderer.drawImage(
                    this.image,
                    offset.x, offset.y,
                    this.tilewidth, this.tileheight,
                    dx, dy,
                    this.tilewidth + renderer.uvOffset, this.tileheight + renderer.uvOffset
                );
            }

            if (tmxTile.flipped)  {
                // restore the context to the previous state
                renderer.restore();
            }
        }
793895
public AffineTransform metersToTilePixelsTransform(int tx, int ty, int zoomLevel) {
        AffineTransform result = new AffineTransform();
        double scale = 1.0 / resolution(zoomLevel);
        int nTiles = 2 << (zoomLevel - 1);
        int px = tx * -256;
        int py = (nTiles - ty) * -256;
        // flip y for upper-left origin
        result.scale(1, -1);
        result.translate(px, py);
        result.scale(scale, scale);
        result.translate(originShift, originShift);
        return result;
    }
195338
function wRectangleTiles (z, wr) {
    const [wMinx, wMiny, wMaxx, wMaxy] = wr;
    const n = (1 << z); // for 0 <= z <= 30 equals Math.pow(2, z)

    const clamp = x => Math.min(Math.max(x, 0), n - 1);
    // compute tile coordinate ranges
    const tMinx = clamp(Math.floor(n * (wMinx + 1) * 0.5));
    const tMaxx = clamp(Math.ceil(n * (wMaxx + 1) * 0.5) - 1);
    const tMiny = clamp(Math.floor(n * (1 - wMaxy) * 0.5));
    const tMaxy = clamp(Math.ceil(n * (1 - wMiny) * 0.5) - 1);
    let tiles = [];
    for (let x = tMinx; x <= tMaxx; ++x) {
        for (let y = tMiny; y <= tMaxy; ++y) {
            tiles.push({ x: x, y: y, z: z });
        }
    }
    return tiles;
}
127565
function (ctx, size, texMeters) {

    if (this.data.grid == 'none') return;

    // one grid feature each 2 meters

    var num = Math.floor(texMeters / 2);
    var step = size / (texMeters / 2); // 2 meters == <step> pixels
    var i, j, ii;

    ctx.fillStyle = this.data.gridColor;

    switch (this.data.grid) {
      case '1x1':
      case '2x2': {
        if (this.data.grid == '1x1') {
          num = num * 2;
          step = size / texMeters;
        }
        for (i = 0; i < num; i++) {
          ii = Math.floor(i * step);
          ctx.fillRect(0, ii, size, 1);
          ctx.fillRect(ii, 0, 1, size);
        }
        break;
      }
      case 'crosses': {
        var l = Math.floor(step / 20);
        for (i = 0; i < num + 1; i++) {
          ii = Math.floor(i * step);
          for (j = 0; j < num + 1; j++) {
            var jj = Math.floor(-l + j * step);
            ctx.fillRect(jj, ii, l * 2, 1);
            ctx.fillRect(ii, jj, 1, l * 2);
          }
        }
        break;
      }
      case 'dots': {
        for (i = 0; i < num + 1; i++) {
          for (j = 0; j < num + 1; j++) {
            ctx.beginPath(); ctx.arc(Math.floor(j * step), Math.floor(i * step), 4, 0, Math.PI * 2); ctx.fill();
          }
        }
        break;
      }
      case 'xlines': {
        for (i = 0; i < num; i++) {
          ctx.fillRect(Math.floor(i * step), 0, 1, size);
        }
        break;
      }
      case 'ylines': {
        for (i = 0; i < num; i++) {
          ctx.fillRect(0, Math.floor(i * step), size, 1);
        }
        break;
      }
    }
  }
1114508
function scanLine(x0, x1, y) {
      var z = c0.zoom,
          z0 = 2 - tileLevel,
          z1 = 4 + tileLevel;

      for (var x = x0; x < x1; x++) {
        var t = cache.load({column: x, row: y, zoom: z}, projection);
        if (!t.ready && !(t.key in newLocks)) {
          t.proxyRefs = {};
          var c, full, proxy;

          // downsample high-resolution tiles
          for (var dz = 1; dz <= z0; dz++) {
            full = true;
            for (var dy = 0, k = 1 << dz; dy <= k; dy++) {
              for (var dx = 0; dx <= k; dx++) {
                proxy = cache.peek(c = {
                  column: (x << dz) + dx,
                  row: (y << dz) + dy,
                  zoom: z + dz
                });
                if (proxy && proxy.ready) {
                  newLocks[proxy.key] = cache.load(c);
                  proxy.proxyCount++;
                  t.proxyRefs[proxy.key] = proxy;
                } else {
                  full = false;
                }
              }
            }
            if (full) break;
          }

          // upsample low-resolution tiles
          if (!full) {
            for (var dz = 1; dz <= z1; dz++) {
              proxy = cache.peek(c = {
                column: x >> dz,
                row: y >> dz,
                zoom: z - dz
              });
              if (proxy && proxy.ready) {
                newLocks[proxy.key] = cache.load(c);
                proxy.proxyCount++;
                t.proxyRefs[proxy.key] = proxy;
                break;
              }
            }
          }
        }
        newLocks[t.key] = t;
      }
    }
781190
def xdifference(self, to):
        
        x,y = 0,1
        assert self.level == to.level
        self_tile = list(self.to_tile()[0])
        to_tile = list(to.to_tile()[0])
        if self_tile[x] >= to_tile[x] and self_tile[y] <= self_tile[y]:
            ne_tile, sw_tile = self_tile, to_tile
        else:
            sw_tile, ne_tile = self_tile, to_tile
        cur = ne_tile[:]
        while cur[x] >= sw_tile[x]:
            while cur[y] <= sw_tile[y]:
                yield from_tile(tuple(cur), self.level)
                cur[y] += 1
            cur[x] -= 1
            cur[y] = ne_tile[y]
464417
def scale_pixels(color, layer):
    """"""
    pixelmap = []

    # Scaling the pixel offsets.
    for pix_x in range(MAX_X + 1):
        for pix_y in range(MAX_Y + 1):

            # Horizontal pixels
            y1 = pix_y * dotsize[0]
            x1 = pix_x * dotsize[1]

            # Vertical pixels
            y2 = pix_y * dotsize[0] + (dotsize[0] - 1)
            x2 = pix_x * dotsize[1] + (dotsize[1] - 1)

            if (y1 <= MAX_Y) and (y2 <= MAX_Y):
                if (x1 <= MAX_X) and (x2 <= MAX_X):
                    if (pix_x, pix_y) in layer:
                        pixelmap.append([(y1, x1), (y2, x2), color])
    return pixelmap
208750
def display(self, data, x=None, y=None, xlabel=None, ylabel=None,
                style=None, nlevels=None, levels=None, contour_labels=None,
                store_data=True, col=0, unzoom=True, auto_contrast=False,
                contrast_level=0, **kws):
        
        if style is not None:
            self.conf.style = style
        self.axes.cla()
        conf = self.conf
        conf.log_scale = False
        conf.rot, conf.flip_ud, conf.flip_lr = False, False, False
        conf.highlight_areas = []
        if 1 in data.shape:
            data = data.squeeze()
        self.data_shape = data.shape
        self.data_range = [0, data.shape[1], 0, data.shape[0]]
        conf.contrast_level = contrast_level
        if auto_contrast:
            conf.contrast_level = 1
        if x is not None:
            self.xdata = np.array(x)
            if self.xdata.shape[0] != data.shape[1]:
                self.xdata = None
        if y is not None:
            self.ydata = np.array(y)
            if self.ydata.shape[0] != data.shape[0]:
                self.ydata = None

        if xlabel is not None:
            self.xlab = xlabel
        if ylabel is not None:
            self.ylab = ylabel
        if store_data:
            self.conf.data = data

        cmap = self.conf.cmap[col]
        if self.conf.style == 'contour':
            if levels is None:
                levels = self.conf.ncontour_levels
            else:
                self.conf.ncontour_levels = levels
            if nlevels is None:
                nlevels = self.conf.ncontour_levels = 9
            nlevels = max(2, nlevels)
            clevels  = np.linspace(data.min(), data.max(), nlevels+1)
            self.conf.contour_levels = clevels
            self.conf.image = self.axes.contourf(data, cmap=self.conf.cmap[col],
                                                 levels=clevels)

            self.conf.contour = self.axes.contour(data, cmap=self.conf.cmap[col],
                                                  levels=clevels)
            cmap_name = self.conf.cmap[col].name
            xname = 'gray'
            try:
                if cmap_name == 'gray_r':
                    xname = 'Reds_r'
                elif cmap_name == 'gray':
                    xname = 'Reds'
                elif cmap_name.endswith('_r'):
                    xname = 'gray_r'
            except:
                pass
            self.conf.contour.set_cmap(getattr(colormap, xname))

            if contour_labels is None:
                contour_labels = self.conf.contour_labels
            if contour_labels:
                self.axes.clabel(self.conf.contour, fontsize=10, inline=1)
            if hasattr(self.contour_callback , '__call__'):
                self.contour_callback(levels=clevels)
        else:
            if data.max() == data.min():
                img = data
            else:
                img = (data - data.min()) /(1.0*data.max() - data.min())
            self.conf.image = self.axes.imshow(img, cmap=self.conf.cmap[col],
                                               interpolation=self.conf.interp)

        self.axes.set_axis_off()
        if unzoom:
            self.unzoom_all()
        if hasattr(self.data_callback, '__call__'):
            self.data_callback(data, x=x, y=y, **kws)

        self.conf.indices = None
        self.indices_thread = Thread(target=self.calc_indices, args=(data.shape, ))
        self.indices_thread.start()
1370217
def _global_tiles_from_bounds(tp, bounds, zoom):
    """"""
    seen = set()

    # clip to tilepyramid top and bottom bounds
    left, right = bounds.left, bounds.right
    top = tp.top if bounds.top > tp.top else bounds.top
    bottom = tp.bottom if bounds.bottom < tp.bottom else bounds.bottom

    if left >= tp.left and right <= tp.right:
        for tile in _tiles_from_cleaned_bounds(tp, bounds, zoom):
            yield tile

    # bounds overlap on the Western side with antimeridian
    if left < tp.left:
        for tile in chain(
            # tiles west of antimeridian
            _tiles_from_cleaned_bounds(
                tp,
                Bounds(left + (tp.right - tp.left), bottom, tp.right, top),
                zoom
            ),
            # tiles east of antimeridian
            _tiles_from_cleaned_bounds(
                tp, Bounds(tp.left, bottom, right, top), zoom
            )
        ):
            # make output tiles unique
            if tile.id not in seen:
                seen.add(tile.id)
                yield tile

    # bounds overlap on the Eastern side with antimeridian
    if right > tp.right:
        for tile in chain(
            # tiles west of antimeridian
            _tiles_from_cleaned_bounds(
                tp, Bounds(left, bottom, tp.right, top), zoom
            ),
            # tiles east of antimeridian
            _tiles_from_cleaned_bounds(
                tp,
                Bounds(tp.left, bottom, right - (tp.right - tp.left), top),
                zoom
            )
        ):
            # make output tiles unique
            if tile.id not in seen:
                seen.add(tile.id)
                yield tile
859954
def quadkey_to_tile(quadkey):
        """"""
        tile_x, tile_y = (0, 0)
        level = len(quadkey)
        for i in xrange(level):
            bit = level - i
            mask = 1 << (bit - 1)
            if quadkey[level - bit] == '1':
                tile_x |= mask
            if quadkey[level - bit] == '2':
                tile_y |= mask
            if quadkey[level - bit] == '3':
                tile_x |= mask
                tile_y |= mask
        return [(tile_x, tile_y), level]
507598
def _blend_layers(self, imagecontent, z_x_y):
        
        (z, x, y) = z_x_y
        result = self._tile_image(imagecontent)
        # Paste each layer
        for (layer, opacity) in self._layers:
            try:
                # Prepare tile of overlay, if available
                overlay = self._tile_image(layer.tile((z, x, y)))
            except (IOError, DownloadError, ExtractionError)as e:
                logger.warn(e)
                continue
            # Extract alpha mask
            overlay = overlay.convert("RGBA")
            r, g, b, a = overlay.split()
            overlay = Image.merge("RGB", (r, g, b))
            a = ImageEnhance.Brightness(a).enhance(opacity)
            overlay.putalpha(a)
            mask = Image.merge("L", (a,))
            result.paste(overlay, (0, 0), mask)
        # Read result
        return self._image_tile(result)
1037251
def _get_vector_tile(self, x_tile, y_tile, z_tile):
        """"""
        cache_file = "mapscache/{}.{}.{}.json".format(z_tile, x_tile, y_tile)
        if cache_file not in self._tiles:
            if os.path.isfile(cache_file):
                with open(cache_file, 'rb') as f:
                    tile = json.loads(f.read().decode('utf-8'))
            else:
                url = _VECTOR_URL.format(z_tile, x_tile, y_tile, _KEY)
                data = requests.get(url).content
                try:
                    tile = mapbox_vector_tile.decode(data)
                    with open(cache_file, mode='w') as f:
                        json.dump(literal_eval(repr(tile)), f)
                except DecodeError:
                    tile = None
            if tile:
                self._tiles[cache_file] = [x_tile, y_tile, z_tile, tile, False]
                if len(self._tiles) > _CACHE_SIZE:
                    self._tiles.popitem(False)
                self._screen.force_update()
975168
def export_image(self, bbox, zoomlevel, imagepath):
        
        assert has_pil, _("Cannot export image without python PIL")
        grid = self.grid_tiles(bbox, zoomlevel)
        width = len(grid[0])
        height = len(grid)
        widthpix = width * self.tile_size
        heightpix = height * self.tile_size

        result = Image.new("RGBA", (widthpix, heightpix))
        offset = (0, 0)
        for i, row in enumerate(grid):
            for j, (x, y) in enumerate(row):
                offset = (j * self.tile_size, i * self.tile_size)
                img = self._tile_image(self.tile((zoomlevel, x, y)))
                result.paste(img, offset)
        logger.info(_("Save resulting image to '%s'") % imagepath)
        result.save(imagepath)
944023
function (tiles) {
		const maxDist = 5;
		
		let t, tile, i;
		
		let topLeft = Vector._temp[0],
			topRight = Vector._temp[1],
			bottomLeft = Vector._temp[2],
			bottomRight = Vector._temp[3];
		
		// Calculate initial boundary edges
		for (t = 0; t < tiles.length; t++) {
			tile = tiles[t];
			
			// Skip over irrelevant tiles
			if (isIrrelevant(tile)) {
				continue;
			}
			
			let body = tile.physics.matterBody.body;
			let vertices = body.vertices;
			
			let left = tile.pixelX;
			let right = tile.pixelX + tile.width;
			let top = tile.pixelY;
			let bottom = tile.pixelY + tile.height;
			
			topLeft.y = top;
			topLeft.x = left;
			topRight.y = top;
			topRight.x = right;
			bottomLeft.y = bottom;
			bottomLeft.x = left;
			bottomRight.y = bottom;
			bottomRight.x = right;
			
			// Identify solid boundary edges
			for (i = 0; i < vertices.length; i++) {
				let firstVertex = vertices[i];
				let secondVertex = vertices[(i + 1) % vertices.length];
				
				// Top
				if (distance(firstVertex, topLeft) < maxDist && distance(secondVertex, topRight) < maxDist) {
					tile.physics.slopes.edges.top = Constants.SOLID;
				}
				
				// Bottom
				if (distance(firstVertex, bottomRight) < maxDist && distance(secondVertex, bottomLeft) < maxDist) {
					tile.physics.slopes.edges.bottom = Constants.SOLID;
				}
				
				// Left
				if (distance(firstVertex, bottomLeft) < maxDist && distance(secondVertex, topLeft) < maxDist) {
					tile.physics.slopes.edges.left = Constants.SOLID;
				}
				
				// Right
				if (distance(firstVertex, topRight) < maxDist && distance(secondVertex, bottomRight) < maxDist) {
					tile.physics.slopes.edges.right = Constants.SOLID;
				}
			}
		}
		
		// Compare neighbouring boundary edges
		for (t = 0; t < tiles.length; t++) {
			tile = tiles[t];
			
			// Skip over irrelevant tiles
			if (isIrrelevant(tile)) {
				continue;
			}
			
			let tileEdges = tile.physics.slopes.edges;
			let neighbours = tile.physics.slopes.neighbours;
			
			let up = neighbours.up;
			let down = neighbours.down;
			let left = neighbours.left;
			let right = neighbours.right;
			
			// Identify empty edges
			if (!isIrrelevant(up)) {
				tileEdges.top = this.compareBoundaryEdges(tileEdges.top, up.physics.slopes.edges.bottom);
				tile.collideUp = tileEdges.top !== Constants.EMPTY;
			}
			
			if (!isIrrelevant(down)) {
				tileEdges.bottom = this.compareBoundaryEdges(tileEdges.bottom, down.physics.slopes.edges.top);
				tile.collideDown = tileEdges.bottom !== Constants.EMPTY;
			}
			
			if (!isIrrelevant(left)) {
				tileEdges.left = this.compareBoundaryEdges(tileEdges.left, left.physics.slopes.edges.right);
				tile.collideLeft = tileEdges.left !== Constants.EMPTY;
			}
			
			if (!isIrrelevant(right)) {
				tileEdges.right = this.compareBoundaryEdges(tileEdges.right, right.physics.slopes.edges.left);
				tile.collideRight = tileEdges.right !== Constants.EMPTY;
			}
		}
	}
72377
def iter_tiles(image, tile_size):
    
    w, h = image.size
    for y in xrange(0, h, tile_size):
        for x in xrange(0, w, tile_size):
            yield x, y
686893
def tile(self, z, x, y):
        
        logger.debug(_("Download tile %s") % ((z, x, y),))
        # Render each keyword in URL ({s}, {x}, {y}, {z}, {size} ... )
        size = self.tilesize
        s = self.tiles_subdomains[(x + y) % len(self.tiles_subdomains)];
        try:
            url = self.tiles_url.format(**locals())
        except KeyError as e:
            raise DownloadError(_("Unknown keyword %s in URL") % e)

        logger.debug(_("Retrieve tile at %s") % url)
        r = DOWNLOAD_RETRIES
        sleeptime = 1
        while r > 0:
            try:
                request = requests.get(url, headers=self.headers)
                if request.status_code == 200:
                    return request.content
                raise DownloadError(_("Status code : %s, url : %s") % (request.status_code, url))
            except requests.exceptions.ConnectionError as e:
                logger.debug(_("Download error, retry (%s left). (%s)") % (r, e))
                r -= 1
                time.sleep(sleeptime)
                # progressivly sleep longer to wait for this tile
                if (sleeptime <= 10) and (r % 2 == 0):
                    sleeptime += 1  # increase wait
        raise DownloadError(_("Cannot download URL %s") % url)