LIBGDX runs fine on desktop, but crashes on android - java

I've been looking through this code for over 2 days and still can't find any errors in the code as to why it crashes on Android. It works perfectly fine on desktop.
Android Target: 4.0.3
Android Phone used: HTC Desire C
Logcat:
04-07 16:42:35.785: E/AndroidRuntime(24197): FATAL EXCEPTION: GLThread 2955
04-07 16:42:35.785: E/AndroidRuntime(24197): java.lang.ClassCastException: com.badlogic.gdx.math.Vector2 cannot be cast to java.lang.String
04-07 16:42:35.785: E/AndroidRuntime(24197): at com.survivegameandroidtest.survive.Player.readPlayer(Player.java:191)
04-07 16:42:35.785: E/AndroidRuntime(24197): at com.survivegameandroidtest.survive.MainMenu.loadPlayer(MainMenu.java:278)
04-07 16:42:35.785: E/AndroidRuntime(24197): at com.survivegameandroidtest.survive.MainMenu.show(MainMenu.java:127)
04-07 16:42:35.785: E/AndroidRuntime(24197): at com.badlogic.gdx.Game.setScreen(Game.java:62)
04-07 16:42:35.785: E/AndroidRuntime(24197): at com.survivegameandroidtest.survive.GameHub.create(GameHub.java:12)
04-07 16:42:35.785: E/AndroidRuntime(24197): at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceChanged(AndroidGraphics.java:334)
04-07 16:42:35.785: E/AndroidRuntime(24197): at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1463)
04-07 16:42:35.785: E/AndroidRuntime(24197): at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1224)
Like I said, this works fine on desktop, but crashes on Android.
Player class
package com.survivegameandroidtest.survive;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
public class Player implements Serializable{
private static final long serialVersionUID = 1L;
SpriteBatch batch;
static Vector2 position = new Vector2(1,1);
Vector2 size;
Vector2 boundSize;
Vector2 boundOffset;
Texture texture;
Rectangle bounds;
String direction = "";
StringCheese cheese;
EnemyCheddarling enemy;
int health = 0, damage;
boolean alive;
private static final int col = 4, row = 4;
Animation animation;
TextureRegion[] frames;
TextureRegion currentFrame;
float stateTime;
int speed = 0;
static String name = "";
public Player(Texture texture, Vector2 position, Vector2 size, Vector2 boundSize, Vector2 boundOffset) {
this.texture = texture;
Player.position = position;
this.size = size;
this.boundOffset = boundOffset;
TextureRegion[][] tmp = TextureRegion.split(texture, texture.getWidth() / col, texture.getHeight() / row);
frames = new TextureRegion[col * row];
int index = 0;
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
frames[index++] = tmp[i][j];
}
}
animation = new Animation(1f, frames);
stateTime = 0f;
currentFrame = animation.getKeyFrame(0);
this.boundSize = boundSize;
bounds = new Rectangle(position.x + boundOffset.x, position.y + boundOffset.y, boundSize.x, boundSize.y);
health = 100;
damage = 20;
alive = true;
name = "SET YO NAME FOOL";
}
public void update() {
bounds.set(position.x + boundOffset.x, position.y + boundOffset.y, boundSize.x, boundSize.y);
if(health <= 0) {
alive = false;
}
stateTime += Gdx.graphics.getDeltaTime()*8;
if(stateTime > col) {
stateTime = 0;
}
//WASD MOVE METHOD
if(Gdx.input.isKeyPressed(Keys.W)) {
position.y += 2f;
currentFrame = animation.getKeyFrame(12 + stateTime);
direction = "up";
speed = 2;
}
if(Gdx.input.isKeyPressed(Keys.A)) {
position.x -= 2f;
currentFrame = animation.getKeyFrame(4 + stateTime);
direction = "left";
speed = 2;
}
if(Gdx.input.isKeyPressed(Keys.S)) {
position.y -= 2f;
currentFrame = animation.getKeyFrame(0 + stateTime);
direction = "down";
speed = 2;
}
if(Gdx.input.isKeyPressed(Keys.D)) {
position.x += 2f;
currentFrame = animation.getKeyFrame(8 + stateTime);
direction = "right";
speed = 2;
}
//ACCELEROMETER MOVE METHOD
if(Gdx.input.getAccelerometerX() != 1 || Gdx.input.getAccelerometerX() != 0 || Gdx.input.getAccelerometerX() != -1 || Gdx.input.getAccelerometerY() != 1 || Gdx.input.getAccelerometerY() != 0 || Gdx.input.getAccelerometerY() != -1) {
for(int rotation = 2; rotation < 5; rotation++) {
if(Gdx.input.getAccelerometerX() <= -rotation) { //DOWN
position.y += rotation;
currentFrame = animation.getKeyFrame(12 + stateTime);
direction = "down";
speed = rotation;
}
if(Gdx.input.getAccelerometerX() >= rotation) { //UP
position.y -= rotation;
currentFrame = animation.getKeyFrame(0 + stateTime);
direction = "up";
speed = rotation;
}
if(Gdx.input.getAccelerometerY() <= -rotation) { //LEFT
position.x -= rotation;
currentFrame = animation.getKeyFrame(4 + stateTime);
direction = "left";
speed = rotation;
}
if(Gdx.input.getAccelerometerY() >= rotation) { //RIGHT
position.x += rotation;
currentFrame = animation.getKeyFrame(8 + stateTime);
direction = "right";
speed = rotation;
}
}
}
}
public void draw(SpriteBatch batch) {
batch.draw(currentFrame, position.x, position.y, size.x, size.y);
}
public void collision() {
if(direction == "up") {
position.y += speed;
}
if(direction == "down") {
position.y -= speed;
}
if(direction == "left") {
position.y -= speed;
}
if(direction == "right") {
position.y += speed;
}
}
public static void savePlayer(Player playerName) throws IOException{
FileHandle file = Gdx.files.local("player.dat");
OutputStream out = null;
try{
file.writeBytes(serialize(name), false);
}catch(Exception ex){
System.out.println(ex.toString());
}finally{
if(out != null) try{out.close();} catch(Exception ex){}
}
try {
System.out.println("Saving Player" + " " + deserialize(file.readBytes()));
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String readPlayer() throws IOException, ClassNotFoundException{
String playerName = "";
FileHandle file = Gdx.files.local("player.dat");
playerName = (String) deserialize(file.readBytes());
System.out.println("Reading Player");
return playerName;
}
private static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(obj);
return b.toByteArray();
}
public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream b = new ByteArrayInputStream(bytes);
ObjectInputStream o = new ObjectInputStream(b);
return o.readObject();
}
//GETTERS AND SETTERS
public SpriteBatch getBatch() {
return batch;
}
public String getName() {
return name;
}
public void setName(String object) {
Player.name = object;
}
public Vector2 getBoundOffset() {
return boundOffset;
}
public void setBoundOffset(Vector2 boundOffset) {
this.boundOffset = boundOffset;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getDamage() {
return damage;
}
public void setDamage(int damage) {
this.damage = damage;
}
public boolean isAlive() {
return alive;
}
public void setAlive(boolean alive) {
this.alive = alive;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public StringCheese getCheese() {
return cheese;
}
public void setCheese(StringCheese cheese) {
this.cheese = cheese;
}
public Rectangle getBounds() {
return bounds;
}
public void setBounds(Rectangle bounds) {
this.bounds = bounds;
}
public Vector2 getSize() {
return size;
}
public void setSize(Vector2 size) {
this.size = size;
}
public Vector2 getBoundSize() {
return boundSize;
}
public void setBoundSize(Vector2 boundSize) {
this.boundSize = boundSize;
}
public Texture getTexture() {
return texture;
}
public void setTexture(Texture texture) {
this.texture = texture;
}
public Animation getAnimation() {
return animation;
}
public void setAnimation(Animation animation) {
this.animation = animation;
}
public TextureRegion[] getFrames() {
return frames;
}
public void setFrames(TextureRegion[] frames) {
this.frames = frames;
}
public TextureRegion getCurrentFrame() {
return currentFrame;
}
public void setCurrentFrame(TextureRegion currentFrame) {
this.currentFrame = currentFrame;
}
public float getStateTime() {
return stateTime;
}
public void setStateTime(float stateTime) {
this.stateTime = stateTime;
}
public static int getCol() {
return col;
}
public static int getRow() {
return row;
}
public void setBatch(SpriteBatch batch) {
this.batch = batch;
}
public Vector2 getPosition() {
return position;
}
public void setPosition(Vector2 position) {
Player.position = position;
}
}
In savePlayer(), I try to serialize the String variable 'name'.
System.out.println("Saving Player" + " " + deserialize(file.readBytes()));
^ This line of code prints out "Saving Player Hosif Yimms" in the console, and none of the methods return a Vector2.
ANSWER: Used a FileHandle method to save the players name, as deserialize return an Object, not String.

Why are you using Object serialization for strings anyway? Just get a reader/writer for your FileHandle. – Chase
public static void savePlayerName(Player player) {
FileHandle file = Gdx.files.local("playername.dat");
file.writeString(player.getName(), false);
}
public static String readPlayerName() {
FileHandle file = Gdx.files.local("playername.dat");
String name = file.readString();
return name;
}

Related

Pacman method for move Java libGDX

I'am working on Pacman clone with Java and libGDX
How to make Pacman move by pressing one button?
Here is my code for moving, but I think it's not the best option:
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
public class Hero {
private int rightBorder;
private int leftBorder;
private int top;
private int bottom;
private GameController gc;
private float cellX;
private float cellY;
private TextureRegion texture;
private float speed;
private boolean isPressedD;
private boolean isPressedA;
private boolean isPressedW;
private boolean isPressedS;
private float offset;
private StringBuilder stringBuilder;
private int score;
public Hero(TextureAtlas atlas, GameController gc){
this.texture = atlas.findRegion("Pacman");
this.cellX = 1;
this.cellY = 1;
this.speed = 5f;
this.isPressedD = false;
this.isPressedA = false;
this.isPressedS = false;
this.isPressedW = false;
this.offset = 36;
this.stringBuilder = new StringBuilder();
this.score = 0;
this.gc = gc;
this.leftBorder = 0;
this.rightBorder = 15;
this.top = 8;
this.bottom = 0;
}
public void update(float dt){
movement(dt);
checkBounds();
}
private void checkBounds(){
if (cellX > rightBorder){
cellX = rightBorder;
}
if (cellX < leftBorder){
cellX = leftBorder;
}
if (cellY > top){
cellY = top;
}
if (cellY < bottom){
cellY = bottom;
}
// if (position.x > 1280 - offset){
// position.x = 1280 - offset;
// }
// if (position.x < 0 + offset){
// position.x = 0 + offset;
// }
// if (position.y > 720 - offset){
// position.y = 720 - offset;
// }
// if (position.y < 0 + offset){
// position.y = 0 + offset;
// }
}
public void movement(float dt){
if (Gdx.input.isKeyJustPressed(Input.Keys.D)){
isPressedD = true;
isPressedA = false;
isPressedS = false;
isPressedW = false;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.A)){
isPressedD = false;
isPressedA = true;
isPressedS = false;
isPressedW = false;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.S)){
isPressedD = false;
isPressedA = false;
isPressedS = true;
isPressedW = false;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.W)){
isPressedD = false;
isPressedA = false;
isPressedS = false;
isPressedW = true;
}
if (isPressedA){
cellX -= speed * dt;
}
if (isPressedD){
cellX += speed * dt;
}
if (isPressedS){
cellY -= speed * dt;
}
if (isPressedW){
cellY += speed * dt;
}
}
public void renderGUI(SpriteBatch batch, BitmapFont font){
stringBuilder.setLength(0);
stringBuilder.append("Score: " + score);
font.draw(batch, stringBuilder, 10, 700);
}
public void render(SpriteBatch batch){
batch.draw(texture, cellX * GameMap.CELL_SIZE, cellY * GameMap.CELL_SIZE);
}
}
Here is moving method directly:
public void movement(float dt){
if (Gdx.input.isKeyJustPressed(Input.Keys.D)){
isPressedD = true;
isPressedA = false;
isPressedS = false;
isPressedW = false;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.A)){
isPressedD = false;
isPressedA = true;
isPressedS = false;
isPressedW = false;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.S)){
isPressedD = false;
isPressedA = false;
isPressedS = true;
isPressedW = false;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.W)){
isPressedD = false;
isPressedA = false;
isPressedS = false;
isPressedW = true;
}
if (isPressedA){
cellX -= speed * dt;
}
if (isPressedD){
cellX += speed * dt;
}
if (isPressedS){
cellY -= speed * dt;
}
if (isPressedW){
cellY += speed * dt;
}
}
It's working but I can't ckeck collisions with walls.
How to change method for moving?
I need to press button and release immediately.
No need to create booleans and then do checks on them. Just check if the key is pressed and then put your code in that if statement.
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
public class Hero {
private int rightBorder;
private int leftBorder;
private int top;
private int bottom;
private GameController gc;
private float cellX;
private float cellY;
private TextureRegion texture;
private float speed;
private float offset;
private StringBuilder stringBuilder;
private int score;
public Hero(TextureAtlas atlas, GameController gc){
this.texture = atlas.findRegion("Pacman");
this.cellX = 1;
this.cellY = 1;
this.speed = 5f;
this.offset = 36;
this.stringBuilder = new StringBuilder();
this.score = 0;
this.gc = gc;
this.leftBorder = 0;
this.rightBorder = 15;
this.top = 8;
this.bottom = 0;
}
public void update(float dt){
movement(dt);
checkBounds();
}
private void checkBounds(){
if (cellX > rightBorder){
cellX = rightBorder;
}
if (cellX < leftBorder){
cellX = leftBorder;
}
if (cellY > top){
cellY = top;
}
if (cellY < bottom){
cellY = bottom;
}
// if (position.x > 1280 - offset){
// position.x = 1280 - offset;
// }
// if (position.x < 0 + offset){
// position.x = 0 + offset;
// }
// if (position.y > 720 - offset){
// position.y = 720 - offset;
// }
// if (position.y < 0 + offset){
// position.y = 0 + offset;
// }
}
public void movement(float dt){
if (Gdx.input.isButtonPressed(Input.Keys.D)){
cellX += speed * dt;
}
else if (Gdx.input.isButtonPressed(Input.Keys.A)){
cellX -= speed * dt;
}
else if (Gdx.input.isButtonPressed(Input.Keys.S)){
cellY -= speed * dt;
}
else if (Gdx.input.isButtonPressed(Input.Keys.W)){
cellY += speed * dt;
}
}
public void renderGUI(SpriteBatch batch, BitmapFont font){
stringBuilder.setLength(0);
stringBuilder.append("Score: " + score);
font.draw(batch, stringBuilder, 10, 700);
}
public void render(SpriteBatch batch){
batch.draw(texture, cellX * GameMap.CELL_SIZE, cellY * GameMap.CELL_SIZE);
}
}

Can't seem to access the image file in my PlayerClass even though it is properly loaded

I'm creating a 2D java game and ran into a nullpointer exception. Whenever I call my render in the playstate class, it throws the exception. I had previously rendered the Font file and got it to work when commenting out the player object references. The player "linkformatted.png" file is able to load after trying and catching, but the nullpointer exception stays. Changing the values didn't work.
public class PlayState extends GameState {
private Font font;
private Player player;
public PlayState(GameStateManager gsm) {
super(gsm);
font = new Font("font/ZeldaFont.png", 16, 16);
player = new Player(new Sprite("entity/linkformatted.png"), new Vector2f(100, 100), 32);
}
public void update() {
player.update();
}
public void input(MouseHandler mouse, KeyHandler key) {
player.input(mouse, key);
}
public void render(Graphics2D g) {
Sprite.drawArray(g, font, "YOU", new Vector2f(100, 100), 32, 32, 16, 0);
player.render(g);
}
}
public class Sprite {
private BufferedImage SPRITESHEET = null;
private BufferedImage[][] spriteArray;
private final int TILE_SIZE = 32;
public int w;
public int h;
private int wSprite;
private int hSprite;
public Sprite(String file) {
w = TILE_SIZE;
h = TILE_SIZE;
System.out.println("Loading: " + file + "...");
SPRITESHEET = loadSprite(file);
wSprite = SPRITESHEET.getWidth() / w;
hSprite = SPRITESHEET.getHeight() / h;
loadSpriteArray();
}
public Sprite(String file, int w, int h) {
this.w = w;
this.h = h;
System.out.println("Loading: " + file + "...");
SPRITESHEET = loadSprite(file);
wSprite = SPRITESHEET.getWidth() / w;
hSprite = SPRITESHEET.getHeight() / h;
loadSpriteArray();
}
public void setSize(int width, int height) {
setWidth(width);
setHeight(height);
}
public void setWidth(int i) {
w = i;
wSprite = SPRITESHEET.getWidth() / w;
}
public void setHeight(int i) {
h = i;
hSprite = SPRITESHEET.getHeight() / h;
}
public int getWidth() {
return w;
}
public int getHeight() {
return h;
}
private BufferedImage loadSprite(String file) {
BufferedImage sprite = null;
try {
sprite = ImageIO.read(getClass().getClassLoader().getResourceAsStream(file));
} catch(Exception e) {
System.out.println("Error: could not load file: " + file);
}
return sprite;
}
public void loadSpriteArray() {
spriteArray = new BufferedImage[wSprite][hSprite];
for(int x = 0; x < wSprite; x++) {
for(int y = 0; y < hSprite; y++) {
spriteArray[x][y] = getSprite(x, y);
}
}
}
public BufferedImage getSpriteSheet() {
return SPRITESHEET;
}
public BufferedImage getSprite(int x, int y) {
return SPRITESHEET.getSubimage(x * w, y * h, w, h);
}
public BufferedImage[] getSpriteArray(int i) {
return spriteArray[i];
}
public BufferedImage[][] getSpriteArray2(int i) {
return spriteArray;
}
public static void drawArray(Graphics2D g, ArrayList<BufferedImage> img, Vector2f pos, int width, int height, int xOffset, int yOffset) {
float x = pos.x;
float y = pos.y;
for(int i = 0; i < img.size(); i++) {
if(img.get(i) != null) {
g.drawImage(img.get(i), (int) x, (int) y, width, height, null);
}
x += xOffset;
y += yOffset;
}
}
public static void drawArray(Graphics2D g, Font f, String word, Vector2f pos, int width, int height, int xOffset, int yOffset) {
float x = pos.x;
float y = pos.y;
for(int i = 0; i < word.length(); i++ ) {
if(word.charAt(i) != 32); // the space
g.drawImage(f.getFont(word.charAt(i)), (int) x, (int) y, width, height, null);
x += xOffset;
y += yOffset;
}
}
}
public class Animation {
private BufferedImage[] frames;
private int currentFrame;
private int numFrames;
private int count;
private int delay;
private int timesPlayed;
public Animation(BufferedImage[] frames) {
timesPlayed = 0;
setFrames(frames);
}
public Animation() {
timesPlayed = 0;
}
public void setFrames(BufferedImage[] frames) {
frames = frames;
currentFrame = 0;
timesPlayed = 0;
delay = 2;
numFrames = frames.length;
}
public void setDelay(int i) { delay = i;}
public void setFrame(int i) { currentFrame = i;}
public void setNumFrames(int i) { numFrames = i;}
public void update() {
if(delay == -1) return;
count++;
if(count == delay) {
currentFrame++;
count = 0;
}
if(currentFrame == numFrames) {
currentFrame = 0;
timesPlayed++;
}
}
public int getDelay() {
return delay;
}
public int getFrame() {
return currentFrame;
}
public int getCount() {
return count;
}
public BufferedImage getImage() {
return frames[currentFrame];
}
public boolean hasPlayedOnce() {
return timesPlayed > 0;
}
public boolean hasPlayed(int i) {
return timesPlayed == i;
}
}
public class Player extends Entity {
public Player(Sprite sprite, Vector2f origin, int size) {
super(sprite, origin, size);
}
public void move() {
if(up) {
dy -= acc;
if(dy < -maxSpeed) {
dy = -maxSpeed;
}
} else {
if(dy < 0) {
dy += deacc;
if(dy > 0) {
dy = 0;
}
}
}
if(down) {
dy += acc;
if(dy < maxSpeed) {
dy = maxSpeed;
}
} else {
if(dy > 0) {
dy -= deacc;
if(dy < 0) {
dy = 0;
}
}
}
if(left) {
dx -= acc;
if(dx < -maxSpeed) {
dy = -maxSpeed;
}
} else {
if(dx < 0) {
dx += deacc;
if(dx > 0) {
dx = 0;
}
}
}
if(right) {
dx += acc;
if(dx > maxSpeed) {
dy = maxSpeed;
}
} else {
if(dx > 0) {
dx -= deacc;
if(dx < 0) {
dx = 0;
}
}
}
}
public void update() {
super.update();
move();
pos.x = dx;
pos.y = dy;
}
#Override
public void render(Graphics2D g) {
g.drawImage(ani.getImage(), (int) (pos.x), (int) (pos.y), size, size, null);
}
public void input(MouseHandler mouse, KeyHandler key) {
if(key.up.down) {
up = true;
} else {
up = false;
}
if(key.down.down) {
down = true;
} else {
down = false;
}
if(key.left.down) {
left = true;
} else {
left = false;
}
if(key.right.down) {
right = true;
} else {
right = false;
}
if(key.attack.down) {
attack = true;
} else {
attack = false;
}
}
}
Here is what is printed:
Loading: entity/linkformatted.png...
Exception in thread "GameThread" java.lang.NullPointerException
at com.zwellis.game.graphics.Animation.getImage(Animation.java:62)
at com.zwellis.game.entity.Player.render(Player.java:82)
at com.zwellis.game.states.PlayState.render(PlayState.java:34)
at com.zwellis.game.states.GameStateManager.render(GameStateManager.java:71)
at com.zwellis.game.GamePanel.render(GamePanel.java:133)
at com.zwellis.game.GamePanel.run(GamePanel.java:90)
at java.base/java.lang.Thread.run(Thread.java:834)
Here is what happens when I made another file to display the image:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageInFrame {
public static void main(String[] args) throws IOException {
String path = "entity/linkformatted.png";
File file = new File(path);
BufferedImage image = ImageIO.read(file);
JLabel label = new JLabel(new ImageIcon(image));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(label);
f.pack();
f.setLocation(200,200);
f.setVisible(true);
}
}
Here is what happens:
Exception in thread "main" javax.imageio.IIOException: Can't read input file!
at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
at ImageInFrame.main(ImageInFrame.java:11)
Here is also the github link
https://github.com/xfyktcl/ZwellisKnight.git

Projectiles in my ArrayList are not changed individually upon collision, how can I fix this?

I am trying to make a game. I want the projectiles (balls) that I shoot to each have their own individual collisions with objects and the margins of the game screen, but right now when one ball collides with the game screen margins, every balls' velocity.x or velocity.y is multiplied by -1 to simulate collision rather than just the individual ball that hit's velocity being modified. (When one ball hits, all balls' velocities are affected). The projectiles are stored in an ArrayList in the GameWorld class and are all given an identical velocity when they are shot. You pick a direction to shoot in, then balls are shot every 0.3s in that direction until all balls are shot.
Here is the code from my Projectiles class:
package com.trimble.gameobjects;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.Vector2;
import com.trimble.gameworld.GameWorld;
public class Projectile {
private Vector2 velocity, acceleration;
private Vector2 position;
private final float RADIUS = 3f;
private boolean active, shot;
private GameWorld world;
private float theta;
public Projectile(float x, GameWorld world) {
this.world = world;
this.position = new Vector2();
this.position.x = x;
this.position.y = world.getGameRect().y - 3;
// hitbox = new Circle(position, 3f);
this.velocity = new Vector2();
this.acceleration = new Vector2(0, 0.5f);
this.active = false;
this.shot = false;
}
public void update(float delta) {
if (active) {
position.add(velocity.cpy().scl(delta));
velocity.add(acceleration.cpy().scl(delta));
// left
if (this.position.x <= 3) {
Gdx.app.log("hit", " left");
this.position.x = 3;
this.velocity.x *= -1;
}
// right
else if (this.position.x >= world.getGameRect().width - 3) {
Gdx.app.log("hit", " right");
this.position.x = world.getGameRect().width - 3;
this.velocity.x *= -1;
}
// top
if (this.position.y < world.getGameRect().y + world.getGameRect().height + 3) {
Gdx.app.log("hit", " top");
this.position.y = world.getGameRect().y + world.getGameRect().height + 3;
this.velocity.y *= -1;
}
// bottom
else if (this.position.y > world.getGameRect().y - 3 && velocity.y > 0) {
Gdx.app.log("hit", " bottom");
if (!this.world.hasTouched()) {
this.world.getBaseCircle().setPositionX(position.x);
this.world.setTouched(true);
}
zeroVelocity();
this.active = false;
this.position = world.getBaseCirclePos();
this.world.addInactive();
}
}
}
public Vector2 getVelocity() {
return velocity;
}
public float getVelocityX() {
return velocity.x;
}
public float getVelocityY() {
return velocity.y;
}
public void setVelocity(Vector2 velocity) {
this.velocity = velocity;
}
public void setVelocityX(float x) {
this.velocity.x = x;
}
public void setVelocityY(float y) {
this.velocity.y = y;
}
public float getTheta() {
return theta;
}
public void setTheta(float theta) {
this.theta = theta;
}
public void zeroVelocity() {
this.velocity.x = 0;
this.velocity.y = 0;
}
public Vector2 getPosition() {
return position;
}
public void setPositionY(float y) {
this.position.y = y;
}
public void setPositionX(float x) {
this.position.x = x;
}
public void setPosition(Vector2 position) {
this.position = position;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public float getR() {
return RADIUS;
}
public boolean wasShot() {
return shot;
}
public void setShot(boolean shot) {
this.shot = shot;
}
}
Here is the code in GameWorld which is called when the player shoots:
public void transitionHasShot() {
if (currentState == GameState.READY) {
currentState = GameState.HASSHOT;
velocity.y = (float) (-165 * Math.sin(theta));
velocity.x = (float) (165 * Math.cos(theta));
baseCircle.setActive(false);
for (Projectile p : projectiles) {
p.setVelocity(velocity);
}
projectiles.get(0).setActive(true);
}
}
Let me know if you need any more info.
I solved the problem by changing the code in transitionHasShot():
change
for (Projectile p : projectiles) {
p.setVelocity(velocity);
}
to:
for (Projectile p : projectiles) {
p.setVelocity(velocity.cpy());
}

Path drawing. in android studio

I am trying to implement path drawing for a herding game.
Currently when I run the game on PC I use the mouse to draw a path for which the herder will move through, but I can not get it to draw a line.
package com.mygdx.herdergame.Sprites;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.Array;
import com.mygdx.herdergame.HerderGame;
import com.mygdx.herdergame.Screens.PlayScreen;
import java.util.ArrayList;
public class Herder extends Sprite implements InputProcessor {
HerderGame game;
public World world;
public Body b2body;
private PlayScreen screen;
//States
private enum State {
RUNNINGRIGHT, RUNNINGLEFT, RUNNINGUP, RUNNINGDOWN, STANDINGRIGHT, STANDINGLEFT, STANDINGUP, STANDINGDOWN
}
private State currentState;
private State previousState;
private float stateTimer;
//Textures
private Animation runningRight;
private Animation runningLeft;
private Animation runningUp;
private Animation runningDown;
private TextureRegion standRight;
private TextureRegion standLeft;
private TextureRegion standUp;
private TextureRegion standDown;
private float destinationX;
private float destinationY;
//Velocity
private static final float MAX_SPEED = 500;
private float speedLimit = 1000;
private Vector2 velocity = new Vector2(0, 0);
private static float ACCURACY = 50;
//Touch Screen
private Vector3 touchpoint = new Vector3();
private Vector2 targetPosition;
private ArrayList<Vector2> herderPath = new ArrayList<Vector2>();
boolean dragging;
boolean followingPath = false;
// death variables
private boolean isInTimedDeathZone;
private float deathTimer;
//this is the constructor.
public Herder(World world, PlayScreen screen) {
super(screen.getAtlas().findRegion("herderRight"));
this.screen = screen;
game = screen.getGame();
this.world = world;
defBody();
setTextures();
currentState = State.STANDINGRIGHT;
previousState = State.STANDINGRIGHT;
stateTimer = 0;
isInTimedDeathZone = false;
deathTimer = 0;
}
public void defBody() {
BodyDef bdef = new BodyDef();
bdef.position.set(500, 500);
bdef.type = BodyDef.BodyType.DynamicBody;
b2body = world.createBody(bdef);
FixtureDef fdef = new FixtureDef();
CircleShape shape = new CircleShape();
shape.setRadius(10);
fdef.shape = shape;
b2body.createFixture(fdef).setUserData(this);
}
public void setTextures() {
int herderUpStartX = game.rm.getChapter(game.getCurrentChapter()).getHerderUp().getStartX();
int herderUpStartY = game.rm.getChapter(game.getCurrentChapter()).getHerderUp().getStartY();
int herderDownStartX = game.rm.getChapter(game.getCurrentChapter()).getHerderDown().getStartX();
int herderDownStartY = game.rm.getChapter(game.getCurrentChapter()).getHerderDown().getStartY();
int herderLeftStartX = game.rm.getChapter(game.getCurrentChapter()).getHerderLeft().getStartX();
int herderLeftStartY = game.rm.getChapter(game.getCurrentChapter()).getHerderLeft().getStartY();
int herderRightStartX = game.rm.getChapter(game.getCurrentChapter()).getHerderRight().getStartX();
int herderRightStartY = game.rm.getChapter(game.getCurrentChapter()).getHerderRight().getStartY();
int numberOfFrame = game.rm.getChapter(game.getCurrentChapter()).getHerderRight().getNumberOfFrame();
int width = game.rm.getChapter(game.getCurrentChapter()).getHerderRight().getWidth();
int height = game.rm.getChapter(game.getCurrentChapter()).getHerderRight().getHeight();
//this enables the sprite to be drawn.
Array<TextureRegion> frames = new Array<TextureRegion>();
for (int i = 0; i < numberOfFrame; i++) {
frames.add(new TextureRegion(getTexture(), herderRightStartX + width * i, herderRightStartY, width, height));
}
runningRight = new Animation(0.1f, frames);
frames.clear();
for (int i = 0; i < numberOfFrame; i++) {
frames.add(new TextureRegion(getTexture(), herderLeftStartX + width * i, herderLeftStartY, width, height));
}
runningLeft = new Animation(0.1f, frames);
frames.clear();
for (int i = 0; i < numberOfFrame; i++) {
frames.add(new TextureRegion(getTexture(), herderDownStartX + width * i, herderDownStartY, width, height));
}
runningDown = new Animation(0.1f, frames);
frames.clear();
for (int i = 0; i < numberOfFrame; i++) {
frames.add(new TextureRegion(getTexture(), herderUpStartX + width * i, herderUpStartY, width, height));
}
runningUp = new Animation(0.1f, frames);
standRight = new TextureRegion(getTexture(), herderRightStartX, herderRightStartY, width, height);
setBounds(0, 0, 32, 32);
setRegion(standRight);
standLeft = new TextureRegion(getTexture(), herderLeftStartX, herderLeftStartY, width, height);
setBounds(0, 0, 32, 32);
setRegion(standLeft);
standUp = new TextureRegion(getTexture(), herderUpStartX, herderUpStartY, width, height);
setBounds(0, 0, 32, 32);
setRegion(standUp);
standDown = new TextureRegion(getTexture(), herderDownStartX, herderDownStartY, width, height);
setBounds(0, 0, 32, 32);
setRegion(standDown);
setSize(32, 32);
}
public TextureRegion getFrame(float dt) {
currentState = getState();
TextureRegion region;
switch (currentState) {
case RUNNINGRIGHT:
region = runningRight.getKeyFrame(stateTimer, true);
break;
case RUNNINGLEFT:
region = runningLeft.getKeyFrame(stateTimer, true);
break;
case RUNNINGUP:
region = runningUp.getKeyFrame(stateTimer, true);
break;
case RUNNINGDOWN:
region = runningDown.getKeyFrame(stateTimer, true);
break;
case STANDINGLEFT:
region = standLeft;
break;
case STANDINGUP:
region = standUp;
break;
case STANDINGDOWN:
region = standDown;
break;
case STANDINGRIGHT:
default:
region = standRight;
break;
}
stateTimer = currentState == previousState ? stateTimer + dt : 0;
previousState = currentState;
return region;
}
public State getState() {
Vector2 direction = b2body.getLinearVelocity();
if (direction.isZero()) {
switch (previousState) {
case RUNNINGUP:
return State.STANDINGUP;
case RUNNINGLEFT:
return State.STANDINGLEFT;
case RUNNINGDOWN:
return State.STANDINGDOWN;
case RUNNINGRIGHT:
return State.STANDINGRIGHT;
default:
return previousState;
}
} else if (direction.x >= 0 && direction.y >= 0) {
if (direction.x > direction.y) {
return State.RUNNINGRIGHT;
} else return State.RUNNINGUP;
} else if (direction.x >= 0 && direction.y <= 0) {
if (direction.x > -direction.y) {
return State.RUNNINGRIGHT;
} else return State.RUNNINGDOWN;
} else if (direction.x <= 0 && direction.y >= 0) {
if (-direction.x > direction.y) {
return State.RUNNINGLEFT;
} else return State.RUNNINGUP;
} else if (direction.x <= 0 && direction.y <= 0) {
if (-direction.x > -direction.y) {
return State.RUNNINGLEFT;
} else return State.RUNNINGDOWN;
} else return currentState = previousState;
}
public void update(float dt) {
if (isXStapable() || isYStapable()) {
stop();
}
if (followingPath) {
if (!herderPath.iterator().hasNext()) {
followingPath = false;
herderPath.clear();
stop();
} else if (targetPosition.dst(b2body.getPosition()) < 1.5) {
targetPosition = herderPath.get(0);
herderPath.remove(0);
velocity = calculateVelocity(b2body.getPosition(), targetPosition);
} else {
velocity = calculateVelocity(b2body.getPosition(), targetPosition);
}
}
b2body.setLinearVelocity(velocity);
setPosition(b2body.getPosition().x - getWidth() / 2, b2body.getPosition().y - getHeight() / 2);
setRegion(getFrame(dt));
if (isInTimedDeathZone) {
deathTimer += dt;
} else {
deathTimer = 0;
}
if (deathTimer > 2f) {
screen.gameOver();
}
}
public void setInTimedDeathZone(boolean b) {
this.isInTimedDeathZone = b;
}
#Override
public boolean keyDown(int keycode) {
switch (keycode) {
case Input.Keys.UP:
velocity.y = speedLimit;
break;
case Input.Keys.DOWN:
velocity.y = -speedLimit;
break;
case Input.Keys.LEFT:
velocity.x = -speedLimit;
break;
case Input.Keys.RIGHT:
velocity.x = speedLimit;
break;
default:
return true;
}
followingPath = false;
return true;
}
#Override
public boolean keyUp(int keycode) {
switch (keycode) {
case Input.Keys.UP:
case Input.Keys.DOWN:
velocity.y = 0;
break;
case Input.Keys.LEFT:
case Input.Keys.RIGHT:
velocity.x = 0;
break;
}
return true;
}
#Override
public boolean keyTyped(char character) {
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
float diffX;
float diffY;
// ignore if its not left mouse button or first touch pointer
if (button != Input.Buttons.LEFT || pointer > 0) return false;
screen.getCamera().unproject(touchpoint.set(screenX, screenY, 0));
//ignore if the first point is not close to the herder
diffX = touchpoint.x - b2body.getPosition().x;
diffY = touchpoint.y - b2body.getPosition().y;
if (diffX > 25 || diffX < -25 || diffY > 25 || diffY < -25) return false;
dragging = true;
herderPath.clear();
targetPosition = b2body.getPosition();
herderPath.add(targetPosition);
return true;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
Vector2 vec2 = new Vector2();
if (!dragging) return false;
screen.getCamera().unproject(touchpoint.set(screenX, screenY, 0));
vec2.set(touchpoint.x, touchpoint.y);
herderPath.add(vec2);
followingPath = true;
return true;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
if (button != Input.Buttons.LEFT || pointer > 0) return false;
screen.getCamera().unproject(touchpoint.set(screenX, screenY, 0));
dragging = false;
return true;
}
private Vector2 calculateVelocity(Vector2 currentPosition, Vector2 targetPosition) {
Vector2 tempTP = new Vector2().set(targetPosition);
return tempTP.sub(currentPosition).nor().scl(speedLimit);
}
public boolean isXValid(int x) {
return b2body.getPosition().x <= x + ACCURACY && b2body.getPosition().x >= x - ACCURACY;
}
public boolean isYValid(int y) {
return b2body.getPosition().y <= y + ACCURACY && b2body.getPosition().y >= y - ACCURACY;
}
public boolean isXStapable() {
return isXValid((int) destinationX);
}
public boolean isYStapable() {
return isYValid((int) destinationY);
}
public void stop() {
velocity.set(0, 0);
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolled(int amount) {
return false;
}
public void setSpeedLimit(float multiplier) {
if (speedLimit > MAX_SPEED) {
this.speedLimit = MAX_SPEED;
} else {
this.speedLimit = multiplier;
}
}
}

StackOverflowError while saving and loading my object in android

I'm writing an android program and i just ran into a problem.
My program serves to create graphs, run some specific algorithms on them (Dijsktra, BelmanFord, etc.), save the graphs to SD Card and loading them back.
The problem: If i save a little bigger, more complex graph i get a stackoverflow error..
Serialization:
public void createExternalStoragePublicGraph(String filename) {
File dir = Environment.getExternalStoragePublicDirectory("grapher");
try {
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, filename);
FileOutputStream fileOutputStream = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(graphDrawerView.getGraph());
objectOutputStream.close();
} catch (IOException e) {
Log.w("ExternalStorage", "Error Writing" + filename, e);
}
}
Deserialization:
public Graph loadExternalStoragePublicGraph(String filename) {
File file = new File(Environment.getExternalStoragePublicDirectory("grapher"), filename);
Graph graph = null;
try {
FileInputStream fint = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fint);
graph = (Graph) ois.readObject();
ois.close();
} catch (Exception e) {
Log.e("Deserialization error:", e.getMessage());
e.printStackTrace();
}
return graph;
}
Graph class:
package com.cslqaai.grapher;
import android.util.Log;
import java.io.Serializable;
import java.util.LinkedList;
public class Graph implements Serializable {
private String name;
private boolean directed = false;
private boolean weighted = false;
private LinkedList<Vertex> vertexes = new LinkedList<Vertex>();
private LinkedList<Edge> edges = new LinkedList<Edge>();
// --------------------------------------------------------------------------------------------------------------------------------------
public Graph(boolean weighted, boolean directed) {
this.directed = directed;
this.weighted = weighted;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public void add(AbstractGraphObject ago) {
if (ago instanceof Vertex) {
this.vertexes.add((Vertex) ago);
} else if (ago instanceof Edge) {
this.edges.add((Edge) ago);
} else {
}
}
// --------------------------------------------------------------------------------------------------------------------------------------
public boolean isWeighted() {
return this.weighted;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public boolean isDirected() {
return this.directed;
}
// --------------------------------------------------------------------------------------------------------------------------------------\
public LinkedList<Edge> getEdges() {
return this.edges;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public LinkedList<Vertex> getVertexes() {
return this.vertexes;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public void reset() {
for (int i = 0; i < this.edges.size(); i++) {
this.edges.get(i).setColorToDefault();
}
}
// --------------------------------------------------------------------------------------------------------------------------------------
void remove(AbstractGraphObject ago) {
if (ago instanceof Vertex) {
Log.d("Graph", "Remove Vertex from graph");
this.vertexes.remove((Vertex) ago);
} else if (ago instanceof Edge) {
Log.d("Graph", "Remove Edge to graph");
this.edges.remove((Edge) ago);
}
}
// --------------------------------------------------------------------------------------------------------------------------------------
public void setWeighted(boolean weighted) {
this.weighted = weighted;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public void setDirected(boolean directed) {
this.directed = directed;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public String getName() {
return this.name;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public void setName(String name) {
this.name = name;
}
}
// ----------------------------------------------------------------------------------------------------------------------------------------
Vertex class:
package com.cslqaai.grapher;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
public class Vertex extends AbstractGraphObject {
public static final int RADIUS_SIZE = 20;
public static final int SURROUNDING_RADIUS_SIZE = 30;
private static Layer defaultVertexLayer = AbstractGraphObject.defaultLayer;
private static int no = 0;
private static Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private static Paint paintColored = new Paint(Paint.ANTI_ALIAS_FLAG);
private static Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private static Paint textBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final int id;
private String name = null;
private Coord coord;
private Coord cachedCoord;
private ArrayList<Edge> edges = new ArrayList<Edge>();
private boolean colored = false;
// --------------------------------------------------------------------------------------------------------------------------------------
static {
Vertex.paint.setColor(0xFF0FF5F5);
Vertex.paintColored.setColor(Color.RED);
Vertex.textPaint.setStyle(Paint.Style.FILL);
Vertex.textPaint.setColor(Color.BLACK);
Vertex.textPaint.setTextAlign(Paint.Align.CENTER);
Vertex.textPaint.setTextSize(20);
Vertex.textPaint.setTypeface(Typeface.create("Helvetica", Typeface.BOLD));
Vertex.textBgPaint.setStyle(Paint.Style.FILL);
Vertex.textBgPaint.setColor(0xFF0FF5F5);
}
// --------------------------------------------------------------------------------------------------------------------------------------
public Vertex(Coord coord) {
super(Vertex.defaultVertexLayer);
this.id = Vertex.no++;
this.coord = coord;
this.recalculate();
}
// --------------------------------------------------------------------------------------------------------------------------------------
public Vertex(int x, int y) {
this(new Coord(x, y));
}
// --------------------------------------------------------------------------------------------------------------------------------------
#Override
public void recalculate() {
this.cachedCoord = new Coord(Math.round((Vertex.baseX + this.coord.getX()) * Vertex.scaleFactor), Math.round((Vertex.baseY + this.coord.getY()) * Vertex.scaleFactor));
this.onScreen = this.cachedCoord.getX() + Vertex.RADIUS_SIZE > 0 && this.cachedCoord.getY() + Vertex.RADIUS_SIZE > 0
&& this.cachedCoord.getX() - Vertex.RADIUS_SIZE < Vertex.screenWidth && this.cachedCoord.getY() - Vertex.RADIUS_SIZE < this.cachedCoord.getY();
}
// --------------------------------------------------------------------------------------------------------------------------------------
public Coord getCoord() {
return this.coord;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public Coord getCachedCoord() {
return this.cachedCoord;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public int getRadiusSize() {
return Vertex.RADIUS_SIZE;
}
// --------------------------------------------------------------------------------------------------------------------------------------
#Override
public void draw(Canvas canvas) {
this.recalculate();
if (!this.onScreen) {
return;
}
canvas.drawCircle(this.cachedCoord.getX(), this.cachedCoord.getY(), Vertex.RADIUS_SIZE * Vertex.scaleFactor, Vertex.paint);
if (this.name != null) {
float width = Vertex.textPaint.measureText(this.name) + 10;
float height = Vertex.textPaint.getTextSize() + 5;
canvas.drawRect(this.cachedCoord.getX() - width / 2, this.cachedCoord.getY() - height / 2, this.cachedCoord.getX() + width / 2, this.cachedCoord.getY() + height / 2, Vertex.textBgPaint);
canvas.drawText(this.name, this.cachedCoord.getX(), this.cachedCoord.getY() + height * 0.25f, Vertex.textPaint);
}
}
// --------------------------------------------------------------------------------------------------------------------------------------
private boolean searchingCoordOn(float radius, float pX, float pY) {
return this.onScreen && ((Math.pow(pX - this.cachedCoord.getX(), 2) + Math.pow(pY - this.cachedCoord.getY(), 2)) < (Math.pow(radius * Vertex.scaleFactor, 2)));
}
// --------------------------------------------------------------------------------------------------------------------------------------
public boolean isOnCoord(float pX, float pY) {
return this.searchingCoordOn(Vertex.RADIUS_SIZE, pX, pY);
}
// --------------------------------------------------------------------------------------------------------------------------------------
public boolean isInCoordSurroundings(float pX, float pY) {
return this.searchingCoordOn(Vertex.SURROUNDING_RADIUS_SIZE, pX, pY);
}
// --------------------------------------------------------------------------------------------------------------------------------------
public void addEdge(Edge edge) {
if (!this.edges.contains(edge)) {
this.edges.add(edge);
}
}
// --------------------------------------------------------------------------------------------------------------------------------------
public ArrayList<Edge> getEdges() {
return this.edges;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public void removeEdge(Edge edge) {
if (this.edges.contains(edge)) {
this.edges.remove(edge);
}
}
// --------------------------------------------------------------------------------------------------------------------------------------
public boolean hasEdge(Edge edge) {
return this.edges.contains(edge);
}
// --------------------------------------------------------------------------------------------------------------------------------------
public static void setDefaultLayer(Layer layer) {
Vertex.defaultVertexLayer = layer;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public static Layer getDefaultLayer() {
return Vertex.defaultVertexLayer;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public static void remove(Vertex vertex) {
Iterator<Edge> edges = vertex.getEdges().iterator();
while (edges.hasNext()) {
Edge e = edges.next();
edges.remove();
Edge.remove(e);
}
Vertex.defaultVertexLayer.remove(vertex);
if (Vertex.graph != null) {
Vertex.graph.remove(vertex);
}
}
// --------------------------------------------------------------------------------------------------------------------------------------
public boolean hasName() {
return this.name != null;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public void setName(String name) {
this.name = name;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public String getName() {
return this.name;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public int getId() {
return this.id;
}
// --------------------------------------------------------------------------------------------------------------------------------------
}
Edge class:
package com.cslqaai.grapher;
import android.graphics.*;
import java.util.ArrayList;
import java.util.LinkedList;
public class Edge extends AbstractGraphObject {
public static final float STROKE_WIDTH = 5f;
public static final float SENSOR_WIDTH = 50f;
public static final float SURROUNDING_SENSOR_WIDTH = 15f;
public static final float TRIANGLE_SIZE = 8f;
private static Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private static Paint paintColored = new Paint(Paint.ANTI_ALIAS_FLAG);
private static Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private static Paint textBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private static Layer defaultEdgeLayer = AbstractGraphObject.defaultLayer;
private static int no = 0;
private final int id;
private int weight = 1;
private Coord cachedSourceCoord;
private Coord cachedTargetCoord;
private Vertex sourceVertex;
private Vertex targetVertex;
private Coord weightCoord;
private boolean colored = false;
// --------------------------------------------------------------------------------------------------------------------------------------
static {
Edge.paint.setColor(0xFFFFFFFF);
Edge.paint.setStrokeWidth(Edge.STROKE_WIDTH * Edge.scaleFactor);
Edge.paint.setStrokeCap(Paint.Cap.ROUND);
Edge.paint.setStyle(Paint.Style.FILL_AND_STROKE);
Edge.paintColored.setColor(0xFFFF0000);
Edge.paintColored.setStrokeWidth(Edge.STROKE_WIDTH * Edge.scaleFactor);
Edge.paintColored.setStrokeCap(Paint.Cap.ROUND);
Edge.paintColored.setStyle(Paint.Style.FILL_AND_STROKE);
Edge.textPaint.setStyle(Paint.Style.FILL);
Edge.textPaint.setColor(Color.BLACK);
Edge.textPaint.setTextAlign(Paint.Align.CENTER);
Edge.textPaint.setTextSize(20);
Edge.textPaint.setTypeface(Typeface.create("Helvetica", Typeface.BOLD));
Edge.textBgPaint.setStyle(Paint.Style.FILL);
Edge.textBgPaint.setColor(Color.WHITE);
}
// --------------------------------------------------------------------------------------------------------------------------------------
public Edge(Vertex sourceVertex, Vertex targetVertex) {
super(Edge.defaultEdgeLayer);
this.id = Edge.no++;
this.sourceVertex = sourceVertex;
this.targetVertex = targetVertex;
this.sourceVertex.addEdge(this);
this.targetVertex.addEdge(this);
this.recalculate();
}
// --------------------------------------------------------------------------------------------------------------------------------------
public void recalculate() {
this.cachedSourceCoord = new Coord(Math.round((Edge.baseX + this.sourceVertex.getCoord().getX()) * Edge.scaleFactor), Math.round((Edge.baseY + this.sourceVertex.getCoord().getY()) * Edge.scaleFactor));
this.cachedTargetCoord = new Coord(Math.round((Edge.baseX + this.targetVertex.getCoord().getX()) * Edge.scaleFactor), Math.round((Edge.baseY + this.targetVertex.getCoord().getY()) * Edge.scaleFactor));
Line line = new Line(this.cachedSourceCoord, this.cachedTargetCoord);
this.weightCoord = line.getMiddle();
this.onScreen = Edge.screenBottomLine.hasIntersection(line)
|| Edge.screenLeftLine.hasIntersection(line)
|| Edge.screenRightLine.hasIntersection(line)
|| Edge.screenTopLine.hasIntersection(line)
|| this.cachedSourceCoord.getX() > 0 && this.cachedSourceCoord.getX() < Edge.screenWidth && this.cachedSourceCoord.getY() > 0 && this.cachedSourceCoord.getY() < Edge.screenHeight
|| this.cachedTargetCoord.getX() > 0 && this.cachedTargetCoord.getX() < Edge.screenWidth && this.cachedTargetCoord.getY() > 0 && this.cachedTargetCoord.getY() < Edge.screenHeight;
}
// --------------------------------------------------------------------------------------------------------------------------------------
#Override
public void draw(Canvas canvas) {
this.recalculate();
if (!this.onScreen) {
return;
}
canvas.drawLine(this.cachedSourceCoord.getX(), this.cachedSourceCoord.getY(), this.cachedTargetCoord.getX(), this.cachedTargetCoord.getY(), this.colored ? Edge.paintColored : Edge.paint);
if (Edge.graph != null && Edge.graph.isDirected()) {
Line line = new Line(this.cachedSourceCoord, this.cachedTargetCoord);
Coord v = line.getVector();
float t = (float) ((Vertex.RADIUS_SIZE + 5) / Math.sqrt(Math.pow(v.getX(), 2) + Math.pow(v.getY(), 2)));
Coord t1 = new Coord((int) (this.cachedTargetCoord.getX() - t * v.getX()), (int) (this.cachedTargetCoord.getY() - t * v.getY()));
if (!line.isOnLine(t1)) {
t1 = new Coord((int) (this.cachedTargetCoord.getX() + t * v.getX()), (int) (this.cachedTargetCoord.getY() + t * v.getY()));
}
t = (float) ((Vertex.RADIUS_SIZE + 5 + Edge.TRIANGLE_SIZE) / Math.sqrt(Math.pow(v.getX(), 2) + Math.pow(v.getY(), 2)));
Coord p = new Coord((int) (this.cachedTargetCoord.getX() - t * v.getX()), (int) (this.cachedTargetCoord.getY() - t * v.getY()));
if (!line.isOnLine(p)) {
p = new Coord((int) (this.cachedTargetCoord.getX() + t * v.getX()), (int) (this.cachedTargetCoord.getY() + t * v.getY()));
}
v = line.getNormalVector().getVector();
t = (float) ((Edge.TRIANGLE_SIZE) / Math.sqrt(Math.pow(v.getX(), 2) + Math.pow(v.getY(), 2)));
Coord t2 = new Coord((int) (p.getX() - t * v.getX()), (int) (p.getY() - t * v.getY()));
Coord t3 = new Coord((int) (p.getX() + t * v.getX()), (int) (p.getY() + t * v.getY()));
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(t1.getX(), t1.getY());
path.lineTo(t2.getX(), t2.getY());
path.lineTo(t3.getX(), t3.getY());
path.lineTo(t1.getX(), t1.getY());
path.close();
canvas.drawPath(path, Edge.paint);
}
if (Edge.graph != null && Edge.graph.isWeighted()) {
float width = Edge.textPaint.measureText(Integer.toString(this.weight)) + 10;
float height = Edge.textPaint.getTextSize() + 5;
canvas.drawRect(this.weightCoord.getX() - width / 2, this.weightCoord.getY() - height / 2, this.weightCoord.getX() + width / 2, this.weightCoord.getY() + height / 2, Edge.textBgPaint);
canvas.drawText(Integer.toString(this.weight), this.weightCoord.getX(), this.weightCoord.getY() + height * 0.25f, Edge.textPaint);
}
}
// --------------------------------------------------------------------------------------------------------------------------------------
private boolean searchingCoordOn(float distance, float pX, float pY) {
Coord p = new Coord((int) pX, (int) pY);
Coord v = (new Line(this.cachedSourceCoord, this.cachedTargetCoord)).getNormalVector().getVector();
float t = (float) (distance / Math.sqrt(Math.pow(v.getX(), 2) + Math.pow(v.getY(), 2)));
Coord c1 = new Coord((int) (this.cachedSourceCoord.getX() - t * v.getX()), (int) (this.cachedSourceCoord.getY() - t * v.getY()));
Coord c2 = new Coord((int) (this.cachedSourceCoord.getX() + t * v.getX()), (int) (this.cachedSourceCoord.getY() + t * v.getY()));
Coord c3 = new Coord((int) (this.cachedTargetCoord.getX() - t * v.getX()), (int) (this.cachedTargetCoord.getY() - t * v.getY()));
Coord v1 = new Coord(c2.getX() - c1.getX(), c2.getY() - c1.getY());
Coord v2 = new Coord(c3.getX() - c1.getX(), c3.getY() - c1.getY());
v = Coord.minus(p, c1);
return this.onScreen
&& 0 <= Coord.dotProduct(v, v1) && Coord.dotProduct(v, v1) <= Coord.dotProduct(v1, v1)
&& 0 <= Coord.dotProduct(v, v2) && Coord.dotProduct(v, v2) <= Coord.dotProduct(v2, v2);
}
// --------------------------------------------------------------------------------------------------------------------------------------
public boolean isOnCoord(float pX, float pY) {
return this.searchingCoordOn(Edge.SENSOR_WIDTH / 2, pX, pY);
}
// --------------------------------------------------------------------------------------------------------------------------------------
public boolean isInCoordSurroundings(float pX, float pY) {
return this.searchingCoordOn(Edge.SURROUNDING_SENSOR_WIDTH / 2, pX, pY);
}
// --------------------------------------------------------------------------------------------------------------------------------------
public Vertex getSourceVertex() {
return this.sourceVertex;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public Vertex getTargetVertex() {
return this.targetVertex;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public static void setDefaultLayer(Layer layer) {
Edge.defaultEdgeLayer = layer;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public static Layer getDefaultLayer() {
return Edge.defaultEdgeLayer;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public static void remove(Edge edge) {
edge.getSourceVertex().removeEdge(edge);
edge.getTargetVertex().removeEdge(edge);
Edge.defaultEdgeLayer.remove(edge);
if (Edge.graph != null) {
Edge.graph.remove(edge);
}
}
// --------------------------------------------------------------------------------------------------------------------------------------
public void setWeight(int weight) {
this.weight = weight;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public int getWeight() {
return this.weight;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public int getId() {
return this.id;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public void setColored() {
this.colored = true;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public void setColorToDefault() {
this.colored = false;
}
// --------------------------------------------------------------------------------------------------------------------------------------
public static ArrayList<Edge> getEdgesBetween(Vertex v1, Vertex v2) {
ArrayList<Edge> edges = v1.getEdges();
ArrayList<Edge> edgesRet = new ArrayList<Edge>();
for (Edge edge : edges) {
if (v2.hasEdge(edge)) {
edgesRet.add(edge);
}
}
return edges;
}
// --------------------------------------------------------------------------------------------------------------------------------------
}
The reason for this is that the "normal" serialization would for each entry recursively invoke another writeObject(e), and for long lists this would give a StackOverflowError. The iterative serialization avoids this.
I found this on stackoverflow. I think my problem is related to my long LinkedLists..
Any ideas, advices how to properly serialize and deserialize my Graph object?
Thank You In Advance!
As a fast fix, you could try substuting the LinkedList List implemetnations with ArrayLists. You didn't give enough details (the exact exception and the implementations of the vertexes and edges would be helpful), but what you quoted might be right: we run out of memory because of the recursive calls. I didn't try, but the ArrayList default Java serialization would avoid this issue.
For a really good solution, the serialization methods of the graph objects could be re-implemented, or a tested and more memory efficient library could be used (eg. kryo).
This question would also be helpful.
Try runnning your program with more RAM. StackOverFlowError means, that the stack is filled and cant take any other method. What you could also do, is run the deserialization in another Thread; They have a seperate stack. There are several ways to do so, I recommend using the classes from java.util.concurrent.

Categories

Resources