How to get FPS in JOGL? - java

I currently trying to output my FPS using JOGL, to no avail. I have tried many things such as
glAutoDrawable.getAnimator().getLastFPS() but it returns 0.0. I have also tried using glAutoDrawable.getAnimator().setUpdateFPSFrames(3, System.out); but it never logs the FPS. I am trying to get the FPS of the ENTIRE application, not a animation.
I have checked Jogl animator always says FPS is 0 but this requires a Animator object which I am not using. When using a new Animator (glAutoDrawable.setAnimator(new Animator());) the FPS still returns 0.0.
Here is the code that I am using:
package ***.core.graphics;
import com.jogamp.opengl.*;
import com.jogamp.opengl.util.Animator;
import ***.log.Log;
import ***.tests.utils.GameTestMethods;
public class GameCanvas implements GLEventListener{
...
#Override
public void display(GLAutoDrawable glAutoDrawable) {
GL2 glDraw = glAutoDrawable.getGL().getGL2();
gameTestMethods.onRender(glDraw); // Draws a rectangle, not the issue.
Log.log(Log.LogLevel.DEBUG, "FPS: "+glAutoDrawable.getAnimator().getLastFPS());//Trying to log FPS, returns 0.0 every time.
}
#Override
public void init(GLAutoDrawable glAutoDrawable) {
glAutoDrawable.setAnimator(new Animator()); // No clue what i'm doing here...
glAutoDrawable.getAnimator().setUpdateFPSFrames(3, System.out); // NEVER logs FPS...
}
...
}
Would this be possible, or would I need my own FPS counter?

Related

My Tiled map is not being rendered in libgdx

I have spent the past couple of days trying to figure out what is wrong with my code. Im trying to render a tile map (.tmx) in libgdx but it does not render and it just shows a red screen with no error. I have re-written the code a few times and I always getting the same result.
my code:
public class Main extends ApplicationAdapter {
SpriteBatch batch;
TiledMap map;
TmxMapLoader loader;
OrthogonalTiledMapRenderer renderer;
OrthographicCamera camera;
#Override
public void create () {
batch = new SpriteBatch();
loader = new TmxMapLoader();
map = loader.load("TiledMaps/TestMap.tmx");
renderer = new OrthogonalTiledMapRenderer(map);
camera = new OrthographicCamera();
camera.setToOrtho(false,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
}
#Override
public void render () {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
renderer.setView(camera);
renderer.render();
batch.begin();
batch.end();
}
#Override
public void dispose () {
batch.dispose();
renderer.dispose();
map.dispose();
}
}
Can anybody find what is happening here I have the tmx file with the tilesheet in the TileMaps folder in the android assets folder.
Any help is appreciated, Thanks in advance.
If I understand correctly, you're attempting something complex (map rendering) but encountering a simple problem (not rendering anything).
Have you got a simple program where you do have something rendering? Built it up so you have a few hard coded tiles rendering? Built it up a bit more to correctly read and display the first tile from the map? Before finally extending it further to read and display all the tiles, once you know the basics are working?
That's how I would tackle this problem. Been programming for years, and just used the same process to get CreateProcess working in C++ on Windows. Wasn't working within my code so I built an empty project that just runs CreateProcess on notepad.exe and tweaked things with answers from StackOverflow.com till I got it working, now it's about adding back in the other complications bit by bit so I'm not completely lost by taking on too much at once.

Processing: Sketch gets stuck when using Capture class

I'm using Processing 2.0.3 on Windows 8. I tried to use the following code but I've no idea why my sketch couldn't run when I'm using the processing.video.* library:
import processing.video.*;
Capture cam;
void setup() {
size(200, 200);
cam = new Capture(this);
cam.start();
}
void draw() {
if (cam.available()) {
// Reads the new frame
cam.read();
}
image(cam, 0, 0);
}
I notice that the sketch will get stuck and will not open the sketch applet window at all if I call anything related to the Capture class. Calling println(Capture.list()); for example will cause the sketch to stuck at where ever that line was called.
What do I have to do to resolve this problem?

Disable screen saver / sleep mode through a website

I am working on a web application that needs to be active on the monitor sometimes for hours without anyone touch the computer.
The problem is that some computers have their screen saver, or worse - sleep mode while their inactive.
I'm trying to think of a way to bypass it. I searched for java applets or maybe a flash file that does only that. I found nothing, unfortunately.
I'm sorry for the too general question but I'm pretty helpless with this subject
I've written the Java applet for you. It will move the mouse cursor one pixel to the right and back every 59 seconds, effectively preventing the screen saver from kicking in.
Note that because of security restrictions this applet will need to be signed and granted the createRobot permission to work on the client, otherwise it will fail to initialize the Robot class. But that's a problem outside this question's scope.
import java.applet.Applet;
import java.awt.*;
import java.util.Timer;
import java.util.TimerTask;
/**
* Moves the mouse cursor once in a minute to prevent the screen saver from
* kicking in.
*/
public class ScreenSaverDisablerApplet extends Applet {
private static final int PERIOD = 59;
private Timer screenSaverDisabler;
#Override
public void start() {
screenSaverDisabler = new Timer();
screenSaverDisabler.scheduleAtFixedRate(new TimerTask() {
Robot r = null;
{
try {
r = new Robot();
} catch (AWTException headlessEnvironmentException) {
screenSaverDisabler.cancel();
}
}
#Override
public void run() {
Point loc = MouseInfo.getPointerInfo().getLocation();
r.mouseMove(loc.x + 1, loc.y);
r.mouseMove(loc.x, loc.y);
}
}, 0, PERIOD*1000);
}
#Override
public void stop() {
screenSaverDisabler.cancel();
}
}

Java ImageIcon.GetImage hanging

I am having trouble with ImageIcon().GetImage()
The strange thing is, is that it sometimes works and shows me the window with the maps on it, and other times it doesn't. It also works on other computers flawlessly but not on mine!
I have tried everything, reinstalling Java, reinstalling IntelliJ, also disabling my firewall, but to no avail. I have also written a similar program in C# which works perfectly, which leads me to believe it isn't a permissions error. I have also tested it on a basic Windows XP system with an on board graphics card which also works perfectly.
Here is my code:
public class main {
public static void main(String[] args) {
System.out.println("Running main..");
try
{
URL url = new URL("http://maps.googleapis.com/maps/api/staticmap?center=-33.80382155278416,18.567184266922002&zoom=17&size=1024x1024&maptype=hybrid&sensor=false&format=png&key=AIzaSyCVnp9iTXRSS3ZE5FjzF7uNZavazWhLko4");
Image img=new ImageIcon(url).getImage();
System.out.println("INFO :"+img);
new ImageFrame(img);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static class ImageFrame extends JFrame{
public ImageFrame(Image img){
setPreferredSize(new Dimension(540, 480));
setaImg(img);
ImagePanel somePanel = new ImagePanel(540, 480);
add(somePanel);
setVisible(true);
}
private Image aImg;
public Image getaImg() {
return aImg;
}
public void setaImg(Image aImg) {
this.aImg = aImg;
}
public class ImagePanel extends JPanel{
public ImagePanel(int width, int height){
setPreferredSize(new Dimension(width, height));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(getaImg(), 0, 0, null); // see javadoc for more info on the parameters
}
}
}
}
I have ran it through the step through debugger and it stops at this line:
Image img=new ImageIcon(url).getImage();
But with no error, it just hangs forever.
I am totally confused as to why it isn't working on my system, and only my system. Any help would be GREATLY appreciated.
Works fine for me
Google's not blocking you are they? From memory you have something like 10,000 queries a day or something.
Try downloading the URL manually using the InputStream (URL.openStream()) and see if you're getting some kind of response other than an image binary.
UPDATED
After investigation, found to be a problem with Java 7 and IPv6 as documented here Downloading files using Java randomly freezes
Always start and update the GUI on the EDT. See Concurrency in Swing for more details.
g.drawImage(getaImg(), 0, 0, null); // see javadoc for more info on the parameters
That comment is very good advice, since a 4 char edit should fix the problem.
g.drawImage(getaImg(), 0, 0, this); // Observer is good for asynchronous image load

Real-time graphing in Java

I have an application which updates a variable about between 5 to 50 times a second and I am looking for some way of drawing a continuous XY plot of this change in real-time.
Though JFreeChart is not recommended for such a high update rate, many users still say that it works for them. I've tried using this demo and modified it to display a random variable, but it seems to use up 100% CPU usage all the time. Even if I ignore that, I do not want to be restricted to JFreeChart's ui class for constructing forms (though I'm not sure what its capabilities are exactly). Would it be possible to integrate it with Java's "forms" and drop-down menus? (as are available in VB) Otherwise, are there any alternatives I could look into?
EDIT: I'm new to Swing, so I've put together a code just to test the functionality of JFreeChart with it (while avoiding the use of the ApplicationFrame class of JFree since I'm not sure how that will work with Swing's combo boxes and buttons). Right now, the graph is being updated immediately and CPU usage is high. Would it be possible to buffer the value with new Millisecond() and update it maybe twice a second? Also, can I add other components to the rest of the JFrame without disrupting JFreeChart? How would I do that? frame.getContentPane().add(new Button("Click")) seems to overwrite the graph.
package graphtest;
import java.util.Random;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
public class Main {
static TimeSeries ts = new TimeSeries("data", Millisecond.class);
public static void main(String[] args) throws InterruptedException {
gen myGen = new gen();
new Thread(myGen).start();
TimeSeriesCollection dataset = new TimeSeriesCollection(ts);
JFreeChart chart = ChartFactory.createTimeSeriesChart(
"GraphTest",
"Time",
"Value",
dataset,
true,
true,
false
);
final XYPlot plot = chart.getXYPlot();
ValueAxis axis = plot.getDomainAxis();
axis.setAutoRange(true);
axis.setFixedAutoRange(60000.0);
JFrame frame = new JFrame("GraphTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ChartPanel label = new ChartPanel(chart);
frame.getContentPane().add(label);
//Suppose I add combo boxes and buttons here later
frame.pack();
frame.setVisible(true);
}
static class gen implements Runnable {
private Random randGen = new Random();
public void run() {
while(true) {
int num = randGen.nextInt(1000);
System.out.println(num);
ts.addOrUpdate(new Millisecond(), num);
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}
}
If your variable is updating that fast, there's no point in updating a chart every time.
Have you thought about buffering the variable changes, and refreshing the chart on a different thread, say, every 5s ? You should find that JFreeChart can handle such update rates well.
Since JFreeChart is a normal desktop library, you can integrate it with a standard Swing application very easily. Or, you can use it to chart via a web application (by rendering to a JPEG/PNG etc. JFreeChart can generate image maps automatically as well, so you can use mouseovers etc.)
In order to get your CPU well below 100% and allow your GUI to remain responsive, you have to throttle back your chart updating rate. A maximum update rate of around 24 frames per second makes sense for a real-time chart; any faster is more or less indistinguishable anyway. If your data is coming in faster than that rate, you just need to buffer it in the background and update your chart in the foreground at your desired update rate. In the following example, I use XChart along with a SwingWorker background thread. The data capture is simulated at a rate of one per every 5 ms and the chart is updated at 24 frames per second. This concept should work with JFreeCharts or any other charting library as well with slight modification. Disclaimer: I'm the lead developer of XChart.
import java.util.LinkedList;
import java.util.List;
import javax.swing.SwingWorker;
import org.knowm.xchart.QuickChart;
import org.knowm.xchart.SwingWrapper;
import org.knowm.xchart.XYChart;
/**
* Creates a real-time chart using SwingWorker
*/
public class SwingWorkerRealTime {
MySwingWorker mySwingWorker;
SwingWrapper<XYChart> sw;
XYChart chart;
public static void main(String[] args) throws Exception {
SwingWorkerRealTime swingWorkerRealTime = new SwingWorkerRealTime();
swingWorkerRealTime.go();
}
private void go() {
// Create Chart
chart = QuickChart.getChart("SwingWorker XChart Real-time Demo", "Time", "Value", "randomWalk", new double[] { 0 }, new double[] { 0 });
chart.getStyler().setLegendVisible(false);
chart.getStyler().setXAxisTicksVisible(false);
// Show it
sw = new SwingWrapper<XYChart>(chart);
sw.displayChart();
mySwingWorker = new MySwingWorker();
mySwingWorker.execute();
}
private class MySwingWorker extends SwingWorker<Boolean, double[]> {
LinkedList<Double> fifo = new LinkedList<Double>();
public MySwingWorker() {
fifo.add(0.0);
}
#Override
protected Boolean doInBackground() throws Exception {
while (!isCancelled()) {
fifo.add(fifo.get(fifo.size() - 1) + Math.random() - .5);
if (fifo.size() > 500) {
fifo.removeFirst();
}
double[] array = new double[fifo.size()];
for (int i = 0; i < fifo.size(); i++) {
array[i] = fifo.get(i);
}
publish(array);
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// eat it. caught when interrupt is called
System.out.println("MySwingWorker shut down.");
}
}
return true;
}
#Override
protected void process(List<double[]> chunks) {
System.out.println("number of chunks: " + chunks.size());
double[] mostRecentDataSet = chunks.get(chunks.size() - 1);
chart.updateXYSeries("randomWalk", null, mostRecentDataSet, null);
sw.repaintChart();
long start = System.currentTimeMillis();
long duration = System.currentTimeMillis() - start;
try {
Thread.sleep(40 - duration); // 40 ms ==> 25fps
// Thread.sleep(400 - duration); // 40 ms ==> 2.5fps
} catch (InterruptedException e) {
}
}
}
}
According to this blog post:
http://jonathanwatmough.com/2008/02/prototyping-code-in-clojure/
its possible to implement 'real-ish time' display of audio spectrums using the KJ DSP library:
http://sirk.sytes.net/software/libs/kjdss/index.htm
so if you can get by with fairly simple charts it might be an alternative to JFreeChart.
If the data is updating more often than you can generate the chart, then you should have a task in a separate thread that regenerates the chart, and starts another regeneration when it's done. There's little point in running it ore often than that, but if it turns out to be too much of a cpu load, you can throttle back the frequency with which it restarts. If updates don't come in, you don't trigger the re-generate. I did something like that in my Zocalo project recently. It does everything but the throttling back.
package net.commerce.zocalo.freechart;
// Copyright 2009 Chris Hibbert. All rights reserved.
// This software is published under the terms of the MIT license, a copy
// of which has been included with this distribution in the LICENSE file.
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.Map;
import java.util.HashMap;
/** Schedule a task like generating a price history graph. Multiple requests may come
in sporadically. We want to ensure that only one is being processed at a time. If we're
busy processing when a request comes in, we'll remember to start another when this one is
done. Multiple requests that come in while processing will spur a single restart. */
public class ChartScheduler {
static private Logger log = Logger.getLogger(ChartScheduler.class);
static private Map<String, ChartScheduler> schedulers = new HashMap<String, ChartScheduler>();
private AtomicBoolean generating = new AtomicBoolean(false);
private AtomicBoolean requested = new AtomicBoolean(false);
private ExecutorService threads = Executors.newCachedThreadPool();
private Callable<Boolean> callable;
private int runs = 0;
private String name;
private ChartScheduler(String name, final Runnable worker) {
this.name = name;
callable = new Callable<Boolean>() {
public Boolean call() throws Exception {
worker.run();
runs++;
restartIfNeeded();
return true;
}
};
}
public static ChartScheduler create(String name, Runnable worker) {
ChartScheduler sched = find(name);
if (sched == null) {
sched = new ChartScheduler(name, worker);
schedulers.put(name, sched);
}
return sched;
}
public static ChartScheduler find(String name) {
return schedulers.get(name);
}
public boolean generateNewChart() {
requested.set(true);
if (generating.compareAndSet(false, true)) {
startNewThread();
return true;
} else {
return false;
}
}
private Future<Boolean> startNewThread() {
generating.set(true);
requested.set(false);
return threads.submit(callable);
}
private boolean restartIfNeeded() {
generating.set(false);
if (requested.get()) {
return generateNewChart();
} else {
return false;
}
}
public boolean isBusy() {
return generating.get();
}
public int runs() {
return runs;
}
}
Answered before here. Your variable changes up to 50 times per second, but in most cases you won't need to update every time a change is made. Instead you could update the graph at regular intervals (every 100ms for instance).
Well I am also using JFreechart for high updates. JFreeChart updates up to 10 to 15 frame/second but using 100% CPU usage. But if I want to update it at a much higher frequency it wont be updated. If you find any any library which can be updated at abt 20 fps and can be used to develop a application in Java then please suggest me also. I have seen many library JFreeChart FAQ but I am not sure if anyone could be use for updates at about 20 fps.
You should try out charts from VisualVM (part of JDK).
Intro on it: http://java.dzone.com/news/real-time-charts-java-desktop
Maybe you can use two threads. One for the updating of your variable witch priority equals to 10.
And a second thread who paints so fast as posible witch priority equals to 5.
I had to do the same in a game I'm writing.
It's possible I didn't understand your question.

Categories

Resources