Apparently this is a popular topic. Im a beginner, so my problem is probably something fairly trivial. This is a very simple game kind of like Pong. I am using this code to draw my game:
#Override
public void paint(float deltaTime) {
Graphics g = game.getGraphics();
// draw the game elements
if (state == GameState.Running){
g.drawImage(Assets.back, 0, 0);
//g.drawRect(0, 0, g.getWidth(), g.getHeight(), Color.BLACK);
g.saveCanvas();
g.drawTransRect(0, 0, scene.getLine(), g.getHeight());
g.drawImage(Assets.fore, 0, 0);
//g.drawRect(0, 0, g.getWidth(), g.getHeight(), Color.WHITE);
g.restoreCanvas();
for (Pieces p : pieces){
if (p.getType() == true)
g.drawImage(Assets.pos, p.getX(), p.getY());
if (p.getType() == false){
g.drawImage(Assets.neg, p.getX(), p.getY());
}
}
}
If I run the code as-is, the frame rate looks to be about 15FPS? However, use drawRect (commented out above) instead of the drawImage (background and foreground bmps as Assets), my FPS is at least 60. Im assuming this means that there is much more CPU power involved in displaying bmps vs Rects. How can I use my images and maintain a decent framerate?
Thanks.
EDIT:
My drawImage method looks like this, if it helps:
public void drawImage(Image Image, int x, int y) {
canvas.drawBitmap(((AndroidImage)Image).bitmap, x, y, null);
}
Related
I have been experimenting with squeezing as much performance out of SurfaceView as possible. Currently, I'm subclassing it and implementing a runnable interface on it instead of a callback. I understand there is no hardware acceleration on it.
Still, if I either draw a canvas primitive vertical line scrolling across the screen or a bitmap vertical line, both run slower and slower after each pass. This felt to me like a memory leak, or is it just Android itself? Is OpenGL or another library really my last resort?
I've drawn plenty of scrolling backgrounds before at decent speeds (I think around 5 pixels per tick, this I'm aiming around 20-50 pixels a tick which if anything would be less stops along the way to render).
EDIT: Here is the SurfaceView extended, the thread it makes, the drawing method, and the initialization of it. Basically, this is in a slightly bigger class that just holds this screen's data. The drawXYZ() methods simply use the canvas primitives or a bitmap to paint mainly as the background, which is a solid background color with some vertical and horizontal lines on it like a music staff, little calculating is involved.
The drawCursor is what makes the scrolling vertical line and when I just let it loop the scrolling from left to right, it eventually lags much slower than the first scroll.
public class MySurfaceView extends SurfaceView implements Runnable
{
Thread renderThread = null;
SurfaceHolder holder;
volatile boolean running = false;
public MySurfaceView() {
super(mainActivity);
this.holder = getHolder();
holder.setFixedSize(screenW, screenH);
}
public void resume() {
running = true;
renderThread = new Thread(this);
renderThread.start();
}
#Override
public void run() {
while (running) {
if (!holder.getSurface().isValid()) {
continue;
}
Canvas canvas = holder.lockCanvas();
if(canvas != null) {
doDraw(canvas);
holder.unlockCanvasAndPost(canvas);
}
}
}
public void pause() {
running = false;
while (true) {
try {
renderThread.join();
break;
} catch (InterruptedException e) {
// retry
}
}
}
protected void doDraw(Canvas canvas)
{
canvas.drawColor(Color.rgb(56, 56, 62));
lastNotePlayed = OptionsContainer.getNotePlaying();
//Draw contours (rows).
paint.setColor(Color.rgb(0, 255, 255));
paint.setStrokeWidth(3);
paint.setTextSize(35);
drawContours(canvas, paint);
//Beats per measure (BPM).
paint.setColor(Color.rgb(233, 232, 232));
paint.setStrokeWidth(1);
paint.setStyle(Paint.Style.STROKE);
paint.setPathEffect(bpmLines);
drawBPM(canvas, paint);
paint.setPathEffect(null);
//Draw measures.
paint.setStrokeWidth(5);
drawMeasures(canvas, paint);
//Draw note node inputs.
paint.setColor(Color.rgb(76, 255, 0));
for (int i = 0; i < OptionsContainer.noteList.length; i++) {
if (OptionsContainer.noteList[i].getContour() != 0) {
if (OptionsContainer.noteList[i].getContour() > (OptionsContainer.contour / 2)) {
//Staff on left side, below note.
canvas.drawBitmap(lowerStaffBmp, OptionsContainer.noteList[i].getX(), OptionsContainer.noteList[i].getY(), null);
} else {
canvas.drawBitmap(higherStaffBmp, OptionsContainer.noteList[i].getX(), OptionsContainer.noteList[i].getY() - 40, null);
}
}
}
//Draw cursor.
paint.setStrokeWidth(2);
paint.setColor(Color.WHITE);
drawCursor(canvas, paint);
if (OptionsContainer.isRest)
canvas.drawBitmap(restBmp, (OptionsContainer.screenWidth / 2), (screenHeight - 100) / 2, null);
}
}
#Override
public void init() {
surfaceView = new MySurfaceView();
surfaceView.setLayoutParams(layoutParams);
surfaceView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
// Normalize x,y between 0 and 1
float x = event.getX();
float y = event.getY();
if (x < (OptionsContainer.screenWidth) && y < screenH) {
NoteNode note = new NoteNode(x, y, MainActivity.options);
if (note.getContour() == OptionsContainer.noteList[note.getBeat() - 1].getContour()) {
OptionsContainer.noteList[note.getBeat() - 1] = new NoteNode(x, screenHeight + 200, MainActivity.options);
} else {
OptionsContainer.noteList[note.getBeat() - 1] = note;
}
}
}
return true;
}
});
mainActivity.addContentView(surfaceView, layoutParams);
surfaceView.resume();
}
EDIT #2: Final Answer
Add Path.reset() after the path is drawn in drawBPM(). I'd imagine that stops a memory leak of that path which is trying to keep track of ALL the paths it has been writing and overwriting, little to our knowledge just looking at the lines on the screen. There was a similar Stack Overflow question but fadden's debugging tips below were very helpful for initially trying to figure out what and where it was going wrong.
"Squeezing performance" and Canvas-rendering don't really go together on a SurfaceView, but you can do okay on many devices.
Grafika's "multi-surface test" Activity features a bouncing circle, rendered in software. I haven't noticed it get slower over time, so I suspect something is wrong in your code. Note Grafika does not subclass SurfaceView, and I generally recommend against doing so -- it's too easy to do the wrong thing. The only valid reason to subclass SurfaceView is if you want to draw on both the Surface and the View, e.g. for some sort of mask effect.
You didn't show any code, so there's not much more we can tell you.
I don't see anything blatantly wrong in the code; seems pretty straightforward. I'd check to make sure OptionsContainer.noteList.length isn't growing without bound. Next step would be to use traceview to figure out which part of the rendering is slow, or just spread System.nanoTime() calls around to identify which part is getting progressively slower. If everything in the method shown is executing at a consistent speed except drawCursor(), move the time-check calls into there, narrowing it down until you find what's draining your performance.
If something is consuming memory quickly enough to cause heap issues, you should see a great deal of GC activity in the logcat output. The DDMS allocation tracker tool can help with that.
When I draw more around 100-200 textures all in the same screen, the device becomes very slow and the app crashes without any exceptions. Could you please let me know any best way to have 100 textures without compromising the performance.
I am using the TextureRegion from TextureAtlas.
MainGame
public void render(SpriteBatch sb) {
// TODO Auto-generated method stub
// System.out.println("BallPoolGame Screen - render");
batch = sb;
sb.setProjectionMatrix(camera.combined);
sb.begin();
sb.draw(BACKGROUND_BALL_POOL, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
cellManager.draw(sb);
ballManager.draw(sb);
sb.end();
}
private void setGameTextures() {
gameScreenAtlas = new TextureAtlas("data/texturetutorialpack.pack");
RED_BALL = gameScreenAtlas.findRegion("redball");
// RED_BALL.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
BLUE_BALL = gameScreenAtlas.findRegion("blueball");
// BLUE_BALL.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
GREEN_BALL = gameScreenAtlas.findRegion("greenball");
// GREEN_BALL.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
}
CellManager
public void draw(SpriteBatch sb){
batch=sb;
showImageTexture(MODEL1,207,1);
if(showSelectedCell){
if(allPossiblePathSize>0)
setupBoardCellTexture();
showImage(CELL_SELECTED, rowCoordinate[cellRow], colCoordinate[cellCol]);
}
}
private void setupBoardCellTexture(){
for(CellGrid c : masterGrid){
if(cellTextureIndicator[c.getRow()][c.getCol()]==1){
showImage(CELL_ALL_PATH_TEXTURE,c.getRowCoordinate() ,c.getColCoordinate() );
}
}
}
private void showImage(TextureRegion tr, float rowCoordinate, float colCoordinate) {
batch.draw(tr, colCoordinate,rowCoordinate);
}
BallManager
public void draw(SpriteBatch sb) {
batch = sb;
setupBoardBallTexture();
if (moveTheBall) {
updateBallPosition();
showImage(ball.getTextureRegion(), moveRow + 6, moveCol + 6);
}
squeezeBalls.draw(sb);
}
You are missing some essential data about your app to answer than question:
How big is one texture on average (Size: widthxheight)
On which device is this error occuring (some devices might have less fillrate than others)
What texture filter does the TextureAtlas use (LINEAR, NEAREST, ...)
I guess that you are trying to draw many textures event if they are out of sight. If that is the case you have to implement a check if the cell is visible to the camera.
Another guess would be that you are trying to draw too many elements with the LINEAR TextureFilter. When using linear as a texture filter the gpu needs to sample way more points then with nearest (i think it was 4 times the samples; so in theory your gpu draws 400-800 textures; depending on images size that are too much for mobile gpu fillrates)
Try to describe more circumstances then i can give probably more insight in your problem.
I have a sprite that is supposed to act like a loadbar. I have tried this by using an example image that has been created like a 9patch-type (http://cdn.dibbus.com/wp-content/uploads/2011/03/btn_black.9.png). It seems okay in the start, but as the width of the sprite increases the sprite starts to look pixeled. Anyone know what the problem could be, or have any solution? The code is shown below.
public Sprite loaded;
public void init()
{
atlas = new TextureAtlas(Gdx.files.
internal("data/misc/menu_button.pack"));
loaded = atlas.createSprite("loadbar");
loaded.setPosition((Misc.WIDTH/2) - unloaded.getWidth()/2,
Misc.HEIGTH - unloaded.getHeight());
}
public void draw_load_bar() //render function
{
if(loaded.getWidth() < 600)
{
loaded.setSize(loaded.getWidth()+ 0.5f, loaded.getHeight());
}
loaded.draw(batch);
}
Dont use a Sprite to stretch it. I'd recommend a real Ninepatch from libgdx for it.
public NinePatch loaded;
private float posX, posY, width, height;
public void init()
{
loaded = new NinePatch(the Texture here,10, 10, 10, 10); //bounds outside
//set right pos here...
}
public void draw_load_bar(SpriteBatch batch) //render function
{
if(loaded.getWidth() < 600)
{
//update the size of it here (guess pos is static)
width++;
}
//need to parse the batch and the right sizes.
loaded.draw(batch, posx, posy, width, height);
}
after that you can handle it like a Sprite or Texture but it does stratch right without issues. If you want to the full Picture to be Stretched simply do net set any bounds at the creation new NinePatch(texture, 0,0,0,0)
I'm trying to draw a simple rect on the screen in a class and using it as an actor.
But whatever I do, it seems that there is no option to draw it transparent. Does anyone know how to do this?
Thanks in advance!
public class AreaColorRect extends Actor {
public float opacity = 0.0f;
private Color shapeFillColor = new Color();
public Rectangle area;
public ShapeRenderer shapeRen;
public AreaColorRect(float x, float y, float w, float h) {
shapeRen = new ShapeRenderer();
this.area = new Rectangle(x, y, w, h);
}
#Override
public void draw(SpriteBatch batch, float parentAlpha) {
shapeRen.begin(ShapeType.Filled);
shapeRen.setColor(new Color(shapeFillColor.r, shapeFillColor.g, shapeFillColor.b,
0.0f));
shapeRen.rect(area.x, area.y, area.width, area.height);
shapeRen.end();
}
public void setShapeFillColor(float r, float g, float b) {
this.shapeFillColor = new Color(r, g, b, 1);
}
}
You're mixing contexts. End your SpriteBatch before starting the ShapeRenderer. See libgdx - ShapeRenderer in Group.draw renders in wrong colour. This might not be the problem, though.
You also need to turn on blending. You can just do this once globally, or enable it as necessary (and disable it). It should be enabled by the SpriteBatch context, but I don't think its enabled for the ShapeRenderer.
Gdx.graphics.getGL10().glEnable(GL10.GL_BLEND); // Or GL20
The order you render your background and Actors also makes a difference for transparency.
Finally, you've set the opacity to 0, so the object will be completely invisible. That generally doesn't do anything at all. (I assume you're just trying to get a change from the current 100% visible?)
Sorry for digging this up. Since you are tagging Android, though, I thought I would just chip in my experiences.
I recently spent almost 4 hours on a problem, where alpha blending just wasn't working, as it isn't for you.
Turned out that libgdx' AndroidApplicationConfiguration uses 0 bit for alpha channel as default.
If this is the case for you, too, it might be worth changing that to something more sensible before you initialize() your app.
I just decided to use Scene2d for my game and reached the same question: how to use a rectangle as an actor and draw it on the screen?
Then i found this piece of documentation on the libgdx wiki
(By default the Scene2d has a SpriteBatch that handles drawing of the actors)
If an actor needs to perform drawing differently, such as with a
ShapeRenderer, the Batch should be ended and then begun again at the
end of the method. Of course, this causes the batch to be flushed, so
should be used judiciously. The transformation and projection matrices
from the Batch can be used:
private ShapeRenderer renderer = new ShapeRenderer();
public void draw (Batch batch, float parentAlpha) {
batch.end();
renderer.setProjectionMatrix(batch.getProjectionMatrix());
renderer.setTransformMatrix(batch.getTransformMatrix());
renderer.translate(getX(), getY(), 0);
renderer.begin(ShapeType.Filled);
renderer.setColor(Color.BLUE);
renderer.rect(0, 0, getWidth(), getHeight());
renderer.end();
batch.begin();
}
I just found out something and I was wondering about how and why.
I'm developing a small arcade game for Android. I decided to ignore OpenGL and use the standard SurfaceView and Drawables to do it, since it's suppose to be light (10 sprites or so).
I have drawables that I load, and I use the method Draw and passing them my canvas. This how every sprite is drawn to the screen.
Well it turns out that drawing 4-5 big sprites (200X400 or so) takes a long time on less-than-brand-new phone models. Long enough to make my game unplayable. We're talking about 50-60 milliseconds to draw a single frame using this method. And I really don't do anything there apart from drawing, nowhere I can cut costs. So I decided to try and use Bitmaps instead. Here, however, I need to pre-set the size, since there's no 'setBounds' method in a bitmap. No prob, I resize them to fit my current screen on load, problem solved.
OK. So I got bitmaps. I use Canvas.DrawBitmap now to draw. I bench the new draw method.. and I get a whooping 400% performance boost! Instead of 50-60ms, the entire draw loop now takes 8-12ms. What the hell??
To rule it out, I timed the setBounds too, it takes <1ms so it's not to blame. It's the actual Drawable.Draw that slows things down.
For me this is great news, since I really didn't want to learn OpenGL to make my game playable, but I can't stop wondering about it - Is it fine? are there problems with my method? Why isn't it mentioned anywhere?
The SurfaceView of your Canvas is meant to be used when you should iterate constantly and Drawable is not for that purpose.
Canvas.drawBitmap is doing a lot less work than Drawable.draw so it is faster.
Drawable.draw
Since Drawable is an abstract class, let's look at BitmapDrawable:
BitmapDrawable.draw(canvas)
public void draw(Canvas canvas) {
final Bitmap bitmap = mBitmapState.mBitmap;
if (bitmap == null) {
return;
}
final BitmapState state = mBitmapState;
final Paint paint = state.mPaint;
if (state.mRebuildShader) {
final Shader.TileMode tmx = state.mTileModeX;
final Shader.TileMode tmy = state.mTileModeY;
if (tmx == null && tmy == null) {
paint.setShader(null);
} else {
paint.setShader(new BitmapShader(bitmap,
tmx == null ? Shader.TileMode.CLAMP : tmx,
tmy == null ? Shader.TileMode.CLAMP : tmy));
}
state.mRebuildShader = false;
}
final int restoreAlpha;
if (state.mBaseAlpha != 1.0f) {
final Paint p = getPaint();
restoreAlpha = p.getAlpha();
p.setAlpha((int) (restoreAlpha * state.mBaseAlpha + 0.5f));
} else {
restoreAlpha = -1;
}
final boolean clearColorFilter;
if (mTintFilter != null && paint.getColorFilter() == null) {
paint.setColorFilter(mTintFilter);
clearColorFilter = true;
} else {
clearColorFilter = false;
}
updateDstRectAndInsetsIfDirty();
final Shader shader = paint.getShader();
final boolean needMirroring = needMirroring();
if (shader == null) {
if (needMirroring) {
canvas.save();
// Mirror the bitmap
canvas.translate(mDstRect.right - mDstRect.left, 0);
canvas.scale(-1.0f, 1.0f);
}
canvas.drawBitmap(bitmap, null, mDstRect, paint);
if (needMirroring) {
canvas.restore();
}
} else {
updateShaderMatrix(bitmap, paint, shader, needMirroring);
canvas.drawRect(mDstRect, paint);
}
if (clearColorFilter) {
paint.setColorFilter(null);
}
if (restoreAlpha >= 0) {
paint.setAlpha(restoreAlpha);
}
}
You can see that it even calls canvas.drawBitmap internally.
Canvas.drawBitmap
Compare that to Canvas.drawBitmap. It is much shorter.
Canvas.drawBitmap
public void drawBitmap(#NonNull Bitmap bitmap, float left, float top, #Nullable Paint paint) {
throwIfCannotDraw(bitmap);
native_drawBitmap(mNativeCanvasWrapper, bitmap, left, top,
paint != null ? paint.getNativeInstance() : 0, mDensity, mScreenDensity, bitmap.mDensity);
}
There are a few different drawBitmap methods but all of them are shorter than the Drawable.draw method. Watch out for traps like this to keep your bitmap drawing fast.