Putting the tile in the memory cache by trying to draw them (but on a null Canvas)
484886
private void refresh() {
        if (!refreshCheckStart()) {
            return;
        }
        final TileStates tileStates = mTilesOverlay.getTileStates();
        do {
            mTilesOverlay.drawTiles(null, mProjection, mProjection.getZoomLevel(), mViewPort);
            boolean ready = true;
            if (mIncludeFlags != 0 && mIncludeFlags != INCLUDE_FLAGS_ALL) {
                if (ready && (mIncludeFlags & INCLUDE_FLAG_UPTODATE) == 0 && tileStates.getUpToDate() != 0) {
                    ready = false;
                }
                if (ready && (mIncludeFlags & INCLUDE_FLAG_EXPIRED) == 0 && tileStates.getExpired() != 0) {
                    ready = false;
                }
                if (ready && (mIncludeFlags & INCLUDE_FLAG_SCALED) == 0 && tileStates.getScaled() != 0) {
                    ready = false;
                }
                if (ready && (mIncludeFlags & INCLUDE_FLAG_NOTFOUND) == 0 && tileStates.getNotFound() != 0) {
                    ready = false;
                }
            }
            if (ready) {
                if (mStatus == Status.CANVAS_OK || mStatus == Status.PAINTING) {
                    return;
                }
                if (!refreshCheckFinish()) {
                    return;
                }
                mStatus = Status.PAINTING;
                if (mIsDetached) {
                    return;
                }
                draw();
                mStatus = Status.CANVAS_OK;
                final MapSnapshotable mapSnapshotable = mMapSnapshotable;
                if (mapSnapshotable != null) {
                    mapSnapshotable.callback(MapSnapshot.this);
                }
            }
        } while(refreshCheckEnd());
    }
155471
def draw_grid(self):
        """"""
        self.screen.fill((0xbb, 0xad, 0xa0), self.origin + (self.game_width, self.game_height))
        for y, row in enumerate(self.grid):
            for x, cell in enumerate(row):
                self.screen.blit(self.tiles[cell], self.get_tile_location(x, y))
1058099
def _draw(self, context, opacity):
        """"""

        # if we have been moved around, we should update bounds
        fresh_draw = len(self.__new_instructions or []) > 0
        if fresh_draw: #new stuff!
            self.paths = []
            self.__instruction_cache = self.__new_instructions
            self.__new_instructions = []
        else:
            if not self.__instruction_cache:
                return

        for instruction, args in self.__instruction_cache:
            if fresh_draw:
                if instruction in ("new_path", "stroke", "fill", "clip"):
                    self.paths.append((instruction, "path", context.copy_path()))

                elif instruction in ("save", "restore", "translate", "scale", "rotate"):
                    self.paths.append((instruction, "transform", args))

            if instruction == "set_color":
                self._set_color(context, args[0], args[1], args[2], args[3] * opacity)
            elif instruction == "show_layout":
                self._show_layout(context, *args)
            elif opacity < 1 and instruction == "paint":
                context.paint_with_alpha(opacity)
            else:
                getattr(context, instruction)(*args)
374093
@Override
    public void draw(@NonNull Canvas canvas) {
        if (mCurrDrawable != null) {
            mCurrDrawable.draw(canvas);
        }
        if (mLastDrawable != null) {
            mLastDrawable.draw(canvas);
        }
    }
339869
private TileBitmap createBackgroundBitmap(RenderContext renderContext) {
        TileBitmap bitmap = this.graphicFactory.createTileBitmap(renderContext.rendererJob.tile.tileSize, renderContext.rendererJob.hasAlpha);
        renderContext.canvasRasterer.setCanvasBitmap(bitmap);
        if (!renderContext.rendererJob.hasAlpha) {
            renderContext.canvasRasterer.fill(renderContext.renderTheme.getMapBackgroundOutside());
        }
        return bitmap;

    }
1301129
function drawTileLayer(renderer, layer, rect) {
         // get top-left and bottom-right tile position
         var start = this.pixelToTileCoords(rect.pos.x, rect.pos.y, me.pool.pull("me.Vector2d")).floorSelf();
         var end = this.pixelToTileCoords(rect.pos.x + rect.width + this.tilewidth, rect.pos.y + rect.height + this.tileheight, me.pool.pull("me.Vector2d")).ceilSelf(); //ensure we are in the valid tile range

         start.x = start.x < 0 ? 0 : start.x;
         start.y = start.y < 0 ? 0 : start.y;
         end.x = end.x > this.cols ? this.cols : end.x;
         end.y = end.y > this.rows ? this.rows : end.y; // main drawing loop

         for (var y = start.y; y < end.y; y++) {
           for (var x = start.x; x < end.x; x++) {
             var tmxTile = layer.layerData[x][y];

             if (tmxTile) {
               this.drawTile(renderer, x, y, tmxTile);
             }
           }
         }

         me.pool.push(start);
         me.pool.push(end);
       }
966819
function() {
		var spriteIndex = this.currentSprite << 2,
			y = this.oam2[ spriteIndex ],
			tileIndex = this.oam2[ spriteIndex + 1 ],
			attributes = this.oam2[ spriteIndex + 2 ],
			x = this.oam2[ spriteIndex + 3 ],
			baseTable = this.baseTable,
			tile = 0,
			flipX = attributes & 0x40,
			flipY = 0,
			fineY = 0;

		flipY = attributes & 0x80;
		fineY = ( this.ppu.scanline - y ) & ( this.spriteSize - 1 );
		// (the '& spriteSize' is needed because fineY can overflow due
		// to uninitialized tiles in secondary OAM)

		if ( this.spriteSize === 16 ) {
			// big sprite, select proper nametable and handle flipping
			baseTable = ( tileIndex & 1 ) ? 0x1000 : 0;
			tileIndex = tileIndex & ~1;

			if ( fineY > 7 ) {
				fineY -= 8;
				if ( !flipY ) {
					tileIndex++;
				}
			} else if ( flipY ) {
				tileIndex++;
			}
		}

		if ( flipY ) {
			fineY = 8 - fineY - 1;
		}

		tile = this.memory.cartridge.readTile( baseTable, tileIndex, fineY );

		if ( flipX ) {
			tile = bitmap.reverseTile( tile );
		}

		if ( this.currentSprite < this.nextSpriteCount ) {
			this.renderTile( x, tile, attributes );
		}

		this.currentSprite += 1;
	}
278890
private void refresh() {
        try {
            Canvas canvas = mSurface.lockCanvas(null);
            mWebView.draw(canvas);
            mSurface.unlockCanvasAndPost(canvas);
        } catch (Surface.OutOfResourcesException t) {
            Log.e("GVRWebBoardObject", "lockCanvas failed");
        }
        mSurfaceTexture.updateTexImage();
    }
881801
public byte[] drawTileBytes(int x, int y, int zoom) {

		BufferedImage image = drawTile(x, y, zoom);

		byte[] tileData = null;

		// Convert the image to bytes
		if (image != null) {
			try {
				tileData = ImageUtils.writeImageToBytes(image, compressFormat);
			} catch (IOException e) {
				LOGGER.log(Level.SEVERE, "Failed to create tile. x: " + x
						+ ", y: " + y + ", zoom: " + zoom, e);
			}
		}

		return tileData;
	}
65497
function() {
		var cartridge = this.memory.cartridge,

		      attrAddress = attrAddresses[ this.loopyV ],
		      attribute = cartridge.readNameTable( attrAddress & 0x1fff ),

		      nametableAddress = 0x2000 | ( this.loopyV & 0x0fff ),
		      tileIndex = cartridge.readNameTable( nametableAddress & 0x1fff ),
	          tile = cartridge.readTile( this.baseTable, tileIndex, this.y );

		if ( tile ) {
			this.renderTile(
				tile,
				palettes[ attribute & masks[ this.loopyV & 0xfff ] ]
			);
		}

		this.incrementVX();
	}
308725
function (renderer, layer, rect) {
            var incX = 1, incY = 1;

            // get top-left and bottom-right tile position
            var start = this.pixelToTileCoords(
                Math.max(rect.pos.x - (layer.maxTileSize.width - layer.tilewidth), 0),
                Math.max(rect.pos.y - (layer.maxTileSize.height - layer.tileheight), 0),
                me.pool.pull("me.Vector2d")
            ).floorSelf();

            var end = this.pixelToTileCoords(
                rect.pos.x + rect.width + this.tilewidth,
                rect.pos.y + rect.height + this.tileheight,
                me.pool.pull("me.Vector2d")
            ).ceilSelf();

            //ensure we are in the valid tile range
            end.x = end.x > this.cols ? this.cols : end.x;
            end.y = end.y > this.rows ? this.rows : end.y;

            switch (layer.renderorder) {
                case "right-up" :
                    // swapping start.y and end.y
                    end.y = start.y + (start.y = end.y) - end.y;
                    incY = -1;
                    break;
                case "left-down" :
                    // swapping start.x and end.x
                    end.x = start.x + (start.x = end.x) - end.x;
                    incX = -1;
                    break;
                case "left-up" :
                    // swapping start.x and end.x
                    end.x = start.x + (start.x = end.x) - end.x;
                    // swapping start.y and end.y
                    end.y = start.y + (start.y = end.y) - end.y;
                    incX = -1;
                    incY = -1;
                    break;
                default: // right-down
                    break;
            }

            // main drawing loop
            for (var y = start.y; y !== end.y; y+= incY) {
                for (var x = start.x; x !== end.x; x+= incX) {
                    var tmxTile = layer.layerData[x][y];
                    if (tmxTile) {
                        this.drawTile(renderer, x, y, tmxTile);
                    }
                }
            }

            me.pool.push(start);
            me.pool.push(end);
        }
1073626
function(tile, tileUrl, existingRevision, done) {
		if (!this.options.saveToCache) {
			return;
		}

		var canvas = document.createElement("canvas");
		canvas.width = tile.naturalWidth || tile.width;
		canvas.height = tile.naturalHeight || tile.height;

		var context = canvas.getContext("2d");
		context.drawImage(tile, 0, 0);

		var format = this.options.cacheFormat;

		canvas.toBlob(
			function(blob) {
				this._db
					.put({
						_id: tileUrl,
						_rev: existingRevision,
						timestamp: Date.now(),
					})
					.then(
						function(status) {
							return this._db.putAttachment(
								tileUrl,
								"tile",
								status.rev,
								blob,
								format
							);
						}.bind(this)
					)
					.then(function(resp) {
						if (done) {
							done();
						}
					})
					.catch(function() {
						// Saving the tile to the cache might have failed, 
						// but the tile itself has been loaded.
						if (done) {
							done();
						}
					});
			}.bind(this),
			format
		);
	}
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();
            }
        }
648819
function(layer) {
        if (!this.img || !layer) return;

        if (layer.type === "Canvas") {
            this._pattern = this._drawContext.createPattern(
                this.img,
                this._repeat
            );
        } else if (layer.type === "WebGL") {
            this._establishShader(
                "image:" + this.__image,
                Crafty.defaultShader("Image")
            );
            this.program.setTexture(
                this._drawLayer.makeTexture(
                    this.__image,
                    this.img,
                    this._repeat !== "no-repeat"
                )
            );
        }

        if (this._repeat === "no-repeat") {
            this.w = this.w || this.img.width;
            this.h = this.h || this.img.height;
        }

        this.ready = true;
        this.trigger("Invalidate");
    }
319693
public void paint (Graphics g, int x, int y, int width, int height)
    {
        // bail out now if we were passed a bogus source image at construct time
        if (_tiles == null) {
            return;
        }

        int rwid = width-2*_w3, rhei = height-2*_h3;

        g.drawImage(_tiles[0], x, y, _w3, _h3, null);
        g.drawImage(_tiles[1], x + _w3, y, rwid, _h3, null);
        g.drawImage(_tiles[2], x + _w3 + rwid, y, _w3, _h3, null);

        y += _h3;
        g.drawImage(_tiles[3], x, y, _w3, rhei, null);
        g.drawImage(_tiles[4], x + _w3, y, rwid, rhei, null);
        g.drawImage(_tiles[5], x + _w3 + rwid, y, _w3, rhei, null);

        y += rhei;
        g.drawImage(_tiles[6], x, y, _w3, _h3, null);
        g.drawImage(_tiles[7], x + _w3, y, rwid, _h3, null);
        g.drawImage(_tiles[8], x + _w3 + rwid, y, _w3, _h3, null);
    }
989889
function(prepareTiles, rendererHelper,
        visited, flowEvents, sortedRasterizerSlices) {
      if (!prepareTiles.args.prepare_tiles_id)
        return;

      if (!rendererHelper || !rendererHelper.rasterWorkerThreads)
        return;

      var rasterWorkerThreads = rendererHelper.rasterWorkerThreads;
      var prepare_tile_id = prepareTiles.args.prepare_tiles_id;
      var pendingEventQueue = [];

      // Collect all the rasterizer tasks. Return the cached copy if possible.
      if (sortedRasterizerSlices.length === 0)
        this.sortRasterizerSlices(rasterWorkerThreads, sortedRasterizerSlices);

      // TODO(yuhao): Once TaskSetFinishedTaskImpl also get the prepare_tile_id
      // we can simply track by checking id rather than counting.
      var numFinishedTasks = 0;
      var RASTER_TASK_TITLE = 'RasterizerTaskImpl::RunOnWorkerThread';
      var IMAGEDECODE_TASK_TITLE = 'ImageDecodeTaskImpl::RunOnWorkerThread';
      var FINISHED_TASK_TITLE = 'TaskSetFinishedTaskImpl::RunOnWorkerThread';

      for (var i = 0; i < sortedRasterizerSlices.length; i++) {
        var task = sortedRasterizerSlices[i];

        if (task.title === RASTER_TASK_TITLE ||
            task.title === IMAGEDECODE_TASK_TITLE) {
          if (task.args.source_prepare_tiles_id === prepare_tile_id)
            this.addEntireSliceHierarchy(task.mostTopLevelSlice);
        } else if (task.title === FINISHED_TASK_TITLE) {
          if (task.start > prepareTiles.start) {
            pendingEventQueue.push(task.mostTopLevelSlice);
            if (++numFinishedTasks === 3)
              break;
          }
        }
      }

      // Trace PostTask from rasterizer tasks.
      while (pendingEventQueue.length != 0) {
        var event = pendingEventQueue.pop();

        this.addEntireSliceHierarchy(event);
        this.followSubsequentSlices(event, pendingEventQueue, visited,
            flowEvents);
      }
    }
886811
def _draw_as_bitmap(self, context, opacity):
        
        matrix = context.get_matrix()
        matrix_changed = matrix != self._last_matrix
        new_instructions = self.__new_instructions is not None and len(self.__new_instructions) > 0

        if not new_instructions and not matrix_changed:
            context.save()
            context.identity_matrix()
            context.translate(self.extents.x, self.extents.y)
            context.set_source_surface(self.cache_surface)
            if opacity < 1:
                context.paint_with_alpha(opacity)
            else:
                context.paint()
            context.restore()
            return


        if new_instructions:
            self.__instruction_cache = list(self.__new_instructions)
            self.__new_instructions = deque()

        self.paths = []
        self.extents = None

        if not self.__instruction_cache:
            # no instructions - nothing to do
            return

        # instructions that end path
        path_end_instructions = ("new_path", "clip", "stroke", "fill", "stroke_preserve", "fill_preserve")

        # measure the path extents so we know the size of cache surface
        # also to save some time use the context to paint for the first time
        extents = gdk.Rectangle()
        for instruction, args in self.__instruction_cache:
            if instruction in path_end_instructions:
                self.paths.append((instruction, "path", context.copy_path()))
                exts = context.path_extents()
                exts = get_gdk_rectangle(int(exts[0]), int(exts[1]),
                                         int(exts[2]-exts[0]), int(exts[3]-exts[1]))
                if extents.width and extents.height:
                    extents = gdk.rectangle_union(extents, exts)
                else:
                    extents = exts
            elif instruction in ("save", "restore", "translate", "scale", "rotate"):
                self.paths.append((instruction, "transform", args))


            if instruction in ("set_source_pixbuf", "set_source_surface"):
                # draw a rectangle around the pathless instructions so that the extents are correct
                pixbuf = args[0]
                x = args[1] if len(args) > 1 else 0
                y = args[2] if len(args) > 2 else 0
                context.rectangle(x, y, pixbuf.get_width(), pixbuf.get_height())
                context.clip()

            if instruction == "paint" and opacity < 1:
                context.paint_with_alpha(opacity)
            elif instruction == "set_color":
                self._set_color(context, args[0], args[1], args[2], args[3] * opacity)
            elif instruction == "show_layout":
                self._show_layout(context, *args)
            else:
                getattr(context, instruction)(*args)


        # avoid re-caching if we have just moved
        just_transforms = new_instructions == False and \
                          matrix and self._last_matrix \
                          and all([matrix[i] == self._last_matrix[i] for i in range(4)])

        # TODO - this does not look awfully safe
        extents.x += matrix[4] - 5
        extents.y += matrix[5] - 5
        self.extents = extents

        if not just_transforms:
            # now draw the instructions on the caching surface
            w = int(extents.width) + 10
            h = int(extents.height) + 10
            self.cache_surface = context.get_target().create_similar(cairo.CONTENT_COLOR_ALPHA, w, h)
            ctx = cairo.Context(self.cache_surface)
            ctx.translate(-extents.x, -extents.y)

            ctx.transform(matrix)
            for instruction, args in self.__instruction_cache:
                if instruction == "set_color":
                    self._set_color(ctx, args[0], args[1], args[2], args[3])
                elif instruction == "show_layout":
                    self._show_layout(ctx, *args)
                else:
                    getattr(ctx, instruction)(*args)

        self._last_matrix = matrix