/*
MapTileCollisionRenderer
436396
@Override
    public void createCollisionDraw()
    {
        clearCollisionDraw();

        final Collection<CollisionFormula> formulas = mapCollision.getCollisionFormulas();
        collisionCache = new HashMap<>(formulas.size());

        for (final CollisionFormula collision : formulas)
        {
            final ImageBuffer buffer = createFunctionDraw(collision, map.getTileWidth(), map.getTileHeight());
            collisionCache.put(collision, buffer);
        }
    }
673943
function(){
            this.fillBg();
            for (var x = this.width - 1; x >= 0; x--) {
                for (var y = this.height - 1; y >= 0; y--) {
                    // get the actual map tile coord from view coord using offset
                    var tileX = x + this.originX,
                        tileY = y + this.originY;
                    this.drawTile(tileX, tileY);
                }
            }

            this.drawBufferToCanvas();
        }
254527
function(e) {
            if(this.onHover){
                var coords = this.game.renderer.mouseToTileCoords(e.clientX, e.clientY);
                this.onHover(coords);
            }
        }
1227093
private static Tile checkTile(MapTile map, ImageBuffer tileSprite, Integer sheet, int x, int y)
    {
        final int tw = map.getTileWidth();
        final int th = map.getTileHeight();
        final SpriteTiled tileSheet = map.getSheet(sheet);
        final ImageBuffer sheetImage = tileSheet.getSurface();
        final int tilesInX = tileSheet.getWidth() / tw;
        final int tilesInY = tileSheet.getHeight() / th;

        for (int surfaceCurrentTileY = 0; surfaceCurrentTileY < tilesInY; surfaceCurrentTileY++)
        {
            for (int surfaceCurrentTileX = 0; surfaceCurrentTileX < tilesInX; surfaceCurrentTileX++)
            {
                // Tile number on tile sheet
                final int number = surfaceCurrentTileX + surfaceCurrentTileY * tilesInX;

                // Compare tiles between sheet and image map
                final int xa = x * tw;
                final int ya = y * th;
                final int xb = surfaceCurrentTileX * tw;
                final int yb = surfaceCurrentTileY * th;

                if (TilesExtractor.compareTile(tw, th, tileSprite, xa, ya, sheetImage, xb, yb))
                {
                    return map.createTile(sheet, number, xa, (map.getInTileHeight() - 1.0 - y) * th);
                }
            }
        }
        return null;
    }
174755
function() {
        var shouldDraw = OpenLayers.Tile.prototype.draw.apply(this, arguments);
        if (shouldDraw) {
            // The layer's reproject option is deprecated.
            if (this.layer != this.layer.map.baseLayer && this.layer.reproject) {
                // getBoundsFromBaseLayer is defined in deprecated.js.
                this.bounds = this.getBoundsFromBaseLayer(this.position);
            }
            if (this.isLoading) {
                //if we're already loading, send 'reload' instead of 'loadstart'.
                this._loadEvent = "reload";
            } else {
                this.isLoading = true;
                this._loadEvent = "loadstart";
            }
            this.renderTile();
            this.positionTile();
        } else if (shouldDraw === false) {
            this.unload();
        }
        return shouldDraw;
    }
492046
function() {
        var context;
        if (this.cacheImageRecord) {
            context = this.cacheImageRecord.getRenderedContext();
        } else if (this.context2D) {
            context = this.context2D;
        } else {
            $.console.warn(
                '[Tile.drawCanvas] attempting to get tile scale %s when tile\'s not cached',
                this.toString());
            return 1;
        }
        return context.canvas.width / (this.size.x * $.pixelDensityRatio);
    }
389245
private void renderTile(Graphic g, int tx, int ty, double viewX, double viewY)
    {
        final Tile tile = map.getTile(tx, ty);
        if (tile != null)
        {
            final int x = (int) Math.floor(tile.getX() - viewX);
            final int y = (int) Math.floor(-tile.getY() + viewY - tile.getHeight());

            for (final MapTileRenderer renderer : renderers)
            {
                renderer.renderTile(g, map, tile, x, y);
            }
        }
    }
216797
function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive

		if (refreshCoordinateGrid) {
			coordinateGrid.build();
		}

		var segments = rangeToSegments(overlayStart, overlayEnd);

		for (var i=0; i<segments.length; i++) {
			var segment = segments[i];
			dayBind(
				renderCellOverlay(
					segment.row,
					segment.leftCol,
					segment.row,
					segment.rightCol
				)
			);
		}
	}
1087508
@Override
    public void renderTile(Graphic g, MapTile map, Tile tile, int x, int y)
    {
        final int tx = tile.getInTileX();
        final int ty = tile.getInTileY();

        final Tile fogTile = mapFogged.getTile(tx, ty);
        if (fogMap && fogTile != null && fogTile.getNumber() != MapTileFog.NO_FOG)
        {
            fogTiles.setLocation(x, y);
            fogTiles.setTile(fogTile.getNumber());
            fogTiles.render(g);
        }

        final Tile hideTile = mapHidden.getTile(tx, ty);
        if (hideMap && hideTile != null && hideTile.getNumber() != MapTileFog.NO_FOG)
        {
            hideTiles.setTile(hideTile.getNumber());
            hideTiles.setLocation(x, y);
            hideTiles.render(g);
        }
    }
663394
public static void main(String[] args) {
        // Multithreaded map rendering
        Parameters.NUMBER_OF_THREADS = 2;

        // Square frame buffer
        Parameters.SQUARE_FRAME_BUFFER = false;

        HillsRenderConfig hillsCfg = null;
        File demFolder = getDemFolder(args);
        if (demFolder != null) {
            MemoryCachingHgtReaderTileSource tileSource = new MemoryCachingHgtReaderTileSource(demFolder, new DiffuseLightShadingAlgorithm(), AwtGraphicFactory.INSTANCE);
            tileSource.setEnableInterpolationOverlap(true);
            hillsCfg = new HillsRenderConfig(tileSource);
            hillsCfg.indexOnThread();
            args = Arrays.copyOfRange(args, 1, args.length);
        }

        List<File> mapFiles = SHOW_RASTER_MAP ? null : getMapFiles(args);
        final MapView mapView = createMapView();
        final BoundingBox boundingBox = addLayers(mapView, mapFiles, hillsCfg);

        final PreferencesFacade preferencesFacade = new JavaPreferences(Preferences.userNodeForPackage(Samples.class));

        final JFrame frame = new JFrame();
        frame.setTitle("Mapsforge Samples");
        frame.add(mapView);
        frame.pack();
        frame.setSize(1024, 768);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                int result = JOptionPane.showConfirmDialog(frame, MESSAGE, TITLE, JOptionPane.YES_NO_OPTION);
                if (result == JOptionPane.YES_OPTION) {
                    mapView.getModel().save(preferencesFacade);
                    mapView.destroyAll();
                    AwtGraphicFactory.clearResourceMemoryCache();
                    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                }
            }

            @Override
            public void windowOpened(WindowEvent e) {
                final Model model = mapView.getModel();
                model.init(preferencesFacade);
                if (model.mapViewPosition.getZoomLevel() == 0 || !boundingBox.contains(model.mapViewPosition.getCenter())) {
                    byte zoomLevel = LatLongUtils.zoomForBounds(model.mapViewDimension.getDimension(), boundingBox, model.displayModel.getTileSize());
                    model.mapViewPosition.setMapPosition(new MapPosition(boundingBox.getCenterPoint(), zoomLevel));
                }
            }
        });
        frame.setVisible(true);
    }
1239092
function(bounds) {
        this.events.triggerEvent("retile");

        // work out mininum number of rows and columns; this is the number of
        // tiles required to cover the viewport plus at least one for panning

        var viewSize = this.map.getSize();
        
        var origin = this.getTileOrigin();
        var resolution = this.map.getResolution(),
            serverResolution = this.getServerResolution(),
            ratio = resolution / serverResolution,
            tileSize = {
                w: this.tileSize.w / ratio,
                h: this.tileSize.h / ratio
            };

        var minRows = Math.ceil(viewSize.h/tileSize.h) + 
                      2 * this.buffer + 1;
        var minCols = Math.ceil(viewSize.w/tileSize.w) +
                      2 * this.buffer + 1;

        var tileLayout = this.calculateGridLayout(bounds, origin, serverResolution);
        this.gridLayout = tileLayout;
        
        var tilelon = tileLayout.tilelon;
        var tilelat = tileLayout.tilelat;
        
        var layerContainerDivLeft = this.map.layerContainerOriginPx.x;
        var layerContainerDivTop = this.map.layerContainerOriginPx.y;

        var tileBounds = this.getTileBoundsForGridIndex(0, 0);
        var startPx = this.map.getViewPortPxFromLonLat(
            new OpenLayers.LonLat(tileBounds.left, tileBounds.top)
        );
        startPx.x = Math.round(startPx.x) - layerContainerDivLeft;
        startPx.y = Math.round(startPx.y) - layerContainerDivTop;

        var tileData = [], center = this.map.getCenter();

        var rowidx = 0;
        do {
            var row = this.grid[rowidx];
            if (!row) {
                row = [];
                this.grid.push(row);
            }
            
            var colidx = 0;
            do {
                tileBounds = this.getTileBoundsForGridIndex(rowidx, colidx);
                var px = startPx.clone();
                px.x = px.x + colidx * Math.round(tileSize.w);
                px.y = px.y + rowidx * Math.round(tileSize.h);
                var tile = row[colidx];
                if (!tile) {
                    tile = this.addTile(tileBounds, px);
                    this.addTileMonitoringHooks(tile);
                    row.push(tile);
                } else {
                    tile.moveTo(tileBounds, px, false);
                }
                var tileCenter = tileBounds.getCenterLonLat();
                tileData.push({
                    tile: tile,
                    distance: Math.pow(tileCenter.lon - center.lon, 2) +
                        Math.pow(tileCenter.lat - center.lat, 2)
                });
     
                colidx += 1;
            } while ((tileBounds.right <= bounds.right + tilelon * this.buffer)
                     || colidx < minCols);
             
            rowidx += 1;
        } while((tileBounds.bottom >= bounds.bottom - tilelat * this.buffer)
                || rowidx < minRows);
        
        //shave off exceess rows and colums
        this.removeExcessTiles(rowidx, colidx);

        var resolution = this.getServerResolution();
        // store the resolution of the grid
        this.gridResolution = resolution;

        //now actually draw the tiles
        tileData.sort(function(a, b) {
            return a.distance - b.distance; 
        });
        for (var i=0, ii=tileData.length; i<ii; ++i) {
            tileData[i].tile.draw();
        }
    }
1181003
function() {
        var layer = this.layer;
        for(var i=0; i<8; ++i) {
            if(this.rotate && i % 2 === 0) {
                layer.drawFeature(this.rotationHandles[i/2],
                    this.rotationHandleSymbolizer);
            }
            layer.drawFeature(this.handles[i], this.renderIntent);
        }
    }
882797
protected void drawMapTiles(final Graphics g, final int zoom, Rectangle viewportBounds)
    {
        int size = getTileFactory().getTileSize(zoom);
        Dimension mapSize = getTileFactory().getMapSize(zoom);

        // calculate the "visible" viewport area in tiles
        int numWide = viewportBounds.width / size + 2;
        int numHigh = viewportBounds.height / size + 2;

        // TilePoint topLeftTile = getTileFactory().getTileCoordinate(
        // new Point2D.Double(viewportBounds.x, viewportBounds.y));
        TileFactoryInfo info = getTileFactory().getInfo();

        // number of tiles in x direction
        int tpx = (int) Math.floor(viewportBounds.getX() / info.getTileSize(0));
        // number of tiles in y direction
        int tpy = (int) Math.floor(viewportBounds.getY() / info.getTileSize(0));
        // TilePoint topLeftTile = new TilePoint(tpx, tpy);

        // p("top tile = " + topLeftTile);
        // fetch the tiles from the factory and store them in the tiles cache
        // attach the tileLoadListener
        for (int x = 0; x <= numWide; x++)
        {
            for (int y = 0; y <= numHigh; y++)
            {
                int itpx = x + tpx;// topLeftTile.getX();
                int itpy = y + tpy;// topLeftTile.getY();
                // TilePoint point = new TilePoint(x + topLeftTile.getX(), y + topLeftTile.getY());
                // only proceed if the specified tile point lies within the area being painted
                if (g.getClipBounds().intersects(
                        new Rectangle(itpx * size - viewportBounds.x, itpy * size - viewportBounds.y, size, size)))
                {
                    Tile tile = getTileFactory().getTile(itpx, itpy, zoom);
                    int ox = ((itpx * getTileFactory().getTileSize(zoom)) - viewportBounds.x);
                    int oy = ((itpy * getTileFactory().getTileSize(zoom)) - viewportBounds.y);

                    // if the tile is off the map to the north/south, then just don't paint anything
                    if (!isTileOnMap(itpx, itpy, mapSize))
                    {
                        if (isOpaque())
                        {
                            g.setColor(getBackground());
                            g.fillRect(ox, oy, size, size);
                        }
                    }
                    else if (tile.isLoaded())
                    {
                        g.drawImage(tile.getImage(), ox, oy, null);
                    }
                    else
                    {
                        Tile superTile = null;

                        // Use tile at higher zoom level with 200% magnification and if we are not already at max resolution
                        if (zoom < info.getMaximumZoomLevel()) {
                            superTile = getTileFactory().getTile(itpx / 2, itpy / 2, zoom + 1);
                        }

                        if ( superTile != null && superTile.isLoaded())
                        {
                            int offX = (itpx % 2) * size / 2;
                            int offY = (itpy % 2) * size / 2;
                            g.drawImage(superTile.getImage(), ox, oy, ox + size, oy + size, offX, offY, offX + size / 2, offY + size / 2, null);
                        }
                        else
                        {
                            int imageX = (getTileFactory().getTileSize(zoom) - getLoadingImage().getWidth(null)) / 2;
                            int imageY = (getTileFactory().getTileSize(zoom) - getLoadingImage().getHeight(null)) / 2;
                            g.setColor(Color.GRAY);
                            g.fillRect(ox, oy, size, size);
                            g.drawImage(getLoadingImage(), ox + imageX, oy + imageY, null);
                        }
                    }
                    if (isDrawTileBorders())
                    {

                        g.setColor(Color.black);
                        g.drawRect(ox, oy, size, size);
                        g.drawRect(ox + size / 2 - 5, oy + size / 2 - 5, 10, 10);
                        g.setColor(Color.white);
                        g.drawRect(ox + 1, oy + 1, size, size);

                        String text = itpx + ", " + itpy + ", " + getZoom();
                        g.setColor(Color.BLACK);
                        g.drawString(text, ox + 10, oy + 30);
                        g.drawString(text, ox + 10 + 2, oy + 30 + 2);
                        g.setColor(Color.WHITE);
                        g.drawString(text, ox + 10 + 1, oy + 30 + 1);
                    }
                }
            }
        }
    }
978449
private void loadTileCollisions(MapTileCollision mapCollision, Tile tile)
    {
        final TileCollision tileCollision;
        if (!tile.hasFeature(TileCollision.class))
        {
            tileCollision = new TileCollisionModel(tile);
            tile.addFeature(tileCollision);
        }
        else
        {
            tileCollision = tile.getFeature(TileCollision.class);
        }
        tileCollision.removeCollisionFormulas();
        addTileCollisions(mapCollision, tileCollision, tile);
    }
1135688
function (layer) {
            var bounds = layer instanceof me.TMXLayer ? me.pool.pull("me.Rect", 0, 0, 0, 0) : this.bounds;
            bounds.setShape(
                0, 0,
                this.cols * this.tilewidth,
                this.rows * this.tileheight
            );
            return bounds;
        }
1303737
function(evt) {
        evt.layer.events.on({
            tileloadstart: this.makeSameOrigin,
            tileloaded: this.onTileLoaded,
            scope: this
        });        
    }
606521
function GraphicsRenderer(renderer)
{
    ObjectRenderer.call(this, renderer);

    this.graphicsDataPool = [];

    this.primitiveShader = null;
    this.complexPrimitiveShader = null;
}