Stage, viewport, camera, scaling, and Nexus 7 - camera

I am a newbies in Android and I am learning how to use libgdx as well. I found a few tutorials that use the “DisplayScreen extends AbstractScreen” coding technique, and they use Stage and Actor for displaying output. My interpretation of this coding technique is that DisplayScreen will use whatever in AbstractScreen unless it is #Override (please correct me if I am wrong).
Therefore, if I place the code in AbstractScreen resize() to scale the display to a bigger screen yet maintaining the aspect ratio; the stage in DisplayScreen should resize it to fit the bigger screen. The main objective is that I only want to concentrate my game development in 800x480 environment and completely ignore all different sizes/resolution. The resize() in AbstractScreen will do all the hard work to scale and fit my game to any resolution.
Please allow me to use my test example for better explanation. I have no problem displaying my 800x480 black background on my phone. However, the same background was displayed BUT not maintaining its aspect ratio on Nexus 7.
This turorial fixed my problem mentioned above (I adopted to have two black bars on both side of the screen). However, I have a small problem integrating this solution to the “DisplayScreen extends AbstractScreen” technique.
Please see this screen shot here. My issues are:
Why my black box is not resize to fit the screen, yet leaving two red bar on both sides of the screen?
I don’t understand why the black image only displaying 766x480 on my Nexus 7?
It will be fantastic if someone can point me to the right direction.
Code for awesomegame
package com.example.somegame;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.assets.AssetManager;
import com.example.somegame.screens.DisplayScreen;
public class awesomegame extends Game {
public static AssetManager AssetManager = new AssetManager();
#Override
public void create() {
}
#Override
public void render() {
super.render();
}
#Override
public void resize(int width, int height) {
super.resize(width, height);
setScreen( new DisplayScreen(this) );
}
#Override
public void setScreen(Screen screen) {
super.setScreen( screen );
}
Code for AbstractScreen
package com.example.somegame.screens;
import com.example.somegame.awesomegame;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.Scaling;
public class AbstractScreen implements Screen{
private awesomegame awesomegame;
private Stage stage;
private BitmapFont font;
private SpriteBatch batch;
private OrthographicCamera camera;
public AbstractScreen(awesomegame awesomegame) {
this.awesomegame = awesomegame;
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
camera.update();
stage = new Stage(800, 480, false);
}
#Override
public void render(float delta) {
stage.act( delta );
Gdx.gl.glClearColor( .5f, .5f, 0f, 1f );
Gdx.gl.glClear( GL20.GL_COLOR_BUFFER_BIT );
stage.draw();
}
#Override
public void resize(int width, int height) {
Vector2 size = Scaling.fit.apply(800, 480, width, height);
int viewportX = (int)(width - size.x) / 2;
int viewportY = (int)(height - size.y) / 2;
int viewportWidth = (int)size.x;
int viewportHeight = (int)size.y;
Gdx.gl.glViewport(viewportX, viewportY, viewportWidth, viewportHeight);
stage.setViewport(800, 480, true);
}
Code for DisplayScreen
package com.example.somegame.screens;
import com.example.somegame.awesomegame;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
public class DisplayScreen extends AbstractScreen {
private Image loadingBg;
private Stage stage;
float loadingPercent;
public DisplayScreen(awesomegame awesomegame) {
super (awesomegame);
}
#Override
public void show()
{
super.show();
awesomegame.AssetManager.load("img/loading.atlas", TextureAtlas.class);
awesomegame.AssetManager.finishLoading();
stage = new Stage();
TextureAtlas atlas = awesomegame.AssetManager.get("img/loading.atlas", TextureAtlas.class);
loadingBg = new Image(atlas.findRegion("loadingBg"));
loadingBg.setSize(800, 480);
loadingBg.setX(0);
loadingBg.setY(0);
stage.addActor(loadingBg);
// add all asset need to be loaded here. for example
// awesomegame.AssetManager.load("img/whatever.pack", TextureAtlas.class);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor( 1f, 0f, 0f, 1f );
stage.draw();
}

The Nexus 7 has a screen resolution of 1280 x 800, but part of the height is used for the onscreen menu panel (with the back/home/menu buttons).
The main culprit in your code is here, where you try to enforce a specific aspect ratio that doesn't fit this adjusted dimension, resulting in those bars on the side:
public void resize(int width, int height) {
Vector2 size = Scaling.fit.apply(800, 480, width, height);
...
}
Looks like you pulled that resize function off another stackoverflow post. I had done the same, but switched to something simpler when i ran into the same issue:
public void resize(int width, int height) {
stage.setViewport(true, width,height);
stage.getCamera().setToOrtho(false,width,height);
...
}

This code works for me with the latest update:
OrthographicCamera is cam, this makes no cropping, just changes the viewport so the width is still "that many" times larger than the actual window/device
public void resize(int width, int height) {
int newW = width, newH = height;
if (cam.viewportWidth > width) {
float scale = (float) cam.viewportWidth / (float) width;
newW *= scale;
newH *= scale;
}
// true here to flip the Y-axis
cam.setToOrtho(true, newW, newH);
}

Related

Dynamically updating Polyline points in tornadofx

This question is a bit simplistic, but i couldn't figure it out for myself... What I'm trying to do is using a JavaFX Timeline to update my Polyline points. What I've got until now is as follows:
class MainView : View("Hello TornadoFX") {
var myLine: Polyline by singleAssign()
val myTimeline = timeline {
cycleCount = INDEFINITE
}
override val root = hbox {
myLine = polyline(0.0, 0.0, 100.0, 100.0)
myTimeline.apply {
keyFrames += KeyFrame((1/10.0).seconds, {
myLine.points.forEachIndexed { i, d ->
myLine.points[i] = d + 1
}
println(myLine.points)
})
play()
}
}
}
Although the point list does update the values, as shown when printing them, the change is not reflected in the ui.
Thank you very much for your help!
I have not worked with TornadoFX earlier, so I gave a try with the normal JavaFX. Looks like the the UI is updating when the points are updated. May be the issue is something related to your implementation with TornadoFX.
Please check below the working example.
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Polyline;
import javafx.stage.Stage;
import javafx.util.Duration;
public class PolyLinePointsUpdateDemo extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
Pane root = new Pane();
Scene scene = new Scene(root, 600,600);
primaryStage.setScene(scene);
primaryStage.setTitle("PolyLine Points Update");
primaryStage.show();
Polyline line = new Polyline(0.0, 0.0, 100.0, 100.0);
root.getChildren().add(line);
Timeline timeline = new Timeline();
timeline.getKeyFrames().add(new KeyFrame(Duration.millis(250), e->{
for (int i = 0; i < line.getPoints().size(); i++) {
double d = line.getPoints().get(i);
line.getPoints().set(i, d+1);
}
System.out.println(line.getPoints());
}));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}
public static void main(String... a){
Application.launch(a);
}
}
Figured out that the issue was simply using an hbox as the parent layout, instead of a pane, which handles the chidren positioning with absolute coordinates.

Libgdx - camera.unproject is not fixing my coordinates

The following code gives me very strange y coordinates.
10-18 00:13:36.834 30543-30567/com.xxxx.yyyy.android I/x﹕ 137.4782
10-18 00:13:36.834 30543-30567/com.xxxx.yyyy.android I/y﹕ -1984.2426
10-18 00:13:36.835 30543-30567/com.xxxx.yyyy.android I/ux﹕ 91.65213
10-18 00:13:36.835 30543-30567/com.xxxx.yyyy.android I/uy﹕ -1984.2426
I imagine I set up everything wrong rather than do it wrong while running?
The camera.unproject call should take care of all remapping from screen coordinates to game coordinates, shouldn't it? Or do i have to scale and invert before unprojecting?
package com.xxxx.yyyy;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
public class LetterActor extends Actor
{
private Texture texture;
private Vector3 touchPosition = new Vector3();
private Camera camera;
private boolean unproject = true;
public LetterActor(Texture letterTexture, Camera theCamera)
{
texture = letterTexture;
camera = theCamera;
touchPosition.set(240, 800, 0);
camera.unproject(touchPosition);
setPosition(touchPosition.x, touchPosition.y);
setSize(texture.getWidth(), texture.getHeight());
addListener(new InputListener()
{
#Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button)
{
touchPosition.set(x, y, 0);
if (unproject)
{
camera.unproject(touchPosition);
}
setPosition(touchPosition.x, touchPosition.y);
logPositions(x, y, touchPosition.x, touchPosition.y);
return true;
}
#Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button)
{
touchPosition.set(x, y, 0);
if (unproject)
{
camera.unproject(touchPosition);
}
setPosition(touchPosition.x, touchPosition.y);
logPositions(x, y, touchPosition.x, touchPosition.y);
}
#Override
public void touchDragged(InputEvent event, float x, float y, int pointer)
{
touchPosition.set(x, y, 0);
if (unproject)
{
camera.unproject(touchPosition);
}
setPosition(touchPosition.x, touchPosition.y);
logPositions(x, y, touchPosition.x, touchPosition.y);
}
});
}
private void screenTo()
{
}
private void logPositions(float x, float y,float ux, float uy)
{
Gdx.app.log("x", Float.toString(x));
Gdx.app.log("y", Float.toString(y));
Gdx.app.log("ux", Float.toString(ux));
Gdx.app.log("uy", Float.toString(y));
}
#Override
public void draw(Batch batch, float alpha)
{
batch.draw(texture, getX(), getY(), getWidth(), getHeight());
}
#Override
public void act(float delta) {}
}
package com.xxxx.yyyy;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.utils.viewport.ExtendViewport;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.utils.viewport.FitViewport;
public class WordPuzzle extends ApplicationAdapter
{
private final static float VIRTUAL_WIDTH = 480;
private final static float VIRTUAL_HEIGHT = 800;
private OrthographicCamera camera;
private FitViewport viewport;
private Stage stage;
#Override
public void create()
{
camera = new OrthographicCamera(VIRTUAL_WIDTH, VIRTUAL_HEIGHT);
camera.setToOrtho(false, VIRTUAL_WIDTH, VIRTUAL_HEIGHT);
viewport = new FitViewport(VIRTUAL_WIDTH, VIRTUAL_HEIGHT, camera);
stage = new Stage();
stage.setViewport(viewport);
Gdx.input.setInputProcessor(stage);
Texture[] textures = LetterLoader.loadLetters();
for (int i = 0; i < textures.length; i++)
{
LetterActor letterActor = new LetterActor(textures[i], camera);
letterActor.setTouchable(Touchable.enabled);
stage.addActor(letterActor);
}
}
#Override
public void render()
{
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
}
#Override public void resize(int width, int height)
{
stage.getViewport().update(width, height, true);
}
#Override public void dispose()
{
stage.dispose();
}
}
package com.xxxx.yyyy;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
public class LetterLoader {
public static Texture[] loadLetters()
{
Texture[] letters = new Texture[26];
for (int i = 0; i < 26; i++)
{
char letter = (char) (i + 65);
letters[i] = new Texture(Gdx.files.internal("bigletters/" + letter + ".png"));
}
return letters;
}
}
First, the touch position (x, y) you get from the input listener are already the correct coordinates.
Concerning your output, you actually print y two times, but call it uy the second time:
Gdx.app.log("uy", Float.toString(y));
If touchPosition.set(240, 800, 0); is in screen coordinates, then you need to unproject them, but
camera.unproject(touchPosition);
assumes that your camera fills the whole screen, thus it calls internally:
unproject(screenCoords, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Since you use a virtual size, this is wrong. The most simple solution would be to use the unproject method from the viewport that you are using:
viewport.unproject(touchPosition);
This will call the camera unproject method with the correct parameters automatically.
Since you are using Stage and InputListener, the coordinates you get in touchDown and the related methods are already in world coordinates, so it doesn't make sense to unproject them. You can use the x and y directly.
Also (although this is irrelevant to InputListener), camera.unproject assumes a Viewport that fills the screen, which is not true of FitViewport, which you're using. If you are using a Viewport class, you need to use viewport.unproject instead of camera.unproject, so it takes the black bars into account.
But you only need to worry about unprojecting for stuff not related to the Stage.

LibGDX stage coordinates change on window resize

I have seen lots of topics on LibGDX and screen/cam coordinates and also some on window resizing, but I just can't find the solution to the following problem I have.
When making a basic stage and a basic actor in this stage, say windowsize 480x320, everything is OK. I can click my actor and it will respond. But when I resize my window, say to 600x320, everything looks right, but my clicklistener is not working anymore. Also, the stage coordinates are moved or messed up.
I use the following code:
stage.addListener(new InputListener() {
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
//determine if actor was hit
System.out.println(stage.hit(x, y, true));
return true;
}
});
Also, I am resizing my stage camera viewport to correspond to the window:
stage.getCamera().viewportWidth = Gdx.graphics.getWidth();
stage.getCamera().viewportHeight = Gdx.graphics.getHeight();
So when resizing, I get the desired effect on screen, but my listener does not respond - the actor seems 'offset' of where I am clicking. What am I doing wrong? Should I move my actor or my cam, or zoom my cam according to the resize? Can someone please explain this to me?
Thanks a lot in advance!
EDIT: below is the complete code of my class.
public class HelpMePlease implements ApplicationListener{
// A standard simple Actor Class
class CustomActor extends Actor {
Texture texture = new Texture(Gdx.files.internal("data/testTex2.png"));
TextureRegion pixelTexture = new TextureRegion(texture, 0, 0, 1, 1);
Sprite sprite = new Sprite(texture);
public CustomActor() {
setWidth(128);
setHeight(128);
setBounds(getX(), getY(), getWidth(), getHeight());
}
#Override
public void draw(SpriteBatch batch, float parentAlpha) {
batch.draw(sprite, getX(), getY(), 0f, 0f, getWidth(), getHeight(), getScaleX(), getScaleY(), getRotation());
}
}
public Stage stage;
public CustomActor actor;
#Override
public void create() {
stage = new Stage(480,320,true);
actor = new CustomActor();
stage.addListener(new InputListener() {
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
//determine if actor was hit
System.out.println(stage.hit(x, y, true));
return true;
}
});
Gdx.input.setInputProcessor(stage);
stage.addActor(actor);
}
#Override
public void resize(int width, int height) {
//resize cam viewport
stage.getCamera().viewportWidth = Gdx.graphics.getWidth();
stage.getCamera().viewportHeight = Gdx.graphics.getHeight();
}
#Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
stage.getCamera().update(); //just to be sure, I don't know if this is necessary
stage.act();
stage.draw();
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
// TODO Auto-generated method stub
}
}
You can change your resize por this using the latest nightly.
#Override
public void resize(int width, int height) {
stage.getViewport().update(width, height, true);
}
the last parameter "true" will center the camera in the screen
I think your actor is positioning itself good enough, but your display may be a bit off.
Try
batch.draw(sprite, getX(), getY(), 0f, 0f, getWidth(), getHeight(), getScaleX(), getScaleY(), getRotation());
Instead of
batch.draw(sprite, getX(), getY(), getWidth(), getHeight(), 0f, 0f, getScaleX(), getScaleY(), getRotation());
Spritebatch has the following arguments:
public void draw (Texture texture, float x, float y, float width, float height, int srcX, int srcY, int srcWidth,int srcHeight, boolean flipX, boolean flipY)
I guess you just mixed some arguments up by mistake, would you kindly take a look at it?
Problem solved by updating my LibGDX Version using Gradle and using the new Viewport options!
Thanks for taking the time everyone!
In my case adding
stage.getViewport().setScreenSize(width, height);
in resize() solved problem

JavaFX How to change ProgressBar color dynamically?

I was trying to solve my problem with colored progress bars in this thread. The solution was present, but then I ran into another problem: I can't change color dynamically from my code. I want to do it right from my code, not with pre-defined .css. Generally I can do it, but I run into some difficulties when I try to do it with more than one progess bar.
public class JavaFXApplication36 extends Application {
#Override
public void start(Stage primaryStage) {
AnchorPane root = new AnchorPane();
ProgressBar pbRed = new ProgressBar(0.4);
ProgressBar pbGreen = new ProgressBar(0.6);
pbRed.setLayoutY(10);
pbGreen.setLayoutY(30);
pbRed.setStyle("-fx-accent: red;"); // line (1)
pbGreen.setStyle("-fx-accent: green;"); // line (2)
root.getChildren().addAll(pbRed, pbGreen);
Scene scene = new Scene(root, 150, 50);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
}
I always get 2 red progressbars with it! It seems that code in line (1) changes the style of ProgressBar class, not the instance.
Another strange moment is that deleting line (1) don't result in 2 green progress bars. So I can figure that line (2) is completely useless!! WHY?! That's definitely getting odd.
Is there any way to set different colors for separate progressbars?
See also the StackOverflow JavaFX ProgressBar Community Wiki.
There is a workaround you can use until a bug to fix the sample code in your question is filed and fixed.
The code in this answer does a node lookup on the ProgressBar contents, then dynamically modifies the bar colour of the progress bar to any value you like.
import javafx.application.Application;
import javafx.beans.value.*;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ProgressBarDynamicColor extends Application {
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) {
PickedColorBar aquaBar = new PickedColorBar(0.4, Color.AQUA);
PickedColorBar fireBar = new PickedColorBar(0.6, Color.FIREBRICK);
HBox layout = new HBox(20);
layout.getChildren().setAll(aquaBar, fireBar);
layout.setStyle("-fx-background-color: -fx-box-border, cornsilk; -fx-padding: 15;");
stage.setScene(new Scene(layout));
stage.show();
aquaBar.wasShown();
fireBar.wasShown();
}
class PickedColorBar extends VBox {
private final ProgressBar bar;
private final ColorPicker picker;
private boolean wasShownCalled = false;
final ChangeListener<Color> COLOR_LISTENER = new ChangeListener<Color>() {
#Override public void changed(ObservableValue<? extends Color> value, Color oldColor, Color newColor) {
setBarColor(bar, newColor);
}
};
public PickedColorBar(double progress, Color initColor) {
bar = new ProgressBar(progress);
picker = new ColorPicker(initColor);
setSpacing(10);
setAlignment(Pos.CENTER);
getChildren().setAll(bar, picker);
}
// invoke only after the progress bar has been shown on a stage.
public void wasShown() {
if (!wasShownCalled) {
wasShownCalled = true;
setBarColor(bar, picker.getValue());
picker.valueProperty().addListener(COLOR_LISTENER);
}
}
private void setBarColor(ProgressBar bar, Color newColor) {
bar.lookup(".bar").setStyle("-fx-background-color: -fx-box-border, " + createGradientAttributeValue(newColor));
}
private String createGradientAttributeValue(Color newColor) {
String hsbAttribute = createHsbAttributeValue(newColor);
return "linear-gradient(to bottom, derive(" + hsbAttribute+ ",30%) 5%, derive(" + hsbAttribute + ",-17%))";
}
private String createHsbAttributeValue(Color newColor) {
return
"hsb(" +
(int) newColor.getHue() + "," +
(int) (newColor.getSaturation() * 100) + "%," +
(int) (newColor.getBrightness() * 100) + "%)";
}
}
}
The code uses inlined string processing of css attributes to manipulate Region backgrounds. Future JavaFX versions (e.g. JDK8+) will include a public Java API to manipulate background attributes, making obsolete the string processing of attributes from the Java program.
Sample program output:

What is needed in this call to gdk_get_pixmap?

I have created a little drawing area class and now need a pixmap to draw into during the expose event callback. But I can't get any parameter that I have tried to compile. Here are the relevant parts of the code...
The class definition...
class set_display_drawing_area : public Gtk::DrawingArea
{
public:
set_display_drawing_area ();
virtual ~set_display_drawing_area ();
protected:
virtual bool on_expose_event(GdkEventExpose* event);
private:
GdkPixmap *pixmap_ptr;
};
and the expose callback...
bool set_display_drawing_area::on_expose_event(GdkEventExpose* event)
{
Glib::RefPtr<Gdk::Window> window = get_window();
if (window)
{
Gtk::Allocation allocation = get_allocation();
const int width = allocation.get_width();
const int height = allocation.get_height();
pixmap_ptr = gdk_pixmap_new (window, // <-- What is needed here?
width,
height,
-1);
You're mixing gtkmm (C++) and gtk (C) style code here. gdk_pixmap_new is a C function which has no idea about templates and classes (such as Glib::RefPtr). You'll probably want to use gtkmm for your pixmap as well:
Glib::RefPtr<Gdk::Pixmap> pixmap;
and
pixmap = Gdk::Pixmap::create(window, width, height);