Setting image instead of java standard ellipse Java Processing - java

I'm trying to create a solar system using processing but I'm stuck at trying to set an image instead of using the java standard elipse image.
I started this at school and it consisted of an ellipse rotating around another ellipse.
package processing;
import processing.core.PApplet;
import processing.core.PImage;
public class SolarSystem extends PApplet{
PImage background;
Pianets earth;
public void settings() {
size(650,500);
}
public void setup() {
background = loadImage("C:\\background\\bg.jpg");
earth = new Pianets(this, width/2,height/2,40, 200, 0);
}
public void draw() {
background(background);
earth.showEarth();
earth.rotateEarth(0.007f);
}
public static void main(String[] args) {
PApplet.main("processing.SolarSystem");
}
}
Planets class
package processing;
import processing.core.PApplet;
public class Pianets {
PApplet vis;
float x0,y0; //centre
float diam;
float r; //distance from the centre
float alpha; //rotation angle
public Pianeti(PApplet applet, float x, float y, float diam,float r, float alpha){
vis = applet;
this.x0=x;
this.y0=y;
this.diam=diam;
this.r=r;
this.alpha=alpha;
}
void rotateEarth(float deltaAlpha){
alpha +=deltaAlpha;
}
void showEarth(){
//drawing the body of object at the centre
vis.ellipse(x0, y0, diam, diam);
float x = x0 + r*vis.cos(alpha);
float y = y0 + r*vis.sin(alpha);
vis.ellipse(x,y,diam,diam);
}
I created two images on paint that are the earth and the sun but I don't know how to set the image up.

Questions like this are best answered by looking at the Processing reference. There's an Image section that lists a loadImage() function for loading an image file, and an image() function for drawing it. Please read those.
You should also get into the habit of breaking your problem down into smaller pieces. For example, instead of posting your whole project (which has nothing to do with loading images right now), try to create a smaller example program that just shows a single image. Get that working perfectly before moving on. Then if you're confused about something, you can post a MCVE along with a specific technical question.
Shameless self-promotion: I wrote a tutorial on images in Processing available here.

Related

Java - Slick 2D - Placing text (or any graphics) on a rectangle (or any Shape)

I am making an RTS game using Slick 2D. I have a building class and it contains an int called resources. I want the resources variable to become a string and be rendered onto the center of my building (which is just supposed to be a rectangle).
Here's my building class:
package test;
import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.geom.Rectangle;
public class BaseBuilding extends Rectangle{
private int resources;
private Graphics g;
public BaseBuilding(float x, float y, float width, float height) {
super(x, y, width, height);
resources = 0;
g = new Graphics();
} // end constructor
public void render(){
g.drawString("bro wat", resources, resources);
g.setColor(Color.gray);
g.fill(this);
g.drawString(Integer.toString(resources), this.width/2, this.height/2);
} // end update
public int getResources(){
return resources;
} // end getResources
public void addResources(int mulla){
resources += mulla;
if (resources < 0)
resources = 0;
} // end addResources
public void createBasicUnit(){
// create a BasicUnit object in a randomly, valid position close to this object
// TODO
} // end createBasicUnit
} // end class def
So far all my states are working and i got the rectangle to appear appropriately. My g.drawString(str, float, float) code with correct parameters will work on my GameState class(not shown) in its render function, but it gives me this error in my BaseBuilding class:
java.lang.NullPointerException
at org.newdawn.slick.Graphics.drawString(Graphics.java:1366)
at test.BaseBuilding.render(BaseBuilding.java:19)
at test.GameState.render(GameState.java:34)
at org.newdawn.slick.state.StateBasedGame.render(StateBasedGame.java:199)
at org.newdawn.slick.GameContainer.updateAndRender(GameContainer.java:688)
at org.newdawn.slick.AppGameContainer.gameLoop(AppGameContainer.java:411)
at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:321)
at test.StateBaseGame.main(StateBaseGame.java:22)
Sat Apr 18 03:18:55 EDT 2015 ERROR:Game.render() failure - check the game code.
org.newdawn.slick.SlickException: Game.render() failure - check the game code.
at org.newdawn.slick.GameContainer.updateAndRender(GameContainer.java:691)
at org.newdawn.slick.AppGameContainer.gameLoop(AppGameContainer.java:411)
at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:321)
at test.StateBaseGame.main(StateBaseGame.java:22)
So i dug around and found out it's this line that's causing me problems:
g.drawString(Integer.toString(resources), this.width/2, this.height/2);
Couldn't find it on the internet; help if you can please thanks.
After taking a look at the Slick source code, your problem comes from the font variable inside the Graphics class which is null.
You are instantiating Graphics with the default constructor which does not provide a default value for the font variable. And the other one, as the doc says, only the container should be instantiate Graphics.
So, you should never instantiate Graphics, instead just retrieve it from the GameContainer (getGraphics) which is everywhere, or you can also get g from the render method of your game class (Game, BasicGame, BasicGameState, StateBasedGame, depending on what you use...).
To keep it simple, just pass your Graphics object through your render method:
public void render(Graphics g){
g.drawString("bro wat", resources, resources);
g.setColor(Color.gray);
g.fill(this);
g.drawString(Integer.toString(resources), this.width/2, this.height/2);
} // end update
And inside your Game:
render(GameContainer container, Graphics g) {
myBaseBuilding.render(g);
}

Sprite resize libGDX

I have a sprite, which I draw with:
sprite.draw(spriteBatch);
This works....
I have two spites showing the same, but with different resolution...
Let's say x1 = h:100px, x2= h:200px
In the very wrapper class of the sprite I have a method like this:
public static void setSclae(float newScale, Sprite sprite) {
// sprite.scale(newScale - sprite.getScaleX());
sprite.setScale(newScale);
}
(I tried both, both didn't work) Documentation: http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/graphics/g2d/Sprite.html#setScale(float)
On creation of the wrapper class I call the function like this:
setScale(setSide/(setWidth ? this.sprite.getBoundingRectangle().width : this.sprite.getBoundingRectangle().height));
setWidth => boolean (Do you want to set the height or the width??)
this. sprite is a sprite. Origin #(0,0)
The problem is: I want to set the height, no matter which sprite comes in, to 50px...
For x1: setScale(50/100) -> 0.5f
For x2: setScale(50/200) -> 0.25f
Why the hell does this piese of code not work??
Thanks for helping out
Yours,
Florian
PS: Here the constructor of the wrapper class:
public Drawable(Sprite sprite, Vector2 position, Anchor anchor, float setSide, boolean setWidth, boolean flipH, boolean flipV) {
this.sprite = new Sprite(sprite);
this.sprite.setOrigin(0, 0);
setPosition(anchor, position.x, position.y);
setScale(setSide / (setWidth ? this.sprite.getBoundingRectangle().width : this.sprite.getBoundingRectangle().height));
this.sprite.flip(flipV, flipH);
}
I will answer it myself. How I solved it? I implemented my own "Sprites" class, using TexTureRegion. You might not need everything. Pastebin: http://pastebin.com/1Y25HFBm
The IGameObject interface folows. [You do not need the IIntersect interface...
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public interface IGameObject {
public static enum Anchor {TopLeft, MiddleLeft, LowLeft, TopMiddle, MiddleMiddle, LowMiddle, TopRight, MiddleRight, LowRight}
public void Update(GameTime.GameTimeArgs gameTimeArgs);
public void Draw(SpriteBatch spriteBatch);
public void setPosition(Anchor a, float x, float y);
public void setScale(float newScale);
public String toString();
}
Hope that helps :D
Yours,
Florian

Using rectangles to simulate straight line motion of an object

I am relatively new to Java and have been trying to simulate the motion of an object (say a car) on a straight path.
I want my object to move in steps in the output, instead of appearing just at the last point of the line.
I have used 2 classes :Veh.java - the vehicle object and SimuFrame.java - to create the simulation environment.
I have referred to some online tutorials for ideas: http://www.newthinktank.com/2012/07/java-video-tutorial-52/ (This simulates the asteroids game. Howeer I want my object to move in a straight line instead of in a random direction)
Please help me understand where I am wrong and what to do next..
Thanks a lot.
Here's my code:
import java.awt.*;
import java.awt.event.*;
public class Veh extends Rectangle{
int uLeftX, uLeftY; //upper LH Position for Rectangle
static int height = 20;
static int width = 20;
int[] pathCoords=new int[1000];
int startPosY; // start position of the objet - anywhere on the left bounday of the frame.
int goalPosY; // end position of the objet - anywhere on the right boundary of the frame.
//Constructor to Create a new Veh
public Veh(int startPosY,int goalPosY){
//Create a new rectangle vehicle from super class constructor
super(0, startPosY, height, width);
this.startPosY=startPosY;
this.goalPosY=goalPosY;
this.pathCoords = Pathmove();
}
//Calculating the 1000 points on the line joining (0,startPosY) and (goalPosY,999)
int[] Pathmove(){
//Slope calculation
float s=(float)(this.goalPosY-this.startPosY)/999;
pathCoords[0]=this.startPosY;
System.out.println("First xy pair is: 0," +this.pathCoords[0]);
for(int m=1; m<1000; m++){
pathCoords[m]= (int)(m*s)-(int)((m-1)*s)+ pathCoords[m-1];
}
return pathCoords;
}
//Function to move the Reactangular object along the line using the Y coordinate values from Pathmove()
void move(){
int[] a = (int[])this.pathCoords.clone();
for (int c=0; c<a.length;c++){
this.setLocation(c,a[c]);
}
}
}
This is the code for creating the simulation environment.
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class SimuFrame extends JFrame{
public static int frameWidth=1000;
public static int frameHeight=1000;
public static void main(String[] args){
new SimuFrame();
}
public SimuFrame(){
this.setSize(frameWidth,frameHeight);
this.setTitle("Path Planning Results");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SimuObject SO=new SimuObject();
this.add(SO);
// Used to execute code after a given delay
// The attribute is corePoolSize - the number of threads to keep in
// the pool, even if they are idle
ScheduledThreadPoolExecutor executor= new ScheduledThreadPoolExecutor(5);
executor.scheduleAtFixedRate(new RepaintTheFrame(this), 0L, 20L, TimeUnit.MILLISECONDS);
this.setVisible(true);
}
}
// Class implements the runnable interface
// By creating this thread I want to continually redraw the screen
// while other code continues to execute
class RepaintTheFrame implements Runnable{
SimuFrame theFrame;
public RepaintTheFrame(SimuFrame theFrame){
}
#Override
public void run() {
theFrame.repaint();
}
}
class SimuObject extends JComponent{
//Holds every Veh created
public ArrayList<Veh> vehs=new ArrayList<Veh>();
public SimuObject(){
int startPosY = (int)(Math.random()*999);
int goalPosY = (int)(Math.random()*999);
vehs.add(new Veh(startPosY,goalPosY));
}
public void paint(Graphics g){
// Allows me to make many settings changes in regards to graphics
Graphics2D graphicSettings = (Graphics2D)g;
// Draw a background that is as big as the Simu board
graphicSettings.setColor(Color.WHITE);
graphicSettings.fillRect(0, 0, getWidth(), getHeight());
// Set rendering rules
graphicSettings.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Set the drawing color to red
graphicSettings.setPaint( Color.RED);
// Cycle through all of the Rock objects
for(Veh veh : vehs){
// Move the vehicle
veh.move();
graphicSettings.draw(veh);
}
}
}
You have a number of problems in your code:
You have a (swallowed) NullPointerException (NPE) in RepaintTheFrame.run(), which causes ScheduledThreadPoolExecutor.scheduleAtFixedRate() to run only once, per scheduleAtFixedRate()'s javadoc.
You are moving your car in JComponent.paint().
In any graphical framework, the repaint will be called automatically by the framework, usually on an OS event, e.g. moving the window, moving the mouse over the window, etc.
Your paint() method should only draw. It should not modify your domain model.
Your move() method always ends up with the vehicle at the end. That's probably not your intent. You probably want your move() method to merely increment the car's position.
Moving from a start value to an end value in steps is called interpolation. You want linear interpolation specifically here. Its one of the easiest to grasp.
This page will be of great assistance to you.
Without getting fancy with interpolation, you could just change your move routine like so:
int index =0;
void move(){
//int[] a = (int[])this.pathCoords.clone();
if(index<this.pathCoords.length)
this.setLocation(c,pathCoords[index]);
index+=1;
}
Not sure why you were cloning the array there. It probably isn't necessary.

Jmonkey engine 3.0 Drawing points

How can I draw a 3D-point (or point sprite) in 3D space?
There is no documentation for drawing a point in JMonkey Engine site or anywhere else. Just a single point. Then updating the coordinates. No color, just a dot in 3D space.
A point (as opposed to a sphere) can be created using a mesh in which you directly set its buffers (or technically buffer; since a points mesh doesn't require an index buffer as other more complex meshes require. See How can I draw a straight line in the JMonkey Engine library). Mesh creation is documented here.
An example of creating points in 3D space using a mesh is below:
import com.jme3.app.SimpleApplication;
import com.jme3.material.Material;
import com.jme3.math.*;
import com.jme3.renderer.RenderManager;
import com.jme3.scene.*;
import com.jme3.util.BufferUtils;
public class Main extends SimpleApplication {
public static void main(String[] args) {
Main app = new Main();
app.start();
}
#Override
public void simpleInitApp() {
Vector3f[] lineVerticies=new Vector3f[5];
lineVerticies[0]=new Vector3f(2,0,0);
lineVerticies[1]=new Vector3f(-1,0,1);
lineVerticies[2]=new Vector3f(0,1,1);
lineVerticies[3]=new Vector3f(1,1,1);
lineVerticies[4]=new Vector3f(1,4,0);
plotPoints(lineVerticies,ColorRGBA.White);
}
public void plotPoints(Vector3f[] lineVerticies, ColorRGBA pointColor){
Mesh mesh = new Mesh();
mesh.setMode(Mesh.Mode.Points);
mesh.setBuffer(VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer(lineVerticies));
mesh.updateBound();
mesh.updateCounts();
Geometry geo=new Geometry("line",mesh);
Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", pointColor);
geo.setMaterial(mat);
rootNode.attachChild(geo);
}
#Override
public void simpleUpdate(float tpf) {
//TODO: add update code
}
#Override
public void simpleRender(RenderManager rm) {
//TODO: add render code
}
}
This will create the points within pointVerticies as shown below
Later if you need to update infomation in a buffer you can do so using:
VertexBuffer posBuffer = mesh.getBuffer(Type.Position);
posBuffer.updateData(BufferUtils.createFloatBuffer(newData));
posBuffer.setUpdateNeeded();
mesh.updateCounts();
mesh.updateBound();
Or (much more efficiently) you can just attach your geometry to a node and move that (depending on your usage case).
Notes
In its most basic state the Vertex buffer expects x1,y1,z1,x2,y2,z2,x3.... etc with no demarcation between where one vertex ends and the other begins. So the following would enter 3 vertices into the buffer; (1.1,1.2,1.3), (2.1,2.2,2.3) and (3.1,3.2,3.3)
m.setBuffer(VertexBuffer.Type.Position, 3, new float[]{1.1,1.2,1.3,2.1,2.2,2.3,3.1,3.2,3.3});
However the createFloatBuffer() method converts from an array of Vector3f into this form.
Also; its often possible to 'get away with' not calling mesh.updateBound();, however without it objects may be culled because the graphics card believes them to be off screen when actually they are visible

Java custom Paint implementation performance issue

I'm using Java to create a game, and I'm using TexturePaint to texture areas in the background. Performance is fine using java.awt.TexturePaint, however, I want to have areas having an inherent rotation, so I tried implementing a custom Paint called OrientedTexturePaint:
public class OrientableTexturePaint implements Paint {
private TexturePaint texture;
private float orientation;
public OrientableTexturePaint(TexturePaint paint, float orientation)
{
texture = paint;
this.orientation = HelperMethods.clampRadians((float)Math.toRadians(orientation));
}
public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds, AffineTransform xform, RenderingHints hints)
{
AffineTransform newTransform = (AffineTransform)xform.clone();
newTransform.rotate(orientation);
return texture.createContext(cm, deviceBounds, userBounds, newTransform, hints);
}
public int getTransparency()
{
return texture.getTransparency();
}
}
Only problem is, there's a huge performance hit: the frame rate drops from a comfortable (capped) 60fps to about 3fps. Furthermore, if I implement this as a pure wrapper to TexturePaint - without creating the new transform, simply passing the arguments to TexturePaint's methods and returning what TexturePaint returns, I get the same result.
i.e.:
public class MyTexturePaint implements Paint {
private TexturePaint texture;
public OrientableTexturePaint(TexturePaint paint, float orientation)
{
texture = paint;
}
public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds, AffineTransform xform, RenderingHints hints)
{
return texture.createContext(cm, deviceBounds, userBounds, xform, hints);
}
public int getTransparency()
{
return texture.getTransparency();
}
}
performs massively worse than TexturePaint does. How come, and is there any way to get around this?
I would paint the rotated portion to a BufferedImage and then paint that to the background. Then you only have to update the BufferedImage when there is a change to the rotated portions.
If you don't create a cache this way, if you do the painting from scratch each time, you have to consider the pipeline of the paint model and how complex that is. Performance is about reducing the bottlenecks in the rendering pipeline, and passing everything through a texturepaint process sounds like a massive bottleneck. Textures are to be created once, used often, not created often, used once.

Categories